text
stringlengths 54
60.6k
|
|---|
<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 "chrome/common/extensions/extension_process_policy.h"
#include "chrome/common/extensions/extension_set.h"
namespace extensions {
const Extension* GetNonBookmarkAppExtension(
const ExtensionSet& extensions, const ExtensionURLInfo& url) {
// Exclude bookmark apps, which do not use the app process model.
const Extension* extension = extensions.GetExtensionOrAppByURL(url);
if (extension && extension->from_bookmark())
extension = NULL;
return extension;
}
bool CrossesExtensionProcessBoundary(
const ExtensionSet& extensions,
const ExtensionURLInfo& old_url,
const ExtensionURLInfo& new_url) {
const Extension* old_url_extension = GetNonBookmarkAppExtension(extensions,
old_url);
const Extension* new_url_extension = GetNonBookmarkAppExtension(extensions,
new_url);
// TODO(creis): Temporary workaround for crbug.com/59285: Only return true if
// we would enter an extension app's extent from a non-app, or if we leave an
// extension with no web extent. We avoid swapping processes to exit a hosted
// app for now, since we do not yet support postMessage calls from outside the
// app back into it (e.g., as in Facebook OAuth 2.0).
bool old_url_is_hosted_app = old_url_extension &&
!old_url_extension->web_extent().is_empty();
if (old_url_is_hosted_app)
return false;
return old_url_extension != new_url_extension;
}
} // namespace extensions
<commit_msg>Exclude extensions and Chrome Web Store from hosted app process workaround.<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 "chrome/common/extensions/extension_process_policy.h"
#include "chrome/common/extensions/extension_set.h"
namespace extensions {
const Extension* GetNonBookmarkAppExtension(
const ExtensionSet& extensions, const ExtensionURLInfo& url) {
// Exclude bookmark apps, which do not use the app process model.
const Extension* extension = extensions.GetExtensionOrAppByURL(url);
if (extension && extension->from_bookmark())
extension = NULL;
return extension;
}
bool CrossesExtensionProcessBoundary(
const ExtensionSet& extensions,
const ExtensionURLInfo& old_url,
const ExtensionURLInfo& new_url) {
const Extension* old_url_extension = GetNonBookmarkAppExtension(extensions,
old_url);
const Extension* new_url_extension = GetNonBookmarkAppExtension(extensions,
new_url);
// TODO(creis): Temporary workaround for crbug.com/59285: Do not swap process
// to navigate from a hosted app to a normal page or another hosted app
// (unless either is the web store). This is because we do not yet support
// postMessage calls from outside the app back into it (e.g., as in Facebook
// OAuth 2.0). This will be removed when http://crbug.com/99202 is fixed.
bool old_url_is_hosted_app = old_url_extension &&
!old_url_extension->web_extent().is_empty();
bool new_url_is_normal_or_hosted = !new_url_extension ||
!new_url_extension->web_extent().is_empty();
bool either_is_web_store =
(old_url_extension &&
old_url_extension->id() == extension_misc::kWebStoreAppId) ||
(new_url_extension &&
new_url_extension->id() == extension_misc::kWebStoreAppId);
if (old_url_is_hosted_app &&
new_url_is_normal_or_hosted &&
!either_is_web_store)
return false;
return old_url_extension != new_url_extension;
}
} // namespace extensions
<|endoftext|>
|
<commit_before>#ifndef CPIMPL
#define CPIMPL
#include<memory> //make_unique, unique_ptr
#include<utility> //forward, move
#include<type_traits> //is_nothrow_assignable
namespace nTool
{
template<class T>
class CPimpl //a class to help you use pimpl easily
{
std::unique_ptr<T> p_;
public:
CPimpl()
:p_{std::make_unique<T>()}{}
CPimpl(const CPimpl &val)
:p_{std::make_unique<T>(val.get())}{}
CPimpl(CPimpl &&rVal) noexcept
:p_{std::move(rVal.p_)}{}
//as smart pointer, use () instead of {}
template<class ... Args>
CPimpl(Args &&...args)
:p_(std::make_unique<T>(std::forward<Args>(args)...)){}
inline T& get() const noexcept
{
return *p_;
}
CPimpl& operator=(const CPimpl &val) noexcept(std::is_nothrow_assignable<T,T&>::value)
{
get()=val.get();
return *this;
}
CPimpl& operator=(CPimpl &&rVal) noexcept
{
p_=std::move(rVal.p_);
return *this;
}
explicit operator bool() const noexcept
{
return p_.operator bool();
}
~CPimpl(){}
};
}
#endif<commit_msg>reorder code<commit_after>#ifndef CPIMPL
#define CPIMPL
#include<memory> //make_unique, unique_ptr
#include<utility> //forward, move
#include<type_traits> //is_nothrow_assignable
namespace nTool
{
template<class T>
class CPimpl //a class to help you use pimpl easily
{
std::unique_ptr<T> p_;
public:
CPimpl()
:p_{std::make_unique<T>()}{}
CPimpl(const CPimpl &val)
:p_{std::make_unique<T>(val.get())}{}
CPimpl(CPimpl &&rVal) noexcept
:p_{std::move(rVal.p_)}{}
//as smart pointer, use () instead of {}
template<class ... Args>
CPimpl(Args &&...args)
:p_(std::make_unique<T>(std::forward<Args>(args)...)){}
inline T& get() const noexcept
{
return *p_;
}
explicit operator bool() const noexcept
{
return p_.operator bool();
}
CPimpl& operator=(const CPimpl &val) noexcept(std::is_nothrow_assignable<T,T&>::value)
{
get()=val.get();
return *this;
}
CPimpl& operator=(CPimpl &&rVal) noexcept
{
p_=std::move(rVal.p_);
return *this;
}
~CPimpl(){}
};
}
#endif<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012-2013 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Thomas Grass
* Andreas Hansson
* Sascha Bischoff
*/
#include <sstream>
#include "base/random.hh"
#include "cpu/testers/traffic_gen/traffic_gen.hh"
#include "debug/Checkpoint.hh"
#include "debug/TrafficGen.hh"
#include "sim/stats.hh"
#include "sim/system.hh"
using namespace std;
TrafficGen::TrafficGen(const TrafficGenParams* p)
: MemObject(p),
system(p->system),
masterID(system->getMasterId(name())),
configFile(p->config_file),
elasticReq(p->elastic_req),
nextTransitionTick(0),
nextPacketTick(0),
port(name() + ".port", *this),
retryPkt(NULL),
retryPktTick(0),
updateEvent(this),
drainManager(NULL)
{
}
TrafficGen*
TrafficGenParams::create()
{
return new TrafficGen(this);
}
BaseMasterPort&
TrafficGen::getMasterPort(const string& if_name, PortID idx)
{
if (if_name == "port") {
return port;
} else {
return MemObject::getMasterPort(if_name, idx);
}
}
void
TrafficGen::init()
{
if (!port.isConnected())
fatal("The port of %s is not connected!\n", name());
// if the system is in timing mode active the request generator
if (system->isTimingMode()) {
DPRINTF(TrafficGen, "Timing mode, activating request generator\n");
parseConfig();
// enter initial state
enterState(currState);
} else {
DPRINTF(TrafficGen,
"Traffic generator is only active in timing mode\n");
}
}
void
TrafficGen::initState()
{
// when not restoring from a checkpoint, make sure we kick things off
if (system->isTimingMode()) {
// call nextPacketTick on the state to advance it
nextPacketTick = states[currState]->nextPacketTick(elasticReq, 0);
schedule(updateEvent, std::min(nextPacketTick, nextTransitionTick));
} else {
DPRINTF(TrafficGen,
"Traffic generator is only active in timing mode\n");
}
}
unsigned int
TrafficGen::drain(DrainManager *dm)
{
if (retryPkt == NULL) {
// shut things down
nextPacketTick = MaxTick;
nextTransitionTick = MaxTick;
deschedule(updateEvent);
return 0;
} else {
drainManager = dm;
return 1;
}
}
void
TrafficGen::serialize(ostream &os)
{
DPRINTF(Checkpoint, "Serializing TrafficGen\n");
// save ticks of the graph event if it is scheduled
Tick nextEvent = updateEvent.scheduled() ? updateEvent.when() : 0;
DPRINTF(TrafficGen, "Saving nextEvent=%llu\n", nextEvent);
SERIALIZE_SCALAR(nextEvent);
SERIALIZE_SCALAR(nextTransitionTick);
SERIALIZE_SCALAR(nextPacketTick);
SERIALIZE_SCALAR(currState);
}
void
TrafficGen::unserialize(Checkpoint* cp, const string& section)
{
// restore scheduled events
Tick nextEvent;
UNSERIALIZE_SCALAR(nextEvent);
if (nextEvent != 0) {
schedule(updateEvent, nextEvent);
}
UNSERIALIZE_SCALAR(nextTransitionTick);
UNSERIALIZE_SCALAR(nextPacketTick);
// @todo In the case of a stateful generator state such as the
// trace player we would also have to restore the position in the
// trace playback and the tick offset
UNSERIALIZE_SCALAR(currState);
}
void
TrafficGen::update()
{
// if we have reached the time for the next state transition, then
// perform the transition
if (curTick() >= nextTransitionTick) {
transition();
} else {
assert(curTick() >= nextPacketTick);
// get the next packet and try to send it
PacketPtr pkt = states[currState]->getNextPacket();
numPackets++;
if (!port.sendTimingReq(pkt)) {
retryPkt = pkt;
retryPktTick = curTick();
}
}
// if we are waiting for a retry, do not schedule any further
// events, in the case of a transition or a successful send, go
// ahead and determine when the next update should take place
if (retryPkt == NULL) {
// schedule next update event based on either the next execute
// tick or the next transition, which ever comes first
nextPacketTick = states[currState]->nextPacketTick(elasticReq, 0);
Tick nextEventTick = std::min(nextPacketTick, nextTransitionTick);
DPRINTF(TrafficGen, "Next event scheduled at %lld\n", nextEventTick);
schedule(updateEvent, nextEventTick);
}
}
void
TrafficGen::parseConfig()
{
// keep track of the transitions parsed to create the matrix when
// done
vector<Transition> transitions;
// open input file
ifstream infile;
infile.open(configFile.c_str(), ifstream::in);
if (!infile.is_open()) {
fatal("Traffic generator %s config file not found at %s\n",
name(), configFile);
}
// read line by line and determine the action based on the first
// keyword
string keyword;
string line;
while (getline(infile, line).good()) {
// see if this line is a comment line, and if so skip it
if (line.find('#') != 1) {
// create an input stream for the tokenization
istringstream is(line);
// determine the keyword
is >> keyword;
if (keyword == "STATE") {
// parse the behaviour of this state
uint32_t id;
Tick duration;
string mode;
is >> id >> duration >> mode;
if (mode == "TRACE") {
string traceFile;
Addr addrOffset;
is >> traceFile >> addrOffset;
states[id] = new TraceGen(name(), masterID, duration,
traceFile, addrOffset);
DPRINTF(TrafficGen, "State: %d TraceGen\n", id);
} else if (mode == "IDLE") {
states[id] = new IdleGen(name(), masterID, duration);
DPRINTF(TrafficGen, "State: %d IdleGen\n", id);
} else if (mode == "LINEAR" || mode == "RANDOM") {
uint32_t read_percent;
Addr start_addr;
Addr end_addr;
Addr blocksize;
Tick min_period;
Tick max_period;
Addr data_limit;
is >> read_percent >> start_addr >> end_addr >>
blocksize >> min_period >> max_period >> data_limit;
DPRINTF(TrafficGen, "%s, addr %x to %x, size %d,"
" period %d to %d, %d%% reads\n",
mode, start_addr, end_addr, blocksize, min_period,
max_period, read_percent);
if (blocksize > system->cacheLineSize())
fatal("TrafficGen %s block size (%d) is larger than "
"system block size (%d)\n", name(),
blocksize, system->cacheLineSize());
if (read_percent > 100)
fatal("%s cannot have more than 100% reads", name());
if (min_period > max_period)
fatal("%s cannot have min_period > max_period", name());
if (mode == "LINEAR") {
states[id] = new LinearGen(name(), masterID,
duration, start_addr,
end_addr, blocksize,
min_period, max_period,
read_percent, data_limit);
DPRINTF(TrafficGen, "State: %d LinearGen\n", id);
} else if (mode == "RANDOM") {
states[id] = new RandomGen(name(), masterID,
duration, start_addr,
end_addr, blocksize,
min_period, max_period,
read_percent, data_limit);
DPRINTF(TrafficGen, "State: %d RandomGen\n", id);
}
} else {
fatal("%s: Unknown traffic generator mode: %s",
name(), mode);
}
} else if (keyword == "TRANSITION") {
Transition transition;
is >> transition.from >> transition.to >> transition.p;
transitions.push_back(transition);
DPRINTF(TrafficGen, "Transition: %d -> %d\n", transition.from,
transition.to);
} else if (keyword == "INIT") {
// set the initial state as the active state
is >> currState;
DPRINTF(TrafficGen, "Initial state: %d\n", currState);
}
}
}
// resize and populate state transition matrix
transitionMatrix.resize(states.size());
for (size_t i = 0; i < states.size(); i++) {
transitionMatrix[i].resize(states.size());
}
for (vector<Transition>::iterator t = transitions.begin();
t != transitions.end(); ++t) {
transitionMatrix[t->from][t->to] = t->p;
}
// ensure the egress edges do not have a probability larger than
// one
for (size_t i = 0; i < states.size(); i++) {
double sum = 0;
for (size_t j = 0; j < states.size(); j++) {
sum += transitionMatrix[i][j];
}
// avoid comparing floating point numbers
if (abs(sum - 1.0) > 0.001)
fatal("%s has transition probability != 1 for state %d\n",
name(), i);
}
// close input file
infile.close();
}
void
TrafficGen::transition()
{
// exit the current state
states[currState]->exit();
// determine next state
double p = random_mt.gen_real1();
assert(currState < transitionMatrix.size());
double cumulative = 0.0;
size_t i = 0;
do {
cumulative += transitionMatrix[currState][i];
++i;
} while (cumulative < p && i < transitionMatrix[currState].size());
enterState(i - 1);
}
void
TrafficGen::enterState(uint32_t newState)
{
DPRINTF(TrafficGen, "Transition to state %d\n", newState);
currState = newState;
// we could have been delayed and not transitioned on the exact
// tick when we were supposed to (due to back pressure when
// sending a packet)
nextTransitionTick = curTick() + states[currState]->duration;
states[currState]->enter();
}
void
TrafficGen::recvRetry()
{
assert(retryPkt != NULL);
DPRINTF(TrafficGen, "Received retry\n");
numRetries++;
// attempt to send the packet, and if we are successful start up
// the machinery again
if (port.sendTimingReq(retryPkt)) {
retryPkt = NULL;
// remember how much delay was incurred due to back-pressure
// when sending the request, we also use this to derive
// the tick for the next packet
Tick delay = curTick() - retryPktTick;
retryPktTick = 0;
retryTicks += delay;
if (drainManager == NULL) {
// packet is sent, so find out when the next one is due
nextPacketTick = states[currState]->nextPacketTick(elasticReq,
delay);
Tick nextEventTick = std::min(nextPacketTick, nextTransitionTick);
schedule(updateEvent, std::max(curTick(), nextEventTick));
} else {
// shut things down
nextPacketTick = MaxTick;
nextTransitionTick = MaxTick;
drainManager->signalDrainDone();
// Clear the drain event once we're done with it.
drainManager = NULL;
}
}
}
void
TrafficGen::regStats()
{
// Initialise all the stats
using namespace Stats;
numPackets
.name(name() + ".numPackets")
.desc("Number of packets generated");
numRetries
.name(name() + ".numRetries")
.desc("Number of retries");
retryTicks
.name(name() + ".retryTicks")
.desc("Time spent waiting due to back-pressure (ticks)");
}
bool
TrafficGen::TrafficGenPort::recvTimingResp(PacketPtr pkt)
{
delete pkt->req;
delete pkt;
return true;
}
<commit_msg>cpu: fix bug when TrafficGen deschedules event<commit_after>/*
* Copyright (c) 2012-2013 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Thomas Grass
* Andreas Hansson
* Sascha Bischoff
*/
#include <sstream>
#include "base/random.hh"
#include "cpu/testers/traffic_gen/traffic_gen.hh"
#include "debug/Checkpoint.hh"
#include "debug/TrafficGen.hh"
#include "sim/stats.hh"
#include "sim/system.hh"
using namespace std;
TrafficGen::TrafficGen(const TrafficGenParams* p)
: MemObject(p),
system(p->system),
masterID(system->getMasterId(name())),
configFile(p->config_file),
elasticReq(p->elastic_req),
nextTransitionTick(0),
nextPacketTick(0),
port(name() + ".port", *this),
retryPkt(NULL),
retryPktTick(0),
updateEvent(this),
drainManager(NULL)
{
}
TrafficGen*
TrafficGenParams::create()
{
return new TrafficGen(this);
}
BaseMasterPort&
TrafficGen::getMasterPort(const string& if_name, PortID idx)
{
if (if_name == "port") {
return port;
} else {
return MemObject::getMasterPort(if_name, idx);
}
}
void
TrafficGen::init()
{
if (!port.isConnected())
fatal("The port of %s is not connected!\n", name());
// if the system is in timing mode active the request generator
if (system->isTimingMode()) {
DPRINTF(TrafficGen, "Timing mode, activating request generator\n");
parseConfig();
// enter initial state
enterState(currState);
} else {
DPRINTF(TrafficGen,
"Traffic generator is only active in timing mode\n");
}
}
void
TrafficGen::initState()
{
// when not restoring from a checkpoint, make sure we kick things off
if (system->isTimingMode()) {
// call nextPacketTick on the state to advance it
nextPacketTick = states[currState]->nextPacketTick(elasticReq, 0);
schedule(updateEvent, std::min(nextPacketTick, nextTransitionTick));
} else {
DPRINTF(TrafficGen,
"Traffic generator is only active in timing mode\n");
}
}
unsigned int
TrafficGen::drain(DrainManager *dm)
{
if (!updateEvent.scheduled()) {
// no event has been scheduled yet (e.g. switched from atomic mode)
return 0;
}
if (retryPkt == NULL) {
// shut things down
nextPacketTick = MaxTick;
nextTransitionTick = MaxTick;
deschedule(updateEvent);
return 0;
} else {
drainManager = dm;
return 1;
}
}
void
TrafficGen::serialize(ostream &os)
{
DPRINTF(Checkpoint, "Serializing TrafficGen\n");
// save ticks of the graph event if it is scheduled
Tick nextEvent = updateEvent.scheduled() ? updateEvent.when() : 0;
DPRINTF(TrafficGen, "Saving nextEvent=%llu\n", nextEvent);
SERIALIZE_SCALAR(nextEvent);
SERIALIZE_SCALAR(nextTransitionTick);
SERIALIZE_SCALAR(nextPacketTick);
SERIALIZE_SCALAR(currState);
}
void
TrafficGen::unserialize(Checkpoint* cp, const string& section)
{
// restore scheduled events
Tick nextEvent;
UNSERIALIZE_SCALAR(nextEvent);
if (nextEvent != 0) {
schedule(updateEvent, nextEvent);
}
UNSERIALIZE_SCALAR(nextTransitionTick);
UNSERIALIZE_SCALAR(nextPacketTick);
// @todo In the case of a stateful generator state such as the
// trace player we would also have to restore the position in the
// trace playback and the tick offset
UNSERIALIZE_SCALAR(currState);
}
void
TrafficGen::update()
{
// if we have reached the time for the next state transition, then
// perform the transition
if (curTick() >= nextTransitionTick) {
transition();
} else {
assert(curTick() >= nextPacketTick);
// get the next packet and try to send it
PacketPtr pkt = states[currState]->getNextPacket();
numPackets++;
if (!port.sendTimingReq(pkt)) {
retryPkt = pkt;
retryPktTick = curTick();
}
}
// if we are waiting for a retry, do not schedule any further
// events, in the case of a transition or a successful send, go
// ahead and determine when the next update should take place
if (retryPkt == NULL) {
// schedule next update event based on either the next execute
// tick or the next transition, which ever comes first
nextPacketTick = states[currState]->nextPacketTick(elasticReq, 0);
Tick nextEventTick = std::min(nextPacketTick, nextTransitionTick);
DPRINTF(TrafficGen, "Next event scheduled at %lld\n", nextEventTick);
schedule(updateEvent, nextEventTick);
}
}
void
TrafficGen::parseConfig()
{
// keep track of the transitions parsed to create the matrix when
// done
vector<Transition> transitions;
// open input file
ifstream infile;
infile.open(configFile.c_str(), ifstream::in);
if (!infile.is_open()) {
fatal("Traffic generator %s config file not found at %s\n",
name(), configFile);
}
// read line by line and determine the action based on the first
// keyword
string keyword;
string line;
while (getline(infile, line).good()) {
// see if this line is a comment line, and if so skip it
if (line.find('#') != 1) {
// create an input stream for the tokenization
istringstream is(line);
// determine the keyword
is >> keyword;
if (keyword == "STATE") {
// parse the behaviour of this state
uint32_t id;
Tick duration;
string mode;
is >> id >> duration >> mode;
if (mode == "TRACE") {
string traceFile;
Addr addrOffset;
is >> traceFile >> addrOffset;
states[id] = new TraceGen(name(), masterID, duration,
traceFile, addrOffset);
DPRINTF(TrafficGen, "State: %d TraceGen\n", id);
} else if (mode == "IDLE") {
states[id] = new IdleGen(name(), masterID, duration);
DPRINTF(TrafficGen, "State: %d IdleGen\n", id);
} else if (mode == "LINEAR" || mode == "RANDOM") {
uint32_t read_percent;
Addr start_addr;
Addr end_addr;
Addr blocksize;
Tick min_period;
Tick max_period;
Addr data_limit;
is >> read_percent >> start_addr >> end_addr >>
blocksize >> min_period >> max_period >> data_limit;
DPRINTF(TrafficGen, "%s, addr %x to %x, size %d,"
" period %d to %d, %d%% reads\n",
mode, start_addr, end_addr, blocksize, min_period,
max_period, read_percent);
if (blocksize > system->cacheLineSize())
fatal("TrafficGen %s block size (%d) is larger than "
"system block size (%d)\n", name(),
blocksize, system->cacheLineSize());
if (read_percent > 100)
fatal("%s cannot have more than 100% reads", name());
if (min_period > max_period)
fatal("%s cannot have min_period > max_period", name());
if (mode == "LINEAR") {
states[id] = new LinearGen(name(), masterID,
duration, start_addr,
end_addr, blocksize,
min_period, max_period,
read_percent, data_limit);
DPRINTF(TrafficGen, "State: %d LinearGen\n", id);
} else if (mode == "RANDOM") {
states[id] = new RandomGen(name(), masterID,
duration, start_addr,
end_addr, blocksize,
min_period, max_period,
read_percent, data_limit);
DPRINTF(TrafficGen, "State: %d RandomGen\n", id);
}
} else {
fatal("%s: Unknown traffic generator mode: %s",
name(), mode);
}
} else if (keyword == "TRANSITION") {
Transition transition;
is >> transition.from >> transition.to >> transition.p;
transitions.push_back(transition);
DPRINTF(TrafficGen, "Transition: %d -> %d\n", transition.from,
transition.to);
} else if (keyword == "INIT") {
// set the initial state as the active state
is >> currState;
DPRINTF(TrafficGen, "Initial state: %d\n", currState);
}
}
}
// resize and populate state transition matrix
transitionMatrix.resize(states.size());
for (size_t i = 0; i < states.size(); i++) {
transitionMatrix[i].resize(states.size());
}
for (vector<Transition>::iterator t = transitions.begin();
t != transitions.end(); ++t) {
transitionMatrix[t->from][t->to] = t->p;
}
// ensure the egress edges do not have a probability larger than
// one
for (size_t i = 0; i < states.size(); i++) {
double sum = 0;
for (size_t j = 0; j < states.size(); j++) {
sum += transitionMatrix[i][j];
}
// avoid comparing floating point numbers
if (abs(sum - 1.0) > 0.001)
fatal("%s has transition probability != 1 for state %d\n",
name(), i);
}
// close input file
infile.close();
}
void
TrafficGen::transition()
{
// exit the current state
states[currState]->exit();
// determine next state
double p = random_mt.gen_real1();
assert(currState < transitionMatrix.size());
double cumulative = 0.0;
size_t i = 0;
do {
cumulative += transitionMatrix[currState][i];
++i;
} while (cumulative < p && i < transitionMatrix[currState].size());
enterState(i - 1);
}
void
TrafficGen::enterState(uint32_t newState)
{
DPRINTF(TrafficGen, "Transition to state %d\n", newState);
currState = newState;
// we could have been delayed and not transitioned on the exact
// tick when we were supposed to (due to back pressure when
// sending a packet)
nextTransitionTick = curTick() + states[currState]->duration;
states[currState]->enter();
}
void
TrafficGen::recvRetry()
{
assert(retryPkt != NULL);
DPRINTF(TrafficGen, "Received retry\n");
numRetries++;
// attempt to send the packet, and if we are successful start up
// the machinery again
if (port.sendTimingReq(retryPkt)) {
retryPkt = NULL;
// remember how much delay was incurred due to back-pressure
// when sending the request, we also use this to derive
// the tick for the next packet
Tick delay = curTick() - retryPktTick;
retryPktTick = 0;
retryTicks += delay;
if (drainManager == NULL) {
// packet is sent, so find out when the next one is due
nextPacketTick = states[currState]->nextPacketTick(elasticReq,
delay);
Tick nextEventTick = std::min(nextPacketTick, nextTransitionTick);
schedule(updateEvent, std::max(curTick(), nextEventTick));
} else {
// shut things down
nextPacketTick = MaxTick;
nextTransitionTick = MaxTick;
drainManager->signalDrainDone();
// Clear the drain event once we're done with it.
drainManager = NULL;
}
}
}
void
TrafficGen::regStats()
{
// Initialise all the stats
using namespace Stats;
numPackets
.name(name() + ".numPackets")
.desc("Number of packets generated");
numRetries
.name(name() + ".numRetries")
.desc("Number of retries");
retryTicks
.name(name() + ".retryTicks")
.desc("Time spent waiting due to back-pressure (ticks)");
}
bool
TrafficGen::TrafficGenPort::recvTimingResp(PacketPtr pkt)
{
delete pkt->req;
delete pkt;
return true;
}
<|endoftext|>
|
<commit_before>#define GLM_SWIZZLE
#include "sound_system.hpp"
#include "../state/state_comp.hpp"
#include <core/units.hpp>
namespace mo {
namespace sys {
namespace sound {
using namespace unit_literals;
Sound_system::Sound_system(ecs::Entity_manager& entity_manager, physics::Transform_system& ts,
audio::Audio_ctx& audio_ctx) noexcept
: _transform(ts),
_audio_ctx(audio_ctx),
_sounds(entity_manager.list<Sound_comp>())
{
entity_manager.register_component_type<Sound_comp>();
}
namespace {
auto determine_sound(Sound_comp& sc, state::State_comp& state) {
return sc.get_sound(static_cast<int>(state.state().s));
}
}
void Sound_system::play_sounds(const renderer::Camera& camera) noexcept {
auto cam_area = camera.area();
auto top_left = cam_area.xy();
auto bottom_right = cam_area.zw();
auto max_dist = glm::length(camera.viewport().zw()) / 2.f;
_transform.foreach_in_rect(top_left, bottom_right, [&](ecs::Entity& entity) {
process(entity.get<sys::physics::Transform_comp>(),
entity.get<sys::sound::Sound_comp>(),
entity.get<sys::state::State_comp>())
>> [&](const physics::Transform_comp& trans, Sound_comp& sc, state::State_comp& state) {
auto sound = determine_sound(sc, state);
if(sound) {
auto p_entity = camera.viewport().zw()/2.f - camera.world_to_screen(remove_units(trans.position()));
auto angle = Angle(glm::atan(p_entity.y, p_entity.x));
DEBUG("angle in radians: " << angle);
DEBUG("angle in degrees:" << angle * (180.f / 3.1415f));
auto dist = glm::length(p_entity) / max_dist;
//if(dist<=1.0f) {
sc._channel = _audio_ctx.play_dynamic(*sound, angle, dist, false, sc._channel);
return;
//}
}
_audio_ctx.stop(sc._channel);
sc._channel = -1;
};
});
}
}
}
}
<commit_msg>removed DEBUG Code<commit_after>#define GLM_SWIZZLE
#include "sound_system.hpp"
#include "../state/state_comp.hpp"
#include <core/units.hpp>
namespace mo {
namespace sys {
namespace sound {
using namespace unit_literals;
Sound_system::Sound_system(ecs::Entity_manager& entity_manager, physics::Transform_system& ts,
audio::Audio_ctx& audio_ctx) noexcept
: _transform(ts),
_audio_ctx(audio_ctx),
_sounds(entity_manager.list<Sound_comp>())
{
entity_manager.register_component_type<Sound_comp>();
}
namespace {
auto determine_sound(Sound_comp& sc, state::State_comp& state) {
return sc.get_sound(static_cast<int>(state.state().s));
}
}
void Sound_system::play_sounds(const renderer::Camera& camera) noexcept {
auto cam_area = camera.area();
auto top_left = cam_area.xy();
auto bottom_right = cam_area.zw();
auto max_dist = glm::length(camera.viewport().zw()) / 2.f;
_transform.foreach_in_rect(top_left, bottom_right, [&](ecs::Entity& entity) {
process(entity.get<sys::physics::Transform_comp>(),
entity.get<sys::sound::Sound_comp>(),
entity.get<sys::state::State_comp>())
>> [&](const physics::Transform_comp& trans, Sound_comp& sc, state::State_comp& state) {
auto sound = determine_sound(sc, state);
if(sound) {
auto p_entity = camera.viewport().zw()/2.f - camera.world_to_screen(remove_units(trans.position()));
auto angle = Angle(glm::atan(p_entity.y, p_entity.x));
auto dist = glm::length(p_entity) / max_dist;
//if(dist<=1.0f) {
sc._channel = _audio_ctx.play_dynamic(*sound, angle, dist, false, sc._channel);
return;
//}
}
_audio_ctx.stop(sc._channel);
sc._channel = -1;
};
});
}
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <atlbase.h>
#include <atlcom.h>
#include "base/scoped_comptr_win.h"
#include "base/thread.h"
#include "chrome_frame/bho.h"
//#include "chrome_frame/urlmon_moniker.h"
#include "chrome_frame/test/test_server.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "chrome_frame/test/urlmon_moniker_tests.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#define GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING
#include "testing/gmock_mutant.h"
using testing::_;
using testing::CreateFunctor;
using testing::Eq;
using testing::Invoke;
using testing::SetArgumentPointee;
using testing::StrEq;
using testing::Return;
using testing::DoAll;
using testing::WithArgs;
static int kUrlmonMonikerTimeoutSec = 5;
namespace {
const char kTestContent[] = "<html><head>"
"<meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\" />"
"</head><body>Test HTML content</body></html>";
} // end namespace
class UrlmonMonikerTest : public testing::Test {
protected:
UrlmonMonikerTest() {
}
};
TEST_F(UrlmonMonikerTest, MonikerPatch) {
EXPECT_EQ(true, MonikerPatch::Initialize());
EXPECT_EQ(true, MonikerPatch::Initialize()); // Should be ok to call twice.
MonikerPatch::Uninitialize();
}
// Runs an HTTP server on a worker thread that has a message loop.
class RunTestServer : public base::Thread {
public:
RunTestServer()
: base::Thread("TestServer"),
default_response_("/", kTestContent),
ready_(::CreateEvent(NULL, TRUE, FALSE, NULL)) {
}
bool Start() {
bool ret = StartWithOptions(Options(MessageLoop::TYPE_UI, 0));
if (ret) {
message_loop()->PostTask(FROM_HERE,
NewRunnableFunction(&RunTestServer::StartServer, this));
wait_until_ready();
}
return ret;
}
static void StartServer(RunTestServer* me) {
me->server_.reset(new test_server::SimpleWebServer(43210));
me->server_->AddResponse(&me->default_response_);
::SetEvent(me->ready_);
}
bool wait_until_ready() {
return ::WaitForSingleObject(ready_, kUrlmonMonikerTimeoutSec * 1000)
== WAIT_OBJECT_0;
}
protected:
scoped_ptr<test_server::SimpleWebServer> server_;
test_server::SimpleResponse default_response_;
ScopedHandle ready_;
};
// Helper class for running tests that rely on the NavigationManager.
class UrlmonMonikerTestManager {
public:
explicit UrlmonMonikerTestManager(const wchar_t* test_url) {
EXPECT_EQ(true, MonikerPatch::Initialize());
}
~UrlmonMonikerTestManager() {
MonikerPatch::Uninitialize();
}
chrome_frame_test::TimedMsgLoop& loop() {
return loop_;
}
protected:
chrome_frame_test::TimedMsgLoop loop_;
};
ACTION_P(SetBindInfo, is_async) {
DWORD* flags = arg0;
BINDINFO* bind_info = arg1;
DCHECK(flags);
DCHECK(bind_info);
DCHECK(bind_info->cbSize >= sizeof(BINDINFO));
*flags = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA;
if (is_async)
*flags |= BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE;
bind_info->dwBindVerb = BINDVERB_GET;
memset(&bind_info->stgmedData, 0, sizeof(STGMEDIUM));
bind_info->grfBindInfoF = 0;
bind_info->szCustomVerb = NULL;
}
// Wraps the MockBindStatusCallbackImpl mock object and allows the user
// to specify expectations on the callback object.
class UrlmonMonikerTestCallback {
public:
explicit UrlmonMonikerTestCallback(UrlmonMonikerTestManager* mgr)
: mgr_(mgr), clip_format_(0) {
}
~UrlmonMonikerTestCallback() {
}
typedef enum GetBindInfoExpectations {
EXPECT_NO_CALL,
REQUEST_SYNCHRONOUS,
REQUEST_ASYNCHRONOUS,
} GET_BIND_INFO_EXPECTATION;
// Sets gmock expectations for the IBindStatusCallback mock object.
void SetCallbackExpectations(GetBindInfoExpectations bind_info_handling,
HRESULT data_available_response,
bool quit_loop_on_stop) {
EXPECT_CALL(callback_, OnProgress(_, _, _, _))
.WillRepeatedly(Return(S_OK));
if (bind_info_handling == REQUEST_ASYNCHRONOUS) {
EXPECT_CALL(callback_, GetBindInfo(_, _))
.WillOnce(DoAll(SetBindInfo(true), Return(S_OK)));
} else if (bind_info_handling == REQUEST_SYNCHRONOUS) {
EXPECT_CALL(callback_, GetBindInfo(_, _))
.WillOnce(DoAll(SetBindInfo(false), Return(S_OK)));
} else {
DCHECK(bind_info_handling == EXPECT_NO_CALL);
}
EXPECT_CALL(callback_, OnStartBinding(_, _))
.WillOnce(Return(S_OK));
EXPECT_CALL(callback_, OnDataAvailable(_, _, _, _))
.WillRepeatedly(Return(data_available_response));
if (quit_loop_on_stop) {
// When expecting asynchronous
EXPECT_CALL(callback_, OnStopBinding(data_available_response, _))
.WillOnce(DoAll(QUIT_LOOP(mgr_->loop()), Return(S_OK)));
} else {
EXPECT_CALL(callback_, OnStopBinding(data_available_response, _))
.WillOnce(Return(S_OK));
}
}
HRESULT CreateUrlMonikerAndBindToStorage(const wchar_t* url,
IBindCtx** bind_ctx) {
ScopedComPtr<IMoniker> moniker;
HRESULT hr = CreateURLMoniker(NULL, url, moniker.Receive());
EXPECT_TRUE(moniker != NULL);
if (moniker) {
ScopedComPtr<IBindCtx> context;
::CreateAsyncBindCtx(0, callback(), NULL, context.Receive());
DCHECK(context);
ScopedComPtr<IStream> stream;
hr = moniker->BindToStorage(context, NULL, IID_IStream,
reinterpret_cast<void**>(stream.Receive()));
if (SUCCEEDED(hr) && bind_ctx)
*bind_ctx = context.Detach();
}
return hr;
}
IBindStatusCallback* callback() {
return &callback_;
}
protected:
CComObjectStackEx<MockBindStatusCallbackImpl> callback_;
UrlmonMonikerTestManager* mgr_;
CLIPFORMAT clip_format_;
};
// Tests synchronously binding to a moniker and downloading the target.
TEST_F(UrlmonMonikerTest, BindToStorageSynchronous) {
const wchar_t test_url[] = L"http://localhost:43210/";
UrlmonMonikerTestManager test(test_url);
UrlmonMonikerTestCallback callback(&test);
RunTestServer server_thread;
EXPECT_TRUE(server_thread.Start());
callback.SetCallbackExpectations(
UrlmonMonikerTestCallback::REQUEST_SYNCHRONOUS, S_OK, false);
ScopedComPtr<IBindCtx> bind_ctx;
HRESULT hr = callback.CreateUrlMonikerAndBindToStorage(test_url,
bind_ctx.Receive());
// The download should have happened synchronously, so we don't expect
// MK_S_ASYNCHRONOUS or any errors.
EXPECT_EQ(S_OK, hr);
IBindCtx* release = bind_ctx.Detach();
EXPECT_EQ(0, release->Release());
server_thread.Stop();
}
// Tests asynchronously binding to a moniker and downloading the target.
TEST_F(UrlmonMonikerTest, BindToStorageAsynchronous) {
const wchar_t test_url[] = L"http://localhost:43210/";
UrlmonMonikerTestManager test(test_url);
UrlmonMonikerTestCallback callback(&test);
test_server::SimpleWebServer server(43210);
test_server::SimpleResponse default_response("/", kTestContent);
server.AddResponse(&default_response);
callback.SetCallbackExpectations(
UrlmonMonikerTestCallback::REQUEST_ASYNCHRONOUS, S_OK, true);
ScopedComPtr<IBindCtx> bind_ctx;
HRESULT hr = callback.CreateUrlMonikerAndBindToStorage(test_url,
bind_ctx.Receive());
EXPECT_EQ(MK_S_ASYNCHRONOUS, hr);
test.loop().RunFor(kUrlmonMonikerTimeoutSec);
IBindCtx* release = bind_ctx.Detach();
EXPECT_EQ(0, release->Release());
}
// Responds with the Chrome mime type.
class ResponseWithContentType : public test_server::SimpleResponse {
public:
ResponseWithContentType(const char* request_path,
const std::string& contents)
: test_server::SimpleResponse(request_path, contents) {
}
virtual bool GetContentType(std::string* content_type) const {
*content_type = WideToASCII(kChromeMimeType);
return true;
}
};
/*
// Downloads a document asynchronously and then verifies that the downloaded
// contents were cached and the cache contents are correct.
// TODO(tommi): Fix and re-enable.
// http://code.google.com/p/chromium/issues/detail?id=39415
TEST_F(UrlmonMonikerTest, BindToStorageSwitchContent) {
const wchar_t test_url[] = L"http://localhost:43210/";
UrlmonMonikerTestManager test(test_url);
UrlmonMonikerTestCallback callback(&test);
test_server::SimpleWebServer server(43210);
ResponseWithContentType default_response("/", kTestContent);
server.AddResponse(&default_response);
callback.SetCallbackExpectations(
UrlmonMonikerTestCallback::REQUEST_ASYNCHRONOUS, INET_E_TERMINATED_BIND,
true);
HRESULT hr = callback.CreateUrlMonikerAndBindToStorage(test_url, NULL);
EXPECT_EQ(MK_S_ASYNCHRONOUS, hr);
test.loop().RunFor(kUrlmonMonikerTimeoutSec);
scoped_refptr<RequestData> request_data(
test.nav_manager().GetActiveRequestData(test_url));
EXPECT_TRUE(request_data != NULL);
if (request_data) {
EXPECT_EQ(request_data->GetCachedContentSize(),
arraysize(kTestContent) - 1);
ScopedComPtr<IStream> stream;
request_data->GetResetCachedContentStream(stream.Receive());
EXPECT_TRUE(stream != NULL);
if (stream) {
char buffer[0xffff];
DWORD read = 0;
stream->Read(buffer, sizeof(buffer), &read);
EXPECT_EQ(read, arraysize(kTestContent) - 1);
EXPECT_EQ(0, memcmp(buffer, kTestContent, read));
}
}
}
// Fetches content asynchronously first to cache it and then
// verifies that fetching the cached content the same way works as expected
// and happens synchronously.
TEST_F(UrlmonMonikerTest, BindToStorageCachedContent) {
const wchar_t test_url[] = L"http://localhost:43210/";
UrlmonMonikerTestManager test(test_url);
UrlmonMonikerTestCallback callback(&test);
test_server::SimpleWebServer server(43210);
ResponseWithContentType default_response("/", kTestContent);
server.AddResponse(&default_response);
// First set of expectations. Download the contents
// asynchronously. This should populate the cache so that
// the second request should be served synchronously without
// going to the server.
callback.SetCallbackExpectations(
UrlmonMonikerTestCallback::REQUEST_ASYNCHRONOUS, INET_E_TERMINATED_BIND,
true);
HRESULT hr = callback.CreateUrlMonikerAndBindToStorage(test_url, NULL);
EXPECT_EQ(MK_S_ASYNCHRONOUS, hr);
test.loop().RunFor(kUrlmonMonikerTimeoutSec);
scoped_refptr<RequestData> request_data(
test.nav_manager().GetActiveRequestData(test_url));
EXPECT_TRUE(request_data != NULL);
if (request_data) {
// This time, just accept the content as normal.
UrlmonMonikerTestCallback callback2(&test);
callback2.SetCallbackExpectations(
UrlmonMonikerTestCallback::EXPECT_NO_CALL, S_OK, false);
hr = callback2.CreateUrlMonikerAndBindToStorage(test_url, NULL);
// S_OK means that the operation completed synchronously.
// Otherwise we'd get MK_S_ASYNCHRONOUS.
EXPECT_EQ(S_OK, hr);
}
}
*/
<commit_msg>Fix build by commenting the tests in UrlmonMonikerTest. I have to rewrite those tests anyway.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <atlbase.h>
#include <atlcom.h>
#include "base/scoped_comptr_win.h"
#include "base/thread.h"
#include "chrome_frame/bho.h"
//#include "chrome_frame/urlmon_moniker.h"
#include "chrome_frame/test/test_server.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "chrome_frame/test/urlmon_moniker_tests.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#define GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING
#include "testing/gmock_mutant.h"
using testing::_;
using testing::CreateFunctor;
using testing::Eq;
using testing::Invoke;
using testing::SetArgumentPointee;
using testing::StrEq;
using testing::Return;
using testing::DoAll;
using testing::WithArgs;
static int kUrlmonMonikerTimeoutSec = 5;
namespace {
const char kTestContent[] = "<html><head>"
"<meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\" />"
"</head><body>Test HTML content</body></html>";
} // end namespace
class UrlmonMonikerTest : public testing::Test {
protected:
UrlmonMonikerTest() {
}
};
TEST_F(UrlmonMonikerTest, MonikerPatch) {
EXPECT_EQ(true, MonikerPatch::Initialize());
EXPECT_EQ(true, MonikerPatch::Initialize()); // Should be ok to call twice.
MonikerPatch::Uninitialize();
}
// Runs an HTTP server on a worker thread that has a message loop.
class RunTestServer : public base::Thread {
public:
RunTestServer()
: base::Thread("TestServer"),
default_response_("/", kTestContent),
ready_(::CreateEvent(NULL, TRUE, FALSE, NULL)) {
}
bool Start() {
bool ret = StartWithOptions(Options(MessageLoop::TYPE_UI, 0));
if (ret) {
message_loop()->PostTask(FROM_HERE,
NewRunnableFunction(&RunTestServer::StartServer, this));
wait_until_ready();
}
return ret;
}
static void StartServer(RunTestServer* me) {
me->server_.reset(new test_server::SimpleWebServer(43210));
me->server_->AddResponse(&me->default_response_);
::SetEvent(me->ready_);
}
bool wait_until_ready() {
return ::WaitForSingleObject(ready_, kUrlmonMonikerTimeoutSec * 1000)
== WAIT_OBJECT_0;
}
protected:
scoped_ptr<test_server::SimpleWebServer> server_;
test_server::SimpleResponse default_response_;
ScopedHandle ready_;
};
// Helper class for running tests that rely on the NavigationManager.
class UrlmonMonikerTestManager {
public:
explicit UrlmonMonikerTestManager(const wchar_t* test_url) {
EXPECT_EQ(true, MonikerPatch::Initialize());
}
~UrlmonMonikerTestManager() {
MonikerPatch::Uninitialize();
}
chrome_frame_test::TimedMsgLoop& loop() {
return loop_;
}
protected:
chrome_frame_test::TimedMsgLoop loop_;
};
ACTION_P(SetBindInfo, is_async) {
DWORD* flags = arg0;
BINDINFO* bind_info = arg1;
DCHECK(flags);
DCHECK(bind_info);
DCHECK(bind_info->cbSize >= sizeof(BINDINFO));
*flags = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA;
if (is_async)
*flags |= BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE;
bind_info->dwBindVerb = BINDVERB_GET;
memset(&bind_info->stgmedData, 0, sizeof(STGMEDIUM));
bind_info->grfBindInfoF = 0;
bind_info->szCustomVerb = NULL;
}
// Wraps the MockBindStatusCallbackImpl mock object and allows the user
// to specify expectations on the callback object.
class UrlmonMonikerTestCallback {
public:
explicit UrlmonMonikerTestCallback(UrlmonMonikerTestManager* mgr)
: mgr_(mgr), clip_format_(0) {
}
~UrlmonMonikerTestCallback() {
}
typedef enum GetBindInfoExpectations {
EXPECT_NO_CALL,
REQUEST_SYNCHRONOUS,
REQUEST_ASYNCHRONOUS,
} GET_BIND_INFO_EXPECTATION;
// Sets gmock expectations for the IBindStatusCallback mock object.
void SetCallbackExpectations(GetBindInfoExpectations bind_info_handling,
HRESULT data_available_response,
bool quit_loop_on_stop) {
EXPECT_CALL(callback_, OnProgress(_, _, _, _))
.WillRepeatedly(Return(S_OK));
if (bind_info_handling == REQUEST_ASYNCHRONOUS) {
EXPECT_CALL(callback_, GetBindInfo(_, _))
.WillOnce(DoAll(SetBindInfo(true), Return(S_OK)));
} else if (bind_info_handling == REQUEST_SYNCHRONOUS) {
EXPECT_CALL(callback_, GetBindInfo(_, _))
.WillOnce(DoAll(SetBindInfo(false), Return(S_OK)));
} else {
DCHECK(bind_info_handling == EXPECT_NO_CALL);
}
EXPECT_CALL(callback_, OnStartBinding(_, _))
.WillOnce(Return(S_OK));
EXPECT_CALL(callback_, OnDataAvailable(_, _, _, _))
.WillRepeatedly(Return(data_available_response));
if (quit_loop_on_stop) {
// When expecting asynchronous
EXPECT_CALL(callback_, OnStopBinding(data_available_response, _))
.WillOnce(DoAll(QUIT_LOOP(mgr_->loop()), Return(S_OK)));
} else {
EXPECT_CALL(callback_, OnStopBinding(data_available_response, _))
.WillOnce(Return(S_OK));
}
}
HRESULT CreateUrlMonikerAndBindToStorage(const wchar_t* url,
IBindCtx** bind_ctx) {
ScopedComPtr<IMoniker> moniker;
HRESULT hr = CreateURLMoniker(NULL, url, moniker.Receive());
EXPECT_TRUE(moniker != NULL);
if (moniker) {
ScopedComPtr<IBindCtx> context;
::CreateAsyncBindCtx(0, callback(), NULL, context.Receive());
DCHECK(context);
ScopedComPtr<IStream> stream;
hr = moniker->BindToStorage(context, NULL, IID_IStream,
reinterpret_cast<void**>(stream.Receive()));
if (SUCCEEDED(hr) && bind_ctx)
*bind_ctx = context.Detach();
}
return hr;
}
IBindStatusCallback* callback() {
return &callback_;
}
protected:
CComObjectStackEx<MockBindStatusCallbackImpl> callback_;
UrlmonMonikerTestManager* mgr_;
CLIPFORMAT clip_format_;
};
/*
// Tests synchronously binding to a moniker and downloading the target.
TEST_F(UrlmonMonikerTest, BindToStorageSynchronous) {
const wchar_t test_url[] = L"http://localhost:43210/";
UrlmonMonikerTestManager test(test_url);
UrlmonMonikerTestCallback callback(&test);
RunTestServer server_thread;
EXPECT_TRUE(server_thread.Start());
callback.SetCallbackExpectations(
UrlmonMonikerTestCallback::REQUEST_SYNCHRONOUS, S_OK, false);
ScopedComPtr<IBindCtx> bind_ctx;
HRESULT hr = callback.CreateUrlMonikerAndBindToStorage(test_url,
bind_ctx.Receive());
// The download should have happened synchronously, so we don't expect
// MK_S_ASYNCHRONOUS or any errors.
EXPECT_EQ(S_OK, hr);
IBindCtx* release = bind_ctx.Detach();
EXPECT_EQ(0, release->Release());
server_thread.Stop();
}
// Tests asynchronously binding to a moniker and downloading the target.
TEST_F(UrlmonMonikerTest, BindToStorageAsynchronous) {
const wchar_t test_url[] = L"http://localhost:43210/";
UrlmonMonikerTestManager test(test_url);
UrlmonMonikerTestCallback callback(&test);
test_server::SimpleWebServer server(43210);
test_server::SimpleResponse default_response("/", kTestContent);
server.AddResponse(&default_response);
callback.SetCallbackExpectations(
UrlmonMonikerTestCallback::REQUEST_ASYNCHRONOUS, S_OK, true);
ScopedComPtr<IBindCtx> bind_ctx;
HRESULT hr = callback.CreateUrlMonikerAndBindToStorage(test_url,
bind_ctx.Receive());
EXPECT_EQ(MK_S_ASYNCHRONOUS, hr);
test.loop().RunFor(kUrlmonMonikerTimeoutSec);
IBindCtx* release = bind_ctx.Detach();
EXPECT_EQ(0, release->Release());
}
// Responds with the Chrome mime type.
class ResponseWithContentType : public test_server::SimpleResponse {
public:
ResponseWithContentType(const char* request_path,
const std::string& contents)
: test_server::SimpleResponse(request_path, contents) {
}
virtual bool GetContentType(std::string* content_type) const {
*content_type = WideToASCII(kChromeMimeType);
return true;
}
};
// Downloads a document asynchronously and then verifies that the downloaded
// contents were cached and the cache contents are correct.
// TODO(tommi): Fix and re-enable.
// http://code.google.com/p/chromium/issues/detail?id=39415
TEST_F(UrlmonMonikerTest, BindToStorageSwitchContent) {
const wchar_t test_url[] = L"http://localhost:43210/";
UrlmonMonikerTestManager test(test_url);
UrlmonMonikerTestCallback callback(&test);
test_server::SimpleWebServer server(43210);
ResponseWithContentType default_response("/", kTestContent);
server.AddResponse(&default_response);
callback.SetCallbackExpectations(
UrlmonMonikerTestCallback::REQUEST_ASYNCHRONOUS, INET_E_TERMINATED_BIND,
true);
HRESULT hr = callback.CreateUrlMonikerAndBindToStorage(test_url, NULL);
EXPECT_EQ(MK_S_ASYNCHRONOUS, hr);
test.loop().RunFor(kUrlmonMonikerTimeoutSec);
scoped_refptr<RequestData> request_data(
test.nav_manager().GetActiveRequestData(test_url));
EXPECT_TRUE(request_data != NULL);
if (request_data) {
EXPECT_EQ(request_data->GetCachedContentSize(),
arraysize(kTestContent) - 1);
ScopedComPtr<IStream> stream;
request_data->GetResetCachedContentStream(stream.Receive());
EXPECT_TRUE(stream != NULL);
if (stream) {
char buffer[0xffff];
DWORD read = 0;
stream->Read(buffer, sizeof(buffer), &read);
EXPECT_EQ(read, arraysize(kTestContent) - 1);
EXPECT_EQ(0, memcmp(buffer, kTestContent, read));
}
}
}
// Fetches content asynchronously first to cache it and then
// verifies that fetching the cached content the same way works as expected
// and happens synchronously.
TEST_F(UrlmonMonikerTest, BindToStorageCachedContent) {
const wchar_t test_url[] = L"http://localhost:43210/";
UrlmonMonikerTestManager test(test_url);
UrlmonMonikerTestCallback callback(&test);
test_server::SimpleWebServer server(43210);
ResponseWithContentType default_response("/", kTestContent);
server.AddResponse(&default_response);
// First set of expectations. Download the contents
// asynchronously. This should populate the cache so that
// the second request should be served synchronously without
// going to the server.
callback.SetCallbackExpectations(
UrlmonMonikerTestCallback::REQUEST_ASYNCHRONOUS, INET_E_TERMINATED_BIND,
true);
HRESULT hr = callback.CreateUrlMonikerAndBindToStorage(test_url, NULL);
EXPECT_EQ(MK_S_ASYNCHRONOUS, hr);
test.loop().RunFor(kUrlmonMonikerTimeoutSec);
scoped_refptr<RequestData> request_data(
test.nav_manager().GetActiveRequestData(test_url));
EXPECT_TRUE(request_data != NULL);
if (request_data) {
// This time, just accept the content as normal.
UrlmonMonikerTestCallback callback2(&test);
callback2.SetCallbackExpectations(
UrlmonMonikerTestCallback::EXPECT_NO_CALL, S_OK, false);
hr = callback2.CreateUrlMonikerAndBindToStorage(test_url, NULL);
// S_OK means that the operation completed synchronously.
// Otherwise we'd get MK_S_ASYNCHRONOUS.
EXPECT_EQ(S_OK, hr);
}
}
*/
<|endoftext|>
|
<commit_before>/// HEADER
#include <csapex/scheduling/thread_group.h>
/// PROJECT
#include <csapex/scheduling/task.h>
#include <csapex/utility/thread.h>
#include <csapex/scheduling/task_generator.h>
using namespace csapex;
int ThreadGroup::next_id_ = ThreadGroup::MINIMUM_THREAD_ID;
ThreadGroup::ThreadGroup(int id, std::string name)
: id_(id), name_(name), running_(false), pause_(false)
{
next_id_ = std::max(next_id_, id + 1);
startThread();
}
ThreadGroup::ThreadGroup(std::string name)
: id_(next_id_++), name_(name), running_(false), pause_(false)
{
startThread();
}
ThreadGroup::~ThreadGroup()
{
if(running_ || thread_.joinable()) {
stop();
}
}
int ThreadGroup::nextId()
{
return next_id_;
}
int ThreadGroup::id() const
{
return id_;
}
std::string ThreadGroup::name() const
{
return name_;
}
const std::thread& ThreadGroup::thread() const
{
return thread_;
}
bool ThreadGroup::isEmpty() const
{
return generators_.empty();
}
void ThreadGroup::setPause(bool pause)
{
if(pause != pause_) {
pause_ = pause;
std::unique_lock<std::recursive_mutex> lock(state_mtx_);
pause_changed_.notify_all();
}
}
void ThreadGroup::stop()
{
{
std::unique_lock<std::recursive_mutex> lock(state_mtx_);
running_ = false;
pause_ = false;
pause_changed_.notify_all();
}
{
std::unique_lock<std::recursive_mutex> lock(tasks_mtx_);
work_available_.notify_all();
if(thread_.joinable()) {
lock.unlock();
thread_.join();
}
}
}
void ThreadGroup::add(TaskGenerator* generator)
{
std::unique_lock<std::recursive_mutex> lock(state_mtx_);
if(!running_) {
startThread();
}
generators_.push_back(generator);
}
void ThreadGroup::add(TaskGenerator *generator, const std::vector<TaskPtr> &initial_tasks)
{
add(generator);
std::unique_lock<std::recursive_mutex> lock(tasks_mtx_);
for(TaskPtr t: initial_tasks) {
schedule(t);
}
work_available_.notify_all();
}
std::vector<TaskPtr> ThreadGroup::remove(TaskGenerator* generator)
{
std::vector<TaskPtr> remaining_tasks;
std::unique_lock<std::recursive_mutex> lock(tasks_mtx_);
for(auto it = tasks_.begin(); it != tasks_.end();) {
TaskPtr task = *it;
if(task->getParent() == generator) {
remaining_tasks.push_back(task);
it = tasks_.erase(it);
} else {
++it;
}
}
for(auto it = generators_.begin(); it != generators_.end();) {
if(*it == generator) {
it = generators_.erase(it);
} else {
++it;
}
}
work_available_.notify_all();
return remaining_tasks;
}
void ThreadGroup::schedule(TaskPtr task)
{
std::unique_lock<std::recursive_mutex> tasks_lock(tasks_mtx_);
for(TaskPtr t : tasks_) {
if(t.get() == task.get()) {
return;
}
}
tasks_.push_back(task);
work_available_.notify_all();
}
void ThreadGroup::startThread()
{
std::unique_lock<std::recursive_mutex> lock(state_mtx_);
if(thread_.joinable()) {
running_ = false;
pause_changed_.notify_all();
lock.unlock();
thread_.join();
}
running_ = true;
thread_ = std::thread ([this]() {
csapex::thread::set_name((name_ + "!").c_str());
while(running_) {
{
std::unique_lock<std::recursive_mutex> lock(tasks_mtx_);
running_ = !generators_.empty();
while(running_ && tasks_.empty()) {
work_available_.wait_for(lock, std::chrono::seconds(1));
running_ = !generators_.empty();
}
}
bool done = !running_;
while(!done) {
{
// pause?
std::unique_lock<std::recursive_mutex> state_lock(state_mtx_);
while(running_ && pause_) {
pause_changed_.wait(state_lock);
}
}
// execute one task
std::unique_lock<std::recursive_mutex> tasks_lock(tasks_mtx_);
if(tasks_.empty()) {
done = true;
} else {
auto task = tasks_.front();
tasks_.pop_front();
tasks_lock.unlock();
{
std::unique_lock<std::recursive_mutex> state_lock(state_mtx_);
if(running_) {
state_lock.unlock();
// TODO: this can fail...
task->execute();
} else {
done = true;
}
}
}
}
}
});
}
<commit_msg>one shutdown deadlock fixed<commit_after>/// HEADER
#include <csapex/scheduling/thread_group.h>
/// PROJECT
#include <csapex/scheduling/task.h>
#include <csapex/utility/thread.h>
#include <csapex/scheduling/task_generator.h>
using namespace csapex;
int ThreadGroup::next_id_ = ThreadGroup::MINIMUM_THREAD_ID;
ThreadGroup::ThreadGroup(int id, std::string name)
: id_(id), name_(name), running_(false), pause_(false)
{
next_id_ = std::max(next_id_, id + 1);
startThread();
}
ThreadGroup::ThreadGroup(std::string name)
: id_(next_id_++), name_(name), running_(false), pause_(false)
{
startThread();
}
ThreadGroup::~ThreadGroup()
{
if(running_ || thread_.joinable()) {
stop();
}
}
int ThreadGroup::nextId()
{
return next_id_;
}
int ThreadGroup::id() const
{
return id_;
}
std::string ThreadGroup::name() const
{
return name_;
}
const std::thread& ThreadGroup::thread() const
{
return thread_;
}
bool ThreadGroup::isEmpty() const
{
return generators_.empty();
}
void ThreadGroup::setPause(bool pause)
{
if(pause != pause_) {
pause_ = pause;
std::unique_lock<std::recursive_mutex> lock(state_mtx_);
pause_changed_.notify_all();
}
}
void ThreadGroup::stop()
{
{
std::unique_lock<std::recursive_mutex> lock(state_mtx_);
running_ = false;
pause_ = false;
pause_changed_.notify_all();
}
{
std::unique_lock<std::recursive_mutex> lock(tasks_mtx_);
work_available_.notify_all();
if(thread_.joinable()) {
lock.unlock();
thread_.join();
}
}
}
void ThreadGroup::add(TaskGenerator* generator)
{
std::unique_lock<std::recursive_mutex> lock(state_mtx_);
if(!running_) {
startThread();
}
generators_.push_back(generator);
}
void ThreadGroup::add(TaskGenerator *generator, const std::vector<TaskPtr> &initial_tasks)
{
add(generator);
std::unique_lock<std::recursive_mutex> lock(tasks_mtx_);
for(TaskPtr t: initial_tasks) {
schedule(t);
}
work_available_.notify_all();
}
std::vector<TaskPtr> ThreadGroup::remove(TaskGenerator* generator)
{
std::vector<TaskPtr> remaining_tasks;
std::unique_lock<std::recursive_mutex> lock(tasks_mtx_);
for(auto it = tasks_.begin(); it != tasks_.end();) {
TaskPtr task = *it;
if(task->getParent() == generator) {
remaining_tasks.push_back(task);
it = tasks_.erase(it);
} else {
++it;
}
}
for(auto it = generators_.begin(); it != generators_.end();) {
if(*it == generator) {
it = generators_.erase(it);
} else {
++it;
}
}
work_available_.notify_all();
return remaining_tasks;
}
void ThreadGroup::schedule(TaskPtr task)
{
std::unique_lock<std::recursive_mutex> tasks_lock(tasks_mtx_);
for(TaskPtr t : tasks_) {
if(t.get() == task.get()) {
return;
}
}
tasks_.push_back(task);
work_available_.notify_all();
}
void ThreadGroup::startThread()
{
std::unique_lock<std::recursive_mutex> lock(state_mtx_);
if(thread_.joinable()) {
running_ = false;
pause_changed_.notify_all();
lock.unlock();
thread_.join();
}
running_ = true;
thread_ = std::thread ([this]() {
csapex::thread::set_name((name_ + "!").c_str());
while(running_) {
{
std::unique_lock<std::recursive_mutex> lock(tasks_mtx_);
running_ = !generators_.empty();
while(running_ && tasks_.empty()) {
work_available_.wait_for(lock, std::chrono::seconds(1));
running_ = running_ && !generators_.empty();
}
}
bool done = !running_;
while(!done) {
{
// pause?
std::unique_lock<std::recursive_mutex> state_lock(state_mtx_);
while(running_ && pause_) {
pause_changed_.wait(state_lock);
}
}
// execute one task
std::unique_lock<std::recursive_mutex> tasks_lock(tasks_mtx_);
if(tasks_.empty()) {
done = true;
} else {
auto task = tasks_.front();
tasks_.pop_front();
tasks_lock.unlock();
{
std::unique_lock<std::recursive_mutex> state_lock(state_mtx_);
if(running_) {
state_lock.unlock();
// TODO: this can fail...
task->execute();
} else {
done = true;
}
}
}
}
}
});
}
<|endoftext|>
|
<commit_before>
//////////////////////////////////////////////////////////////////////////////
// This software module is developed by SCIDM team in 1999-2008.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// For any questions please contact SciDM team by email at scidmteam@yahoo.com
//////////////////////////////////////////////////////////////////////////////
#include "seg_align.h"
#include "weights.h"
#include <common_typedefs.h>
#include <common_algo.h>
#include <deque>
#include <assert.h>
SegAlign::SegAlign (WMatrix& wm, float gip, float gep, float gcap, int max_ovl)
:
wm_ (wm),
gip_ (gip),
gep_ (gep),
gcap_ (gcap),
max_ovl_ (max_ovl)
{
}
class CompareSimIdxByPos
{
const ARVect& sims_;
int max_ovl_;
public:
CompareSimIdxByPos (const ARVect& sims, int max_ovl) : sims_ (sims), max_ovl_ (max_ovl) {}
bool operator () (int idx1, int idx2)
{
const BATCH& b1 = sims_ [idx1].batches_ [0];
const BATCH& b2 = sims_ [idx2].batches_ [0];
int vv = b1.xpos - b2.xpos;
if (vv < 0) return true;
if (vv > 0) return false;
return b1.ypos - b2.ypos;
}
};
static void make_pos_ordered_sim_index (ARVect& sims, int max_ovl, UIntVect& target)
{
range (target, sims.size ());
std::sort (target.begin (), target.end (), CompareSimIdxByPos (sims, max_ovl));
}
void SegAlign :: fill_trace (ARVect& sims, UIntVect& order, TraceVect& trace)
{
// walk all similarities preceeding current by X axis
// if continuation is possible
// calculate and remember score; find best score / cutoff position for overlaps
// For each position, right-to-left:
for (UIntVect::iterator i1 = order.begin (); i1 != order.end (); i1 ++)
{
// select best of compatibles for each ending not later then current.beg + max_dom_ovl_
for (UIntVect::iterator i2 = order.begin (); i2 != order.end (); i2 ++)
{
if (i1 == i2)
continue;
bool overrun;
bool comp = sims [*i1].can_continue (sims [*i2], max_ovl_, overrun);
if (overrun) break;
if (!comp) continue;
// compatible. calculate and remember score
float cur_score = trace [*i2].score_ + sims [*i2].al_score_;
float& prev_score = trace [*i1].score_;
if (cur_score > prev_score)
{
prev_score = cur_score;
trace [*i1].idx_ = *i2;
trace [*i1].gap_ = trace [*i2].gap_ + sims [*i2].gap (sims [*i1]);
}
else if (cur_score == prev_score)
{
int cur_gap = trace [*i2].gap_ + sims [*i2].gap (sims [*i1]);;
int& prev_gap = trace [*i1].gap_;
if (cur_gap < prev_gap)
{
// no need to assign score - it is same
trace [*i1].idx_ = *i2;
prev_gap = cur_gap;
}
}
}
}
}
unsigned SegAlign::find_continuations (TraceVect& trace, BoolVect& continuations)
{
continuations.resize (trace.size ());
std::fill (continuations.begin (), continuations.end (), false);
for (int ii = 0; ii < trace.size (); ii ++)
if (trace [ii].idx_ != -1)
continuations [trace [ii].idx_] = true;
return std::count (continuations.begin (), continuations.end (), false);
}
void SegAlign::make_score_order (TraceVect& trace, BoolVect& continuations, unsigned resno, UIntVect& target)
{
unsigned p = 0;
target.resize (resno);
for (int ii = 0; ii < trace.size (); ii ++)
if (!continuations [ii])
target [p ++] = ii;
std::sort (target.begin (), target.end (), CompareTraceIdxByScore (trace));
}
void SegAlign::backtrace_from (unsigned idx, TraceVect& trace, ARVect& sims, BoolVect& processed, BoolVect& to_remove)
{
// backtrace:
// while there is preceeding sim:
// accumulate batches, removing / adjusting overlapping ones
// remember the sim in to_remove list (except head, which does not have preceeding sim)
// switch to preceeding sim
// replace batches and adjust batch_no for head sim (last iterated)
// adjust scores
int iniidx = idx;
// optimization for singlet - no need to merge
// if (trace [idx].idx_ == -1 || processed [trace [idx].idx_])
if (trace [iniidx].idx_ == -1 || processed [trace [iniidx].idx_])
return;
// merge all batches from merged sims;
std::deque <BATCH> batches;
int upd_sim_idx;
int score = 0;
float al_score = 0;
double bitscore = 0;
double evalue = 1e30;
float chi2 = -1e30;
int q_auto = 0;
int t_auto = 0;
while (idx != -1)
{
int next = trace [idx].idx_;
// adjust tail of the added batch list so it does not overlap the head of allready added one.
BATCH* nbp = sims [idx].batches_ + sims [idx].batch_no_ - 1;
if (batches.size ())
{
BATCH& fb = batches.front ();
while ((nbp->xpos >= fb.xpos) ||
(nbp->ypos >= fb.ypos))
nbp --; // no check for getting below batch array start - relying upon prior compatibility check
if (nbp < sims [idx].batches_)
ERR (ERR_Internal);
// assert (nbp >= sims [idx].batches_); // just in case prior compatibility is not working ...
int xd = max_ (0, (int) (nbp->xpos + nbp->len) - (int) fb.xpos);
int yd = max_ (0, (int) (nbp->ypos + nbp->len) - (int) fb.ypos);
int adj = max_ (xd, yd);
nbp->len -= adj;
}
// add adjusted batches to (front of) accumulator
batches.insert (batches.begin (), (BATCH*) sims [idx].batches_, nbp + 1);
al_score += sims [idx].score_; // - GAP cost ?
score += sims [idx].score_;
bitscore += sims [idx].bitscore_;
evalue = min_ (evalue, sims [idx].evalue_);
chi2 = max_ (chi2, sims [idx].chi2_);
q_auto += sims [idx].q_auto_score_;
t_auto += sims [idx].t_auto_score_;
// save present sim into toRemove array (if it is not the last one)
if (next != -1)
to_remove [idx] = true;
upd_sim_idx = idx;
processed [idx] = true;
idx = next;
}
// put new batches into sim being updated (the one at cur
AlignResult& upd_sim = sims [upd_sim_idx];
upd_sim.batches_ = new BATCH [batches.size ()];
upd_sim.batch_no_ = batches.size ();
std::copy (batches.begin (), batches.end (), (BATCH*) upd_sim.batches_);
// adjust the sw score (NOTE: gaps introduced at zero cost here! Also score is NOT adjusted for removed overlaps!)
upd_sim.score_ = score;
upd_sim.al_score_ = al_score;
upd_sim.bitscore_ = bitscore;
upd_sim.evalue_ = evalue;
upd_sim.q_auto_score_ = q_auto;
upd_sim.t_auto_score_ = t_auto;
}
// remember the sim in to_remove list (except head, which is being modified)
// dynamic programming
// find best set of connected paths over similarity segments
bool SegAlign::merge (ARVect& sims)
{
if (sims.size () <= 1)
return false; // nothing to do
// Make list of sim indices ordered by xpos
UIntVect order;
make_pos_ordered_sim_index (sims, max_ovl_, order);
// Allocate array of prev_best control structures (one per sim)
TraceVect trace (sims.size ());
// fill in the trace
fill_trace (sims, order, trace);
// mark indexes that have continuations; the ones that do not are merged groups tails
BoolVect cont;
unsigned resno = find_continuations (trace, cont);
if (resno == sims.size ())
return false; // nothing to do
// make list of tail sim indices in the order descending scores
UIntVect score_order;
make_score_order (trace, cont, resno, score_order);
// processed are seen sims; direct addressed to avoid log-time searches
BoolVect processed (sims.size ()); std::fill (processed.begin (), processed.end (), false);
// to_remove are not needed anymore; direct addressed to avoid log-time searches
BoolVect to_remove (sims.size ()); std::fill (to_remove.begin (), to_remove.end (), false);
// for each similarity without continuation (in score descending order):
for (UIntVect::iterator titr = score_order.begin (); titr != score_order.end (); titr ++)
backtrace_from (*titr, trace, sims, processed, to_remove);
// remove sims at remove positions
remove_mask (sims, to_remove);
return true;
}
<commit_msg>Fixed bug in comparison routine (which led to ambiguity in sort => segfaults!)<commit_after>
//////////////////////////////////////////////////////////////////////////////
// This software module is developed by SCIDM team in 1999-2008.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// For any questions please contact SciDM team by email at scidmteam@yahoo.com
//////////////////////////////////////////////////////////////////////////////
#include "seg_align.h"
#include "weights.h"
#include <common_typedefs.h>
#include <common_algo.h>
#include <deque>
#include <assert.h>
SegAlign::SegAlign (WMatrix& wm, float gip, float gep, float gcap, int max_ovl)
:
wm_ (wm),
gip_ (gip),
gep_ (gep),
gcap_ (gcap),
max_ovl_ (max_ovl)
{
}
class CompareSimIdxByPos
{
const ARVect& sims_;
int max_ovl_;
public:
CompareSimIdxByPos (const ARVect& sims, int max_ovl) : sims_ (sims), max_ovl_ (max_ovl) {}
bool operator () (int idx1, int idx2)
{
const BATCH& b1 = sims_ [idx1].batches_ [0];
const BATCH& b2 = sims_ [idx2].batches_ [0];
int vv = b1.xpos - b2.xpos;
if (vv < 0) return true;
if (vv > 0) return false;
return b1.ypos < b2.ypos;
}
};
static void make_pos_ordered_sim_index (ARVect& sims, int max_ovl, UIntVect& target)
{
range (target, sims.size ());
std::sort (target.begin (), target.end (), CompareSimIdxByPos (sims, max_ovl));
}
void SegAlign :: fill_trace (ARVect& sims, UIntVect& order, TraceVect& trace)
{
// walk all similarities preceeding current by X axis
// if continuation is possible
// calculate and remember score; find best score / cutoff position for overlaps
// For each position, right-to-left:
for (UIntVect::iterator i1 = order.begin (); i1 != order.end (); i1 ++)
{
// select best of compatibles for each ending not later then current.beg + max_dom_ovl_
for (UIntVect::iterator i2 = order.begin (); i2 != order.end (); i2 ++)
{
if (i1 == i2)
continue;
bool overrun;
bool comp = sims [*i1].can_continue (sims [*i2], max_ovl_, overrun);
if (overrun) break;
if (!comp) continue;
// compatible. calculate and remember score
float cur_score = trace [*i2].score_ + sims [*i2].al_score_;
float& prev_score = trace [*i1].score_;
if (cur_score > prev_score)
{
prev_score = cur_score;
trace [*i1].idx_ = *i2;
trace [*i1].gap_ = trace [*i2].gap_ + sims [*i2].gap (sims [*i1]);
}
else if (cur_score == prev_score)
{
int cur_gap = trace [*i2].gap_ + sims [*i2].gap (sims [*i1]);;
int& prev_gap = trace [*i1].gap_;
if (cur_gap < prev_gap)
{
// no need to assign score - it is same
trace [*i1].idx_ = *i2;
prev_gap = cur_gap;
}
}
}
}
}
unsigned SegAlign::find_continuations (TraceVect& trace, BoolVect& continuations)
{
continuations.resize (trace.size ());
std::fill (continuations.begin (), continuations.end (), false);
for (int ii = 0; ii < trace.size (); ii ++)
if (trace [ii].idx_ != -1)
continuations [trace [ii].idx_] = true;
return std::count (continuations.begin (), continuations.end (), false);
}
void SegAlign::make_score_order (TraceVect& trace, BoolVect& continuations, unsigned resno, UIntVect& target)
{
unsigned p = 0;
target.resize (resno);
for (int ii = 0; ii < trace.size (); ii ++)
if (!continuations [ii])
target [p ++] = ii;
std::sort (target.begin (), target.end (), CompareTraceIdxByScore (trace));
}
void SegAlign::backtrace_from (unsigned idx, TraceVect& trace, ARVect& sims, BoolVect& processed, BoolVect& to_remove)
{
// backtrace:
// while there is preceeding sim:
// accumulate batches, removing / adjusting overlapping ones
// remember the sim in to_remove list (except head, which does not have preceeding sim)
// switch to preceeding sim
// replace batches and adjust batch_no for head sim (last iterated)
// adjust scores
int iniidx = idx;
// optimization for singlet - no need to merge
// if (trace [idx].idx_ == -1 || processed [trace [idx].idx_])
if (trace [iniidx].idx_ == -1 || processed [trace [iniidx].idx_])
return;
// merge all batches from merged sims;
std::deque <BATCH> batches;
int upd_sim_idx;
int score = 0;
float al_score = 0;
double bitscore = 0;
double evalue = 1e30;
float chi2 = -1e30;
int q_auto = 0;
int t_auto = 0;
while (idx != -1)
{
int next = trace [idx].idx_;
// adjust tail of the added batch list so it does not overlap the head of allready added one.
BATCH* nbp = sims [idx].batches_ + sims [idx].batch_no_ - 1;
if (batches.size ())
{
BATCH& fb = batches.front ();
while ((nbp->xpos >= fb.xpos) ||
(nbp->ypos >= fb.ypos))
nbp --; // no check for getting below batch array start - relying upon prior compatibility check
if (nbp < sims [idx].batches_)
ERR (ERR_Internal);
// assert (nbp >= sims [idx].batches_); // just in case prior compatibility is not working ...
int xd = max_ (0, (int) (nbp->xpos + nbp->len) - (int) fb.xpos);
int yd = max_ (0, (int) (nbp->ypos + nbp->len) - (int) fb.ypos);
int adj = max_ (xd, yd);
nbp->len -= adj;
}
// add adjusted batches to (front of) accumulator
batches.insert (batches.begin (), (BATCH*) sims [idx].batches_, nbp + 1);
al_score += sims [idx].score_; // - GAP cost ?
score += sims [idx].score_;
bitscore += sims [idx].bitscore_;
evalue = min_ (evalue, sims [idx].evalue_);
chi2 = max_ (chi2, sims [idx].chi2_);
q_auto += sims [idx].q_auto_score_;
t_auto += sims [idx].t_auto_score_;
// save present sim into toRemove array (if it is not the last one)
if (next != -1)
to_remove [idx] = true;
upd_sim_idx = idx;
processed [idx] = true;
idx = next;
}
// put new batches into sim being updated (the one at cur
AlignResult& upd_sim = sims [upd_sim_idx];
upd_sim.batches_ = new BATCH [batches.size ()];
upd_sim.batch_no_ = batches.size ();
std::copy (batches.begin (), batches.end (), (BATCH*) upd_sim.batches_);
// adjust the sw score (NOTE: gaps introduced at zero cost here! Also score is NOT adjusted for removed overlaps!)
upd_sim.score_ = score;
upd_sim.al_score_ = al_score;
upd_sim.bitscore_ = bitscore;
upd_sim.evalue_ = evalue;
upd_sim.q_auto_score_ = q_auto;
upd_sim.t_auto_score_ = t_auto;
}
// remember the sim in to_remove list (except head, which is being modified)
// dynamic programming
// find best set of connected paths over similarity segments
bool SegAlign::merge (ARVect& sims)
{
if (sims.size () <= 1)
return false; // nothing to do
// Make list of sim indices ordered by xpos
UIntVect order;
make_pos_ordered_sim_index (sims, max_ovl_, order);
// Allocate array of prev_best control structures (one per sim)
TraceVect trace (sims.size ());
// fill in the trace
fill_trace (sims, order, trace);
// mark indexes that have continuations; the ones that do not are merged groups tails
BoolVect cont;
unsigned resno = find_continuations (trace, cont);
if (resno == sims.size ())
return false; // nothing to do
// make list of tail sim indices in the order descending scores
UIntVect score_order;
make_score_order (trace, cont, resno, score_order);
// processed are seen sims; direct addressed to avoid log-time searches
BoolVect processed (sims.size ()); std::fill (processed.begin (), processed.end (), false);
// to_remove are not needed anymore; direct addressed to avoid log-time searches
BoolVect to_remove (sims.size ()); std::fill (to_remove.begin (), to_remove.end (), false);
// for each similarity without continuation (in score descending order):
for (UIntVect::iterator titr = score_order.begin (); titr != score_order.end (); titr ++)
backtrace_from (*titr, trace, sims, processed, to_remove);
// remove sims at remove positions
remove_mask (sims, to_remove);
return true;
}
<|endoftext|>
|
<commit_before>/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-CurrentYear, Linköping University,
* Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3
* AND THIS OSMC PUBLIC LICENSE (OSMC-PL).
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S
* ACCEPTANCE OF THE OSMC PUBLIC LICENSE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from Linköping University, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS
* OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
/*
* HopsanGUI
* Fluid and Mechatronic Systems, Department of Management and Engineering, Linköping University
* Main Authors 2009-2010: Robert Braun, Björn Eriksson, Peter Nordin
* Contributors 2009-2010: Mikael Axin, Alessandro Dell'Amico, Karl Pettersson, Ingo Staack
*/
//!
//! @file SystemParametersWidget.cpp
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2010-10-04
//!
//! @brief Contains a System parameter widget class
//!
//$Id$
#include <QtGui>
#include "../MainWindow.h"
#include "SystemParametersWidget.h"
#include <QWidget>
#include <QDialog>
#include "ProjectTabWidget.h"
#include "../GUIObjects/GUISystem.h"
#include "../common.h"
//! Construtor for System Parameters widget, where the user can see and change the System parameters in the model.
//! @param parent Pointer to the main window
SystemParametersWidget::SystemParametersWidget(MainWindow *parent)
: QWidget(parent)
{
//mpParentMainWindow = parent;
//Set the name and size of the main window
this->setObjectName("SystemParameterWidget");
this->resize(400,500);
this->setWindowTitle("System Parameters");
mpSystemParametersTable = new SystemParameterTableWidget(0,1,this);
mpAddButton = new QPushButton(tr("&Set"), this);
mpAddButton->setFixedHeight(30);
mpAddButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
mpAddButton->setAutoDefault(false);
QFont tempFont = mpAddButton->font();
tempFont.setBold(true);
mpAddButton->setFont(tempFont);
mpAddButton->setEnabled(false);
mpRemoveButton = new QPushButton(tr("&Unset"), this);
mpRemoveButton->setFixedHeight(30);
mpRemoveButton->setAutoDefault(false);
mpRemoveButton->setFont(tempFont);
mpRemoveButton->setEnabled(false);
mpGridLayout = new QGridLayout(this);
mpGridLayout->addWidget(mpSystemParametersTable, 0, 0);
mpGridLayout->addWidget(mpAddButton, 1, 0);
mpGridLayout->addWidget(mpRemoveButton, 2, 0);
update();
connect(mpAddButton, SIGNAL(clicked()), mpSystemParametersTable, SLOT(openComponentPropertiesDialog()));
connect(mpRemoveButton, SIGNAL(clicked()), mpSystemParametersTable, SLOT(removeSelectedParameters()));
connect(gpMainWindow->mpProjectTabs, SIGNAL(currentChanged(int)), this, SLOT(update()));//Strössel!
connect(gpMainWindow->mpProjectTabs, SIGNAL(newTabAdded()), this, SLOT(update()));//Strössel!
}
void SystemParametersWidget::update()
{
if(gpMainWindow->mpProjectTabs->count()>0)
{
mpAddButton->setEnabled(true);
mpRemoveButton->setEnabled(true);
}
else
{
mpAddButton->setEnabled(false);
mpRemoveButton->setEnabled(false);
}
mpSystemParametersTable->update();
}
SystemParameterTableWidget::SystemParameterTableWidget(int rows, int columns, QWidget *parent)
: QTableWidget(rows, columns, parent)
{
setFocusPolicy(Qt::StrongFocus);
setSelectionMode(QAbstractItemView::SingleSelection);
setBaseSize(400, 500);
horizontalHeader()->setStretchLastSection(true);
horizontalHeader()->hide();
update();
connect(this, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changeParameter(QTableWidgetItem*)));
}
void SystemParameterTableWidget::keyPressEvent(QKeyEvent *event)
{
QTableWidget::keyPressEvent(event);
if(event->key() == Qt::Key_Delete)
{
std::cout << "Delete current System Parameter Widget Items" << std::endl;
removeSelectedParameters();
}
}
//! @brief Used for parameter changes done directly in the label
void SystemParameterTableWidget::changeParameter(QTableWidgetItem *item)
{
//Filter out value labels
if(item->column() == 1)
{
QTableWidgetItem *neighborItem = itemAt(item->row(), item->column()-1);
QString parName = neighborItem->text();
QString parValue = item->text();
//Do not do update, then crash due to the rebuild of the QTableWidgetItems
setParameter(parName, parValue, false);
}
}
double SystemParameterTableWidget::getParameter(QString name)
{
return gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParameter(name);
}
bool SystemParameterTableWidget::hasParameter(QString name)
{
return gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->hasSystemParameter(name);
}
//! Slot that adds a System parameter value
//! @param name Lookup name for the System parameter
//! @param value Value of the System parameter
void SystemParameterTableWidget::setParameter(QString name, double value, bool doUpdate)
{
//Error check
if(!(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->setSystemParameter(name, value)))
{
QMessageBox::critical(0, "Hopsan GUI",
QString("'%1' is an invalid name for a system parameter.")
.arg(name));
return;
}
if(doUpdate)
{
update();
}
emit modifiedSystemParameter();
}
//! Slot that adds a System parameter value
//! @param name Lookup name for the System parameter
//! @param value Value of the System parameter
void SystemParameterTableWidget::setParameter(QString name, QString valueTxt, bool doUpdate)
{
//Error check
bool isDbl;
double value = valueTxt.toDouble((&isDbl));
if(!(isDbl))
{
QMessageBox::critical(0, "Hopsan GUI",
QString("'%1' is not a valid number.")
.arg(valueTxt));
QString oldValue = QString::number(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParameter(name));
QList<QTableWidgetItem *> items = selectedItems();
//Error if size() > 1, but it should not be! :)
for(int i = 0; i<items.size(); ++i)
{
items[i]->setText(oldValue);
}
}
else
{
setParameter(name, value, doUpdate);
}
}
void SystemParameterTableWidget::setParameters()
{
// if(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getNumberOfSystemParameters() > 0)
// {
for(int i=0; i<rowCount(); ++i)
{
QString name = item(i, 0)->text();
double value = item(i, 1)->text().toDouble();
setParameter(name, value);
}
// }
}
//! Slot that removes all selected System parameters in parameter table
//! @todo This shall remove the actual System parameters when they have been implemented, wherever they are stored.
void SystemParameterTableWidget::removeSelectedParameters()
{
if(gpMainWindow->mpProjectTabs->count()>0)
{
QList<QTableWidgetItem *> pSelectedItems = selectedItems();
QStringList parametersToRemove;
QString tempName;
for(int i=0; i<pSelectedItems.size(); ++i)
{
tempName = item(pSelectedItems[i]->row(),0)->text();
if(!parametersToRemove.contains(tempName))
{
parametersToRemove.append(tempName);
gpMainWindow->mpProjectTabs->getCurrentTab()->hasChanged();
}
removeCellWidget(pSelectedItems[i]->row(), pSelectedItems[i]->column());
delete pSelectedItems[i];
}
for(int j=0; j<parametersToRemove.size(); ++j)
{
std::cout << "Removing: " << parametersToRemove[j].toStdString() << std::endl;
gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->removeSystemParameter(parametersToRemove.at(j));
}
}
update();
}
//! Slot that opens "Add Parameter" dialog, where the user can add new System parameters
void SystemParameterTableWidget::openComponentPropertiesDialog()
{
QDialog *pAddComponentPropertiesDialog = new QDialog(this);
pAddComponentPropertiesDialog->setWindowTitle("Set System Parameter");
mpNameLabel = new QLabel("Name: ", this);
mpNameBox = new QLineEdit(this);
mpValueLabel = new QLabel("Value: ", this);
mpValueBox = new QLineEdit(this);
mpValueBox->setValidator(new QDoubleValidator(this));
mpAddInDialogButton = new QPushButton("Set", this);
mpDoneInDialogButton = new QPushButton("Done", this);
QDialogButtonBox *pButtonBox = new QDialogButtonBox(Qt::Horizontal);
pButtonBox->addButton(mpAddInDialogButton, QDialogButtonBox::ActionRole);
pButtonBox->addButton(mpDoneInDialogButton, QDialogButtonBox::ActionRole);
QGridLayout *pDialogLayout = new QGridLayout(this);
pDialogLayout->addWidget(mpNameLabel,0,0);
pDialogLayout->addWidget(mpNameBox,0,1);
pDialogLayout->addWidget(mpValueLabel,1,0);
pDialogLayout->addWidget(mpValueBox,1,1);
pDialogLayout->addWidget(pButtonBox,2,0,1,2);
pAddComponentPropertiesDialog->setLayout(pDialogLayout);
pAddComponentPropertiesDialog->show();
connect(mpDoneInDialogButton,SIGNAL(clicked()),pAddComponentPropertiesDialog,SLOT(close()));
connect(mpAddInDialogButton,SIGNAL(clicked()),this,SLOT(addParameter()));
}
//! @Private help slot that adds a parameter from the selected name and value in "Add Parameter" dialog
void SystemParameterTableWidget::addParameter()
{
bool ok;
setParameter(mpNameBox->text(), mpValueBox->text().toDouble(&ok));
gpMainWindow->mpProjectTabs->getCurrentTab()->hasChanged();
}
//! Updates the parameter table from the contents list
void SystemParameterTableWidget::update()
{
QMap<std::string, double>::iterator it;
QMap<std::string, double> tempMap;
tempMap.clear();
clear();
if(gpMainWindow->mpProjectTabs->count()>0)
{
tempMap = gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParametersMap();
}
if(tempMap.isEmpty())
{
setColumnCount(1);
setRowCount(1);
verticalHeader()->hide();
QTableWidgetItem *item = new QTableWidgetItem();
item->setText("No System parameters set.");
item->setBackgroundColor(QColor("white"));
item->setTextAlignment(Qt::AlignCenter);
item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
setItem(0,0,item);
}
else
{
setRowCount(0);
setColumnCount(2);
setColumnWidth(0, 120);
verticalHeader()->show();
for(it=tempMap.begin(); it!=tempMap.end(); ++it)
{
QString valueString;
valueString.setNum(it.value());
insertRow(rowCount());
QTableWidgetItem *nameItem = new QTableWidgetItem(QString(it.key().c_str()));
QTableWidgetItem *valueItem = new QTableWidgetItem(valueString);
nameItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
valueItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
setItem(rowCount()-1, 0, nameItem);
setItem(rowCount()-1, 1, valueItem);
}
}
}
<commit_msg>removed OM license crap<commit_after>/*
* HopsanGUI
* Fluid and Mechatronic Systems, Department of Management and Engineering, Linköping University
* Main Authors 2009-2010: Robert Braun, Björn Eriksson, Peter Nordin
* Contributors 2009-2010: Mikael Axin, Alessandro Dell'Amico, Karl Pettersson, Ingo Staack
*/
//!
//! @file SystemParametersWidget.cpp
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2010-10-04
//!
//! @brief Contains a System parameter widget class
//!
//$Id$
#include <QtGui>
#include "../MainWindow.h"
#include "SystemParametersWidget.h"
#include <QWidget>
#include <QDialog>
#include "ProjectTabWidget.h"
#include "../GUIObjects/GUISystem.h"
#include "../common.h"
//! Construtor for System Parameters widget, where the user can see and change the System parameters in the model.
//! @param parent Pointer to the main window
SystemParametersWidget::SystemParametersWidget(MainWindow *parent)
: QWidget(parent)
{
//mpParentMainWindow = parent;
//Set the name and size of the main window
this->setObjectName("SystemParameterWidget");
this->resize(400,500);
this->setWindowTitle("System Parameters");
mpSystemParametersTable = new SystemParameterTableWidget(0,1,this);
mpAddButton = new QPushButton(tr("&Set"), this);
mpAddButton->setFixedHeight(30);
mpAddButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
mpAddButton->setAutoDefault(false);
QFont tempFont = mpAddButton->font();
tempFont.setBold(true);
mpAddButton->setFont(tempFont);
mpAddButton->setEnabled(false);
mpRemoveButton = new QPushButton(tr("&Unset"), this);
mpRemoveButton->setFixedHeight(30);
mpRemoveButton->setAutoDefault(false);
mpRemoveButton->setFont(tempFont);
mpRemoveButton->setEnabled(false);
mpGridLayout = new QGridLayout(this);
mpGridLayout->addWidget(mpSystemParametersTable, 0, 0);
mpGridLayout->addWidget(mpAddButton, 1, 0);
mpGridLayout->addWidget(mpRemoveButton, 2, 0);
update();
connect(mpAddButton, SIGNAL(clicked()), mpSystemParametersTable, SLOT(openComponentPropertiesDialog()));
connect(mpRemoveButton, SIGNAL(clicked()), mpSystemParametersTable, SLOT(removeSelectedParameters()));
connect(gpMainWindow->mpProjectTabs, SIGNAL(currentChanged(int)), this, SLOT(update()));//Strössel!
connect(gpMainWindow->mpProjectTabs, SIGNAL(newTabAdded()), this, SLOT(update()));//Strössel!
}
void SystemParametersWidget::update()
{
if(gpMainWindow->mpProjectTabs->count()>0)
{
mpAddButton->setEnabled(true);
mpRemoveButton->setEnabled(true);
}
else
{
mpAddButton->setEnabled(false);
mpRemoveButton->setEnabled(false);
}
mpSystemParametersTable->update();
}
SystemParameterTableWidget::SystemParameterTableWidget(int rows, int columns, QWidget *parent)
: QTableWidget(rows, columns, parent)
{
setFocusPolicy(Qt::StrongFocus);
setSelectionMode(QAbstractItemView::SingleSelection);
setBaseSize(400, 500);
horizontalHeader()->setStretchLastSection(true);
horizontalHeader()->hide();
update();
connect(this, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changeParameter(QTableWidgetItem*)));
}
void SystemParameterTableWidget::keyPressEvent(QKeyEvent *event)
{
QTableWidget::keyPressEvent(event);
if(event->key() == Qt::Key_Delete)
{
std::cout << "Delete current System Parameter Widget Items" << std::endl;
removeSelectedParameters();
}
}
//! @brief Used for parameter changes done directly in the label
void SystemParameterTableWidget::changeParameter(QTableWidgetItem *item)
{
//Filter out value labels
if(item->column() == 1)
{
QTableWidgetItem *neighborItem = itemAt(item->row(), item->column()-1);
QString parName = neighborItem->text();
QString parValue = item->text();
//Do not do update, then crash due to the rebuild of the QTableWidgetItems
setParameter(parName, parValue, false);
}
}
double SystemParameterTableWidget::getParameter(QString name)
{
return gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParameter(name);
}
bool SystemParameterTableWidget::hasParameter(QString name)
{
return gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->hasSystemParameter(name);
}
//! Slot that adds a System parameter value
//! @param name Lookup name for the System parameter
//! @param value Value of the System parameter
void SystemParameterTableWidget::setParameter(QString name, double value, bool doUpdate)
{
//Error check
if(!(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->setSystemParameter(name, value)))
{
QMessageBox::critical(0, "Hopsan GUI",
QString("'%1' is an invalid name for a system parameter.")
.arg(name));
return;
}
if(doUpdate)
{
update();
}
emit modifiedSystemParameter();
}
//! Slot that adds a System parameter value
//! @param name Lookup name for the System parameter
//! @param value Value of the System parameter
void SystemParameterTableWidget::setParameter(QString name, QString valueTxt, bool doUpdate)
{
//Error check
bool isDbl;
double value = valueTxt.toDouble((&isDbl));
if(!(isDbl))
{
QMessageBox::critical(0, "Hopsan GUI",
QString("'%1' is not a valid number.")
.arg(valueTxt));
QString oldValue = QString::number(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParameter(name));
QList<QTableWidgetItem *> items = selectedItems();
//Error if size() > 1, but it should not be! :)
for(int i = 0; i<items.size(); ++i)
{
items[i]->setText(oldValue);
}
}
else
{
setParameter(name, value, doUpdate);
}
}
void SystemParameterTableWidget::setParameters()
{
// if(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getNumberOfSystemParameters() > 0)
// {
for(int i=0; i<rowCount(); ++i)
{
QString name = item(i, 0)->text();
double value = item(i, 1)->text().toDouble();
setParameter(name, value);
}
// }
}
//! Slot that removes all selected System parameters in parameter table
//! @todo This shall remove the actual System parameters when they have been implemented, wherever they are stored.
void SystemParameterTableWidget::removeSelectedParameters()
{
if(gpMainWindow->mpProjectTabs->count()>0)
{
QList<QTableWidgetItem *> pSelectedItems = selectedItems();
QStringList parametersToRemove;
QString tempName;
for(int i=0; i<pSelectedItems.size(); ++i)
{
tempName = item(pSelectedItems[i]->row(),0)->text();
if(!parametersToRemove.contains(tempName))
{
parametersToRemove.append(tempName);
gpMainWindow->mpProjectTabs->getCurrentTab()->hasChanged();
}
removeCellWidget(pSelectedItems[i]->row(), pSelectedItems[i]->column());
delete pSelectedItems[i];
}
for(int j=0; j<parametersToRemove.size(); ++j)
{
std::cout << "Removing: " << parametersToRemove[j].toStdString() << std::endl;
gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->removeSystemParameter(parametersToRemove.at(j));
}
}
update();
}
//! Slot that opens "Add Parameter" dialog, where the user can add new System parameters
void SystemParameterTableWidget::openComponentPropertiesDialog()
{
QDialog *pAddComponentPropertiesDialog = new QDialog(this);
pAddComponentPropertiesDialog->setWindowTitle("Set System Parameter");
mpNameLabel = new QLabel("Name: ", this);
mpNameBox = new QLineEdit(this);
mpValueLabel = new QLabel("Value: ", this);
mpValueBox = new QLineEdit(this);
mpValueBox->setValidator(new QDoubleValidator(this));
mpAddInDialogButton = new QPushButton("Set", this);
mpDoneInDialogButton = new QPushButton("Done", this);
QDialogButtonBox *pButtonBox = new QDialogButtonBox(Qt::Horizontal);
pButtonBox->addButton(mpAddInDialogButton, QDialogButtonBox::ActionRole);
pButtonBox->addButton(mpDoneInDialogButton, QDialogButtonBox::ActionRole);
QGridLayout *pDialogLayout = new QGridLayout(this);
pDialogLayout->addWidget(mpNameLabel,0,0);
pDialogLayout->addWidget(mpNameBox,0,1);
pDialogLayout->addWidget(mpValueLabel,1,0);
pDialogLayout->addWidget(mpValueBox,1,1);
pDialogLayout->addWidget(pButtonBox,2,0,1,2);
pAddComponentPropertiesDialog->setLayout(pDialogLayout);
pAddComponentPropertiesDialog->show();
connect(mpDoneInDialogButton,SIGNAL(clicked()),pAddComponentPropertiesDialog,SLOT(close()));
connect(mpAddInDialogButton,SIGNAL(clicked()),this,SLOT(addParameter()));
}
//! @Private help slot that adds a parameter from the selected name and value in "Add Parameter" dialog
void SystemParameterTableWidget::addParameter()
{
bool ok;
setParameter(mpNameBox->text(), mpValueBox->text().toDouble(&ok));
gpMainWindow->mpProjectTabs->getCurrentTab()->hasChanged();
}
//! Updates the parameter table from the contents list
void SystemParameterTableWidget::update()
{
QMap<std::string, double>::iterator it;
QMap<std::string, double> tempMap;
tempMap.clear();
clear();
if(gpMainWindow->mpProjectTabs->count()>0)
{
tempMap = gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParametersMap();
}
if(tempMap.isEmpty())
{
setColumnCount(1);
setRowCount(1);
verticalHeader()->hide();
QTableWidgetItem *item = new QTableWidgetItem();
item->setText("No System parameters set.");
item->setBackgroundColor(QColor("white"));
item->setTextAlignment(Qt::AlignCenter);
item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
setItem(0,0,item);
}
else
{
setRowCount(0);
setColumnCount(2);
setColumnWidth(0, 120);
verticalHeader()->show();
for(it=tempMap.begin(); it!=tempMap.end(); ++it)
{
QString valueString;
valueString.setNum(it.value());
insertRow(rowCount());
QTableWidgetItem *nameItem = new QTableWidgetItem(QString(it.key().c_str()));
QTableWidgetItem *valueItem = new QTableWidgetItem(valueString);
nameItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
valueItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
setItem(rowCount()-1, 0, nameItem);
setItem(rowCount()-1, 1, valueItem);
}
}
}
<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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 name of Intel Corporation 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include "opencv2/calib3d/calib3d_c.h"
/* POSIT structure */
struct CvPOSITObject
{
int N;
float* inv_matr;
float* obj_vecs;
float* img_vecs;
};
static void icvPseudoInverse3D( float *a, float *b, int n, int method );
static CvStatus icvCreatePOSITObject( CvPoint3D32f *points,
int numPoints,
CvPOSITObject **ppObject )
{
int i;
/* Compute size of required memory */
/* buffer for inverse matrix = N*3*float */
/* buffer for storing weakImagePoints = numPoints * 2 * float */
/* buffer for storing object vectors = N*3*float */
/* buffer for storing image vectors = N*2*float */
int N = numPoints - 1;
int inv_matr_size = N * 3 * sizeof( float );
int obj_vec_size = inv_matr_size;
int img_vec_size = N * 2 * sizeof( float );
CvPOSITObject *pObject;
/* check bad arguments */
if( points == NULL )
return CV_NULLPTR_ERR;
if( numPoints < 4 )
return CV_BADSIZE_ERR;
if( ppObject == NULL )
return CV_NULLPTR_ERR;
/* memory allocation */
pObject = (CvPOSITObject *) cvAlloc( sizeof( CvPOSITObject ) +
inv_matr_size + obj_vec_size + img_vec_size );
if( !pObject )
return CV_OUTOFMEM_ERR;
/* part the memory between all structures */
pObject->N = N;
pObject->inv_matr = (float *) ((char *) pObject + sizeof( CvPOSITObject ));
pObject->obj_vecs = (float *) ((char *) (pObject->inv_matr) + inv_matr_size);
pObject->img_vecs = (float *) ((char *) (pObject->obj_vecs) + obj_vec_size);
/****************************************************************************************\
* Construct object vectors from object points *
\****************************************************************************************/
for( i = 0; i < numPoints - 1; i++ )
{
pObject->obj_vecs[i] = points[i + 1].x - points[0].x;
pObject->obj_vecs[N + i] = points[i + 1].y - points[0].y;
pObject->obj_vecs[2 * N + i] = points[i + 1].z - points[0].z;
}
/****************************************************************************************\
* Compute pseudoinverse matrix *
\****************************************************************************************/
icvPseudoInverse3D( pObject->obj_vecs, pObject->inv_matr, N, 0 );
*ppObject = pObject;
return CV_NO_ERR;
}
static CvStatus icvPOSIT( CvPOSITObject *pObject, CvPoint2D32f *imagePoints,
float focalLength, CvTermCriteria criteria,
float* rotation, float* translation )
{
int i, j, k;
int count = 0, converged = 0;
float inorm, jnorm, invInorm, invJnorm, invScale, scale = 0, inv_Z = 0;
float diff = (float)criteria.epsilon;
float inv_focalLength = 1 / focalLength;
/* Check bad arguments */
if( imagePoints == NULL )
return CV_NULLPTR_ERR;
if( pObject == NULL )
return CV_NULLPTR_ERR;
if( focalLength <= 0 )
return CV_BADFACTOR_ERR;
if( !rotation )
return CV_NULLPTR_ERR;
if( !translation )
return CV_NULLPTR_ERR;
if( (criteria.type == 0) || (criteria.type > (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS)))
return CV_BADFLAG_ERR;
if( (criteria.type & CV_TERMCRIT_EPS) && criteria.epsilon < 0 )
return CV_BADFACTOR_ERR;
if( (criteria.type & CV_TERMCRIT_ITER) && criteria.max_iter <= 0 )
return CV_BADFACTOR_ERR;
/* init variables */
int N = pObject->N;
float *objectVectors = pObject->obj_vecs;
float *invMatrix = pObject->inv_matr;
float *imgVectors = pObject->img_vecs;
while( !converged )
{
if( count == 0 )
{
/* subtract out origin to get image vectors */
for( i = 0; i < N; i++ )
{
imgVectors[i] = imagePoints[i + 1].x - imagePoints[0].x;
imgVectors[N + i] = imagePoints[i + 1].y - imagePoints[0].y;
}
}
else
{
diff = 0;
/* Compute new SOP (scaled orthograthic projection) image from pose */
for( i = 0; i < N; i++ )
{
/* objectVector * k */
float old;
float tmp = objectVectors[i] * rotation[6] /*[2][0]*/ +
objectVectors[N + i] * rotation[7] /*[2][1]*/ +
objectVectors[2 * N + i] * rotation[8] /*[2][2]*/;
tmp *= inv_Z;
tmp += 1;
old = imgVectors[i];
imgVectors[i] = imagePoints[i + 1].x * tmp - imagePoints[0].x;
diff = MAX( diff, (float) fabs( imgVectors[i] - old ));
old = imgVectors[N + i];
imgVectors[N + i] = imagePoints[i + 1].y * tmp - imagePoints[0].y;
diff = MAX( diff, (float) fabs( imgVectors[N + i] - old ));
}
}
/* calculate I and J vectors */
for( i = 0; i < 2; i++ )
{
for( j = 0; j < 3; j++ )
{
rotation[3*i+j] /*[i][j]*/ = 0;
for( k = 0; k < N; k++ )
{
rotation[3*i+j] /*[i][j]*/ += invMatrix[j * N + k] * imgVectors[i * N + k];
}
}
}
inorm = rotation[0] /*[0][0]*/ * rotation[0] /*[0][0]*/ +
rotation[1] /*[0][1]*/ * rotation[1] /*[0][1]*/ +
rotation[2] /*[0][2]*/ * rotation[2] /*[0][2]*/;
jnorm = rotation[3] /*[1][0]*/ * rotation[3] /*[1][0]*/ +
rotation[4] /*[1][1]*/ * rotation[4] /*[1][1]*/ +
rotation[5] /*[1][2]*/ * rotation[5] /*[1][2]*/;
invInorm = cvInvSqrt( inorm );
invJnorm = cvInvSqrt( jnorm );
inorm *= invInorm;
jnorm *= invJnorm;
rotation[0] /*[0][0]*/ *= invInorm;
rotation[1] /*[0][1]*/ *= invInorm;
rotation[2] /*[0][2]*/ *= invInorm;
rotation[3] /*[1][0]*/ *= invJnorm;
rotation[4] /*[1][1]*/ *= invJnorm;
rotation[5] /*[1][2]*/ *= invJnorm;
/* row2 = row0 x row1 (cross product) */
rotation[6] /*->m[2][0]*/ = rotation[1] /*->m[0][1]*/ * rotation[5] /*->m[1][2]*/ -
rotation[2] /*->m[0][2]*/ * rotation[4] /*->m[1][1]*/;
rotation[7] /*->m[2][1]*/ = rotation[2] /*->m[0][2]*/ * rotation[3] /*->m[1][0]*/ -
rotation[0] /*->m[0][0]*/ * rotation[5] /*->m[1][2]*/;
rotation[8] /*->m[2][2]*/ = rotation[0] /*->m[0][0]*/ * rotation[4] /*->m[1][1]*/ -
rotation[1] /*->m[0][1]*/ * rotation[3] /*->m[1][0]*/;
scale = (inorm + jnorm) / 2.0f;
inv_Z = scale * inv_focalLength;
count++;
converged = ((criteria.type & CV_TERMCRIT_EPS) && (diff < criteria.epsilon));
converged |= ((criteria.type & CV_TERMCRIT_ITER) && (count == criteria.max_iter));
}
invScale = 1 / scale;
translation[0] = imagePoints[0].x * invScale;
translation[1] = imagePoints[0].y * invScale;
translation[2] = 1 / inv_Z;
return CV_NO_ERR;
}
static CvStatus icvReleasePOSITObject( CvPOSITObject ** ppObject )
{
cvFree( ppObject );
return CV_NO_ERR;
}
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: icvPseudoInverse3D
// Purpose: Pseudoinverse N x 3 matrix N >= 3
// Context:
// Parameters:
// a - input matrix
// b - pseudoinversed a
// n - number of rows in a
// method - if 0, then b = inv(transpose(a)*a) * transpose(a)
// if 1, then SVD used.
// Returns:
// Notes: Both matrix are stored by n-dimensional vectors.
// Now only method == 0 supported.
//F*/
void
icvPseudoInverse3D( float *a, float *b, int n, int method )
{
int k;
if( method == 0 )
{
float ata00 = 0;
float ata11 = 0;
float ata22 = 0;
float ata01 = 0;
float ata02 = 0;
float ata12 = 0;
float det = 0;
/* compute matrix ata = transpose(a) * a */
for( k = 0; k < n; k++ )
{
float a0 = a[k];
float a1 = a[n + k];
float a2 = a[2 * n + k];
ata00 += a0 * a0;
ata11 += a1 * a1;
ata22 += a2 * a2;
ata01 += a0 * a1;
ata02 += a0 * a2;
ata12 += a1 * a2;
}
/* inverse matrix ata */
{
float inv_det;
float p00 = ata11 * ata22 - ata12 * ata12;
float p01 = -(ata01 * ata22 - ata12 * ata02);
float p02 = ata12 * ata01 - ata11 * ata02;
float p11 = ata00 * ata22 - ata02 * ata02;
float p12 = -(ata00 * ata12 - ata01 * ata02);
float p22 = ata00 * ata11 - ata01 * ata01;
det += ata00 * p00;
det += ata01 * p01;
det += ata02 * p02;
inv_det = 1 / det;
/* compute resultant matrix */
for( k = 0; k < n; k++ )
{
float a0 = a[k];
float a1 = a[n + k];
float a2 = a[2 * n + k];
b[k] = (p00 * a0 + p01 * a1 + p02 * a2) * inv_det;
b[n + k] = (p01 * a0 + p11 * a1 + p12 * a2) * inv_det;
b[2 * n + k] = (p02 * a0 + p12 * a1 + p22 * a2) * inv_det;
}
}
}
/*if ( method == 1 )
{
}
*/
return;
}
CV_IMPL CvPOSITObject *
cvCreatePOSITObject( CvPoint3D32f * points, int numPoints )
{
CvPOSITObject *pObject = 0;
IPPI_CALL( icvCreatePOSITObject( points, numPoints, &pObject ));
return pObject;
}
CV_IMPL void
cvPOSIT( CvPOSITObject * pObject, CvPoint2D32f * imagePoints,
double focalLength, CvTermCriteria criteria,
float* rotation, float* translation )
{
IPPI_CALL( icvPOSIT( pObject, imagePoints,(float) focalLength, criteria,
rotation, translation ));
}
CV_IMPL void
cvReleasePOSITObject( CvPOSITObject ** ppObject )
{
IPPI_CALL( icvReleasePOSITObject( ppObject ));
}
/* End of file. */
<commit_msg>Prevent division by zero<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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 name of Intel Corporation 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include "opencv2/calib3d/calib3d_c.h"
/* POSIT structure */
struct CvPOSITObject
{
int N;
float* inv_matr;
float* obj_vecs;
float* img_vecs;
};
static void icvPseudoInverse3D( float *a, float *b, int n, int method );
static CvStatus icvCreatePOSITObject( CvPoint3D32f *points,
int numPoints,
CvPOSITObject **ppObject )
{
int i;
/* Compute size of required memory */
/* buffer for inverse matrix = N*3*float */
/* buffer for storing weakImagePoints = numPoints * 2 * float */
/* buffer for storing object vectors = N*3*float */
/* buffer for storing image vectors = N*2*float */
int N = numPoints - 1;
int inv_matr_size = N * 3 * sizeof( float );
int obj_vec_size = inv_matr_size;
int img_vec_size = N * 2 * sizeof( float );
CvPOSITObject *pObject;
/* check bad arguments */
if( points == NULL )
return CV_NULLPTR_ERR;
if( numPoints < 4 )
return CV_BADSIZE_ERR;
if( ppObject == NULL )
return CV_NULLPTR_ERR;
/* memory allocation */
pObject = (CvPOSITObject *) cvAlloc( sizeof( CvPOSITObject ) +
inv_matr_size + obj_vec_size + img_vec_size );
if( !pObject )
return CV_OUTOFMEM_ERR;
/* part the memory between all structures */
pObject->N = N;
pObject->inv_matr = (float *) ((char *) pObject + sizeof( CvPOSITObject ));
pObject->obj_vecs = (float *) ((char *) (pObject->inv_matr) + inv_matr_size);
pObject->img_vecs = (float *) ((char *) (pObject->obj_vecs) + obj_vec_size);
/****************************************************************************************\
* Construct object vectors from object points *
\****************************************************************************************/
for( i = 0; i < numPoints - 1; i++ )
{
pObject->obj_vecs[i] = points[i + 1].x - points[0].x;
pObject->obj_vecs[N + i] = points[i + 1].y - points[0].y;
pObject->obj_vecs[2 * N + i] = points[i + 1].z - points[0].z;
}
/****************************************************************************************\
* Compute pseudoinverse matrix *
\****************************************************************************************/
icvPseudoInverse3D( pObject->obj_vecs, pObject->inv_matr, N, 0 );
*ppObject = pObject;
return CV_NO_ERR;
}
static CvStatus icvPOSIT( CvPOSITObject *pObject, CvPoint2D32f *imagePoints,
float focalLength, CvTermCriteria criteria,
float* rotation, float* translation )
{
int i, j, k;
int count = 0, converged = 0;
float inorm, jnorm, invInorm, invJnorm, invScale, scale = 0, inv_Z = 0;
float diff = (float)criteria.epsilon;
/* Check bad arguments */
if( imagePoints == NULL )
return CV_NULLPTR_ERR;
if( pObject == NULL )
return CV_NULLPTR_ERR;
if( focalLength <= 0 )
return CV_BADFACTOR_ERR;
if( !rotation )
return CV_NULLPTR_ERR;
if( !translation )
return CV_NULLPTR_ERR;
if( (criteria.type == 0) || (criteria.type > (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS)))
return CV_BADFLAG_ERR;
if( (criteria.type & CV_TERMCRIT_EPS) && criteria.epsilon < 0 )
return CV_BADFACTOR_ERR;
if( (criteria.type & CV_TERMCRIT_ITER) && criteria.max_iter <= 0 )
return CV_BADFACTOR_ERR;
/* init variables */
float inv_focalLength = 1 / focalLength;
int N = pObject->N;
float *objectVectors = pObject->obj_vecs;
float *invMatrix = pObject->inv_matr;
float *imgVectors = pObject->img_vecs;
while( !converged )
{
if( count == 0 )
{
/* subtract out origin to get image vectors */
for( i = 0; i < N; i++ )
{
imgVectors[i] = imagePoints[i + 1].x - imagePoints[0].x;
imgVectors[N + i] = imagePoints[i + 1].y - imagePoints[0].y;
}
}
else
{
diff = 0;
/* Compute new SOP (scaled orthograthic projection) image from pose */
for( i = 0; i < N; i++ )
{
/* objectVector * k */
float old;
float tmp = objectVectors[i] * rotation[6] /*[2][0]*/ +
objectVectors[N + i] * rotation[7] /*[2][1]*/ +
objectVectors[2 * N + i] * rotation[8] /*[2][2]*/;
tmp *= inv_Z;
tmp += 1;
old = imgVectors[i];
imgVectors[i] = imagePoints[i + 1].x * tmp - imagePoints[0].x;
diff = MAX( diff, (float) fabs( imgVectors[i] - old ));
old = imgVectors[N + i];
imgVectors[N + i] = imagePoints[i + 1].y * tmp - imagePoints[0].y;
diff = MAX( diff, (float) fabs( imgVectors[N + i] - old ));
}
}
/* calculate I and J vectors */
for( i = 0; i < 2; i++ )
{
for( j = 0; j < 3; j++ )
{
rotation[3*i+j] /*[i][j]*/ = 0;
for( k = 0; k < N; k++ )
{
rotation[3*i+j] /*[i][j]*/ += invMatrix[j * N + k] * imgVectors[i * N + k];
}
}
}
inorm = rotation[0] /*[0][0]*/ * rotation[0] /*[0][0]*/ +
rotation[1] /*[0][1]*/ * rotation[1] /*[0][1]*/ +
rotation[2] /*[0][2]*/ * rotation[2] /*[0][2]*/;
jnorm = rotation[3] /*[1][0]*/ * rotation[3] /*[1][0]*/ +
rotation[4] /*[1][1]*/ * rotation[4] /*[1][1]*/ +
rotation[5] /*[1][2]*/ * rotation[5] /*[1][2]*/;
invInorm = cvInvSqrt( inorm );
invJnorm = cvInvSqrt( jnorm );
inorm *= invInorm;
jnorm *= invJnorm;
rotation[0] /*[0][0]*/ *= invInorm;
rotation[1] /*[0][1]*/ *= invInorm;
rotation[2] /*[0][2]*/ *= invInorm;
rotation[3] /*[1][0]*/ *= invJnorm;
rotation[4] /*[1][1]*/ *= invJnorm;
rotation[5] /*[1][2]*/ *= invJnorm;
/* row2 = row0 x row1 (cross product) */
rotation[6] /*->m[2][0]*/ = rotation[1] /*->m[0][1]*/ * rotation[5] /*->m[1][2]*/ -
rotation[2] /*->m[0][2]*/ * rotation[4] /*->m[1][1]*/;
rotation[7] /*->m[2][1]*/ = rotation[2] /*->m[0][2]*/ * rotation[3] /*->m[1][0]*/ -
rotation[0] /*->m[0][0]*/ * rotation[5] /*->m[1][2]*/;
rotation[8] /*->m[2][2]*/ = rotation[0] /*->m[0][0]*/ * rotation[4] /*->m[1][1]*/ -
rotation[1] /*->m[0][1]*/ * rotation[3] /*->m[1][0]*/;
scale = (inorm + jnorm) / 2.0f;
inv_Z = scale * inv_focalLength;
count++;
converged = ((criteria.type & CV_TERMCRIT_EPS) && (diff < criteria.epsilon));
converged |= ((criteria.type & CV_TERMCRIT_ITER) && (count == criteria.max_iter));
}
invScale = 1 / scale;
translation[0] = imagePoints[0].x * invScale;
translation[1] = imagePoints[0].y * invScale;
translation[2] = 1 / inv_Z;
return CV_NO_ERR;
}
static CvStatus icvReleasePOSITObject( CvPOSITObject ** ppObject )
{
cvFree( ppObject );
return CV_NO_ERR;
}
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: icvPseudoInverse3D
// Purpose: Pseudoinverse N x 3 matrix N >= 3
// Context:
// Parameters:
// a - input matrix
// b - pseudoinversed a
// n - number of rows in a
// method - if 0, then b = inv(transpose(a)*a) * transpose(a)
// if 1, then SVD used.
// Returns:
// Notes: Both matrix are stored by n-dimensional vectors.
// Now only method == 0 supported.
//F*/
void
icvPseudoInverse3D( float *a, float *b, int n, int method )
{
int k;
if( method == 0 )
{
float ata00 = 0;
float ata11 = 0;
float ata22 = 0;
float ata01 = 0;
float ata02 = 0;
float ata12 = 0;
float det = 0;
/* compute matrix ata = transpose(a) * a */
for( k = 0; k < n; k++ )
{
float a0 = a[k];
float a1 = a[n + k];
float a2 = a[2 * n + k];
ata00 += a0 * a0;
ata11 += a1 * a1;
ata22 += a2 * a2;
ata01 += a0 * a1;
ata02 += a0 * a2;
ata12 += a1 * a2;
}
/* inverse matrix ata */
{
float inv_det;
float p00 = ata11 * ata22 - ata12 * ata12;
float p01 = -(ata01 * ata22 - ata12 * ata02);
float p02 = ata12 * ata01 - ata11 * ata02;
float p11 = ata00 * ata22 - ata02 * ata02;
float p12 = -(ata00 * ata12 - ata01 * ata02);
float p22 = ata00 * ata11 - ata01 * ata01;
det += ata00 * p00;
det += ata01 * p01;
det += ata02 * p02;
inv_det = 1 / det;
/* compute resultant matrix */
for( k = 0; k < n; k++ )
{
float a0 = a[k];
float a1 = a[n + k];
float a2 = a[2 * n + k];
b[k] = (p00 * a0 + p01 * a1 + p02 * a2) * inv_det;
b[n + k] = (p01 * a0 + p11 * a1 + p12 * a2) * inv_det;
b[2 * n + k] = (p02 * a0 + p12 * a1 + p22 * a2) * inv_det;
}
}
}
/*if ( method == 1 )
{
}
*/
return;
}
CV_IMPL CvPOSITObject *
cvCreatePOSITObject( CvPoint3D32f * points, int numPoints )
{
CvPOSITObject *pObject = 0;
IPPI_CALL( icvCreatePOSITObject( points, numPoints, &pObject ));
return pObject;
}
CV_IMPL void
cvPOSIT( CvPOSITObject * pObject, CvPoint2D32f * imagePoints,
double focalLength, CvTermCriteria criteria,
float* rotation, float* translation )
{
IPPI_CALL( icvPOSIT( pObject, imagePoints,(float) focalLength, criteria,
rotation, translation ));
}
CV_IMPL void
cvReleasePOSITObject( CvPOSITObject ** ppObject )
{
IPPI_CALL( icvReleasePOSITObject( ppObject ));
}
/* End of file. */
<|endoftext|>
|
<commit_before>// bdlt_datetimeinterval.cpp -*-C++-*-
#include <bdlt_datetimeinterval.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdlt_datetimeinterval_cpp,"$Id$ $CSID$")
#ifdef BSLS_PLATFORM_OS_WINDOWS
# define copysign _copysign
#endif
#include <bdlb_bitutil.h>
#include <bslim_printer.h>
#include <bslmf_assert.h>
#include <bsls_libraryfeatures.h>
#include <bsls_platform.h>
#include <bsl_cstdio.h> // 'sprintf'
#include <bsl_ostream.h>
#include <cmath>
namespace BloombergLP {
// Assert fundamental assumptions made in the implementation.
BSLMF_ASSERT(-3 / 2 == -1);
BSLMF_ASSERT(-5 % 4 == -1);
namespace bdlt {
// STATIC HELPER FUNCTIONS
static
int printToBufferFormatted(char *result,
int numBytes,
const char *spec,
int day,
int hour,
int minute,
int second,
int microsecond,
int fractionalSecondPrecision)
{
#if defined(BSLS_LIBRARYFEATURES_HAS_C99_SNPRINTF)
return 0 == fractionalSecondPrecision
? bsl::snprintf(result,
numBytes,
spec,
day,
hour,
minute,
second)
: bsl::snprintf(result,
numBytes,
spec,
day,
hour,
minute,
second,
microsecond);
#elif defined(BSLS_PLATFORM_CMP_MSVC)
// Windows uses a different variant of snprintf that does not necessarily
// null-terminate and returns -1 (or 'numBytes') on overflow.
int rc;
if (0 == fractionalSecondPrecision) {
rc = _snprintf(result,
numBytes,
spec,
day,
hour,
minute,
second);
}
else {
rc = _snprintf(result,
numBytes,
spec,
day,
hour,
minute,
second,
microsecond);
}
if (0 > rc || rc == numBytes) {
if (numBytes > 0) {
result[numBytes - 1] = '\0'; // Make sure to null-terminate on
// overflow.
}
// Need to determine the length that would have been printed without
// overflow.
if (0 == fractionalSecondPrecision) {
// '_' hh: mm: ss
rc = 1 + 3 + 3 + 2;
}
else {
// '_' hh: mm: ss. mmm uuu
rc = 1 + 3 + 3 + 3 + fractionalSecondPrecision;
}
if (-10 < day && 10 > day) {
rc += 1;
}
else if (-100 < day && 100 > day) {
rc += 2;
}
else if (-1000 < day && 1000 > day) {
rc += 3;
}
else if (-10000 < day && 10000 > day) {
rc += 4;
}
else if (-100000 < day && 100000 > day) {
rc += 5;
}
else if (-1000000 < day && 1000000 > day) {
rc += 6;
}
else if (-10000000 < day && 10000000 > day) {
rc += 7;
}
else if (-100000000 < day && 100000000 > day) {
rc += 8;
}
else if (-1000000000 < day && 1000000000 > day) {
rc += 9;
}
else {
rc += 10;
}
}
return rc;
#else
# error THIS CONFIGURATION DOES NOT SUPPORT 'snprintf'
#endif
}
// ----------------------
// class DatetimeInterval
// ----------------------
// PRIVATE MANIPULATORS
void DatetimeInterval::assign(bsls::Types::Int64 days,
bsls::Types::Int64 microseconds)
{
days += microseconds / TimeUnitRatio::k_US_PER_D;
microseconds %= TimeUnitRatio::k_US_PER_D;
if (days > 0 && microseconds < 0) {
--days;
microseconds += TimeUnitRatio::k_US_PER_D;
}
else if (days < 0 && microseconds > 0) {
++days;
microseconds -= TimeUnitRatio::k_US_PER_D;
}
BSLS_ASSERT(days <= bsl::numeric_limits<int32_t>::max());
BSLS_ASSERT(days >= bsl::numeric_limits<int32_t>::min());
d_days = static_cast<int>(days);
d_microseconds = microseconds;
}
// MANIPULATORS
void DatetimeInterval::setTotalSecondsFromDouble(double seconds)
{
double wholeDays;
modf(seconds / TimeUnitRatio::k_S_PER_D, &wholeDays);
// Ignoring fractional part to maintain as much accuracy from
// 'seconds' as possible.
BSLS_ASSERT(bsl::numeric_limits<bsls::Types::Int64>::max() >=
fabs(wholeDays));
// Failing for bsl::numeric_limits<bsls::Types::Int64>::min() is OK
// here, because wholeDays has to fit into 32 bits. Here we're just
// checking that we are not about to run into UB when casting to
// bsls::Types::Int64.
volatile double microseconds =
(seconds - wholeDays * TimeUnitRatio::k_S_PER_D)
* TimeUnitRatio::k_US_PER_S + copysign(0.5, seconds);
// On GCC x86 platforms we have to force copying a floating-point value
// to memory using 'volatile' type qualifier to round-down the value
// stored in x87 unit register.
assign(static_cast<bsls::Types::Int64>(wholeDays),
static_cast<bsls::Types::Int64>(microseconds));
}
DatetimeInterval& DatetimeInterval::addInterval(
int days,
bsls::Types::Int64 hours,
bsls::Types::Int64 minutes,
bsls::Types::Int64 seconds,
bsls::Types::Int64 milliseconds,
bsls::Types::Int64 microseconds)
{
bsls::Types::Int64 d = static_cast<bsls::Types::Int64>(days)
+ hours / TimeUnitRatio::k_H_PER_D
+ minutes / TimeUnitRatio::k_M_PER_D
+ seconds / TimeUnitRatio::k_S_PER_D
+ milliseconds / TimeUnitRatio::k_MS_PER_D
+ microseconds / TimeUnitRatio::k_US_PER_D;
hours %= TimeUnitRatio::k_H_PER_D;
minutes %= TimeUnitRatio::k_M_PER_D;
seconds %= TimeUnitRatio::k_S_PER_D;
milliseconds %= TimeUnitRatio::k_MS_PER_D;
microseconds %= TimeUnitRatio::k_US_PER_D;
bsls::Types::Int64 us = hours * TimeUnitRatio::k_US_PER_H
+ minutes * TimeUnitRatio::k_US_PER_M
+ seconds * TimeUnitRatio::k_US_PER_S
+ milliseconds * TimeUnitRatio::k_US_PER_MS
+ microseconds;
assign(static_cast<bsls::Types::Int64>(d_days) + d,
d_microseconds + us);
return *this;
}
void DatetimeInterval::setInterval(int days,
bsls::Types::Int64 hours,
bsls::Types::Int64 minutes,
bsls::Types::Int64 seconds,
bsls::Types::Int64 milliseconds,
bsls::Types::Int64 microseconds)
{
bsls::Types::Int64 d = static_cast<bsls::Types::Int64>(days)
+ hours / TimeUnitRatio::k_H_PER_D
+ minutes / TimeUnitRatio::k_M_PER_D
+ seconds / TimeUnitRatio::k_S_PER_D
+ milliseconds / TimeUnitRatio::k_MS_PER_D
+ microseconds / TimeUnitRatio::k_US_PER_D;
hours %= TimeUnitRatio::k_H_PER_D;
minutes %= TimeUnitRatio::k_M_PER_D;
seconds %= TimeUnitRatio::k_S_PER_D;
milliseconds %= TimeUnitRatio::k_MS_PER_D;
microseconds %= TimeUnitRatio::k_US_PER_D;
bsls::Types::Int64 us = hours * TimeUnitRatio::k_US_PER_H
+ minutes * TimeUnitRatio::k_US_PER_M
+ seconds * TimeUnitRatio::k_US_PER_S
+ milliseconds * TimeUnitRatio::k_US_PER_MS
+ microseconds;
assign(d, us);
}
// ACCESSORS
// Aspects
int DatetimeInterval::printToBuffer(char *result,
int numBytes,
int fractionalSecondPrecision) const
{
BSLS_ASSERT(result);
BSLS_ASSERT(0 <= numBytes);
BSLS_ASSERT(0 <= fractionalSecondPrecision );
BSLS_ASSERT( fractionalSecondPrecision <= 6);
int d = days();
int h = hours();
int m = minutes();
int s = seconds();
int ms = milliseconds();
int us = microseconds();
// Values with a non-negative day component will have the sign
// "pre-printed".
int printedLength = 0;
if (0 <= d_days) {
if (1 < numBytes) {
if (0 <= d_microseconds) {
*result++ = '+';
}
else {
*result++ = '-';
}
--numBytes;
}
printedLength = 1;
}
// Invert the time component values when the value is negative.
if (0 > d_days || 0 > d_microseconds) {
h = -h;
m = -m;
s = -s;
ms = -ms;
us = -us;
}
int value;
switch (fractionalSecondPrecision) {
case 0: {
char spec[] = "%d_%02d:%02d:%02d";
// Add one for the sign.
return printToBufferFormatted(result,
numBytes,
spec,
d,
h,
m,
s,
0,
0) + printedLength; // RETURN
} break;
case 1: {
value = ms / 100;
} break;
case 2: {
value = ms / 10 ;
} break;
case 3: {
value = ms;
} break;
case 4: {
value = ms * 10 + us / 100;
} break;
case 5: {
value = ms * 100 + us / 10;
} break;
default: {
value = ms * 1000 + us;
} break;
}
char spec[] = "%d_%02d:%02d:%02d.%0Xd";
const int PRECISION_INDEX = sizeof spec - 3;
spec[PRECISION_INDEX] = static_cast<char>('0' + fractionalSecondPrecision);
// Add one for the sign.
return printToBufferFormatted(result,
numBytes,
spec,
d,
h,
m,
s,
value,
fractionalSecondPrecision) + printedLength;
}
bsl::ostream& DatetimeInterval::print(bsl::ostream& stream,
int level,
int spacesPerLevel) const
{
// Format the output to a buffer first instead of inserting into 'stream'
// directly to improve performance and in case the caller has done
// something like:
//..
// os << bsl::setw(20) << myInterval;
//..
// The user-specified width will be effective when 'buffer' is written to
// the 'stream' (below).
const int k_BUFFER_SIZE = 32;
char buffer[k_BUFFER_SIZE];
int rc = printToBuffer(buffer,
k_BUFFER_SIZE,
k_DEFAULT_FRACTIONAL_SECOND_PRECISION);
(void)rc;
bslim::Printer printer(&stream, level, spacesPerLevel);
printer.start(true); // 'true' -> suppress '['
stream << buffer;
printer.end(true); // 'true' -> suppress ']'
return stream;
}
#ifndef BDE_OMIT_INTERNAL_DEPRECATED // BDE2.22
// DEPRECATED METHODS
bsl::ostream& DatetimeInterval::streamOut(bsl::ostream& stream) const
{
return stream << *this;
}
#endif // BDE_OMIT_INTERNAL_DEPRECATED -- BDE2.22
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2017 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>correct compiler warning (#2328)<commit_after>// bdlt_datetimeinterval.cpp -*-C++-*-
#include <bdlt_datetimeinterval.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdlt_datetimeinterval_cpp,"$Id$ $CSID$")
#ifdef BSLS_PLATFORM_OS_WINDOWS
# define copysign _copysign
#endif
#include <bdlb_bitutil.h>
#include <bslim_printer.h>
#include <bslmf_assert.h>
#include <bsls_libraryfeatures.h>
#include <bsls_platform.h>
#include <bsl_cstdio.h> // 'sprintf'
#include <bsl_ostream.h>
#include <cmath>
namespace BloombergLP {
// Assert fundamental assumptions made in the implementation.
BSLMF_ASSERT(-3 / 2 == -1);
BSLMF_ASSERT(-5 % 4 == -1);
namespace bdlt {
// STATIC HELPER FUNCTIONS
static
int printToBufferFormatted(char *result,
int numBytes,
const char *spec,
int day,
int hour,
int minute,
int second,
int microsecond,
int fractionalSecondPrecision)
{
#if defined(BSLS_LIBRARYFEATURES_HAS_C99_SNPRINTF)
return 0 == fractionalSecondPrecision
? bsl::snprintf(result,
numBytes,
spec,
day,
hour,
minute,
second)
: bsl::snprintf(result,
numBytes,
spec,
day,
hour,
minute,
second,
microsecond);
#elif defined(BSLS_PLATFORM_CMP_MSVC)
// Windows uses a different variant of snprintf that does not necessarily
// null-terminate and returns -1 (or 'numBytes') on overflow.
int rc;
if (0 == fractionalSecondPrecision) {
rc = _snprintf(result,
numBytes,
spec,
day,
hour,
minute,
second);
}
else {
rc = _snprintf(result,
numBytes,
spec,
day,
hour,
minute,
second,
microsecond);
}
if (0 > rc || rc == numBytes) {
if (numBytes > 0) {
result[numBytes - 1] = '\0'; // Make sure to null-terminate on
// overflow.
}
// Need to determine the length that would have been printed without
// overflow.
if (0 == fractionalSecondPrecision) {
// '_' hh: mm: ss
rc = 1 + 3 + 3 + 2;
}
else {
// '_' hh: mm: ss. mmm uuu
rc = 1 + 3 + 3 + 3 + fractionalSecondPrecision;
}
if (-10 < day && 10 > day) {
rc += 1;
}
else if (-100 < day && 100 > day) {
rc += 2;
}
else if (-1000 < day && 1000 > day) {
rc += 3;
}
else if (-10000 < day && 10000 > day) {
rc += 4;
}
else if (-100000 < day && 100000 > day) {
rc += 5;
}
else if (-1000000 < day && 1000000 > day) {
rc += 6;
}
else if (-10000000 < day && 10000000 > day) {
rc += 7;
}
else if (-100000000 < day && 100000000 > day) {
rc += 8;
}
else if (-1000000000 < day && 1000000000 > day) {
rc += 9;
}
else {
rc += 10;
}
}
return rc;
#else
# error THIS CONFIGURATION DOES NOT SUPPORT 'snprintf'
#endif
}
// ----------------------
// class DatetimeInterval
// ----------------------
// PRIVATE MANIPULATORS
void DatetimeInterval::assign(bsls::Types::Int64 days,
bsls::Types::Int64 microseconds)
{
days += microseconds / TimeUnitRatio::k_US_PER_D;
microseconds %= TimeUnitRatio::k_US_PER_D;
if (days > 0 && microseconds < 0) {
--days;
microseconds += TimeUnitRatio::k_US_PER_D;
}
else if (days < 0 && microseconds > 0) {
++days;
microseconds -= TimeUnitRatio::k_US_PER_D;
}
BSLS_ASSERT(days <= bsl::numeric_limits<int32_t>::max());
BSLS_ASSERT(days >= bsl::numeric_limits<int32_t>::min());
d_days = static_cast<int>(days);
d_microseconds = microseconds;
}
// MANIPULATORS
void DatetimeInterval::setTotalSecondsFromDouble(double seconds)
{
double wholeDays;
modf(seconds / TimeUnitRatio::k_S_PER_D, &wholeDays);
// Ignoring fractional part to maintain as much accuracy from
// 'seconds' as possible.
BSLS_ASSERT(static_cast<double>(
bsl::numeric_limits<bsls::Types::Int64>::max()) >=
fabs(wholeDays));
// Failing for bsl::numeric_limits<bsls::Types::Int64>::min() is OK
// here, because wholeDays has to fit into 32 bits. Here we're just
// checking that we are not about to run into UB when casting to
// bsls::Types::Int64.
volatile double microseconds =
(seconds - wholeDays * TimeUnitRatio::k_S_PER_D)
* TimeUnitRatio::k_US_PER_S + copysign(0.5, seconds);
// On GCC x86 platforms we have to force copying a floating-point value
// to memory using 'volatile' type qualifier to round-down the value
// stored in x87 unit register.
assign(static_cast<bsls::Types::Int64>(wholeDays),
static_cast<bsls::Types::Int64>(microseconds));
}
DatetimeInterval& DatetimeInterval::addInterval(
int days,
bsls::Types::Int64 hours,
bsls::Types::Int64 minutes,
bsls::Types::Int64 seconds,
bsls::Types::Int64 milliseconds,
bsls::Types::Int64 microseconds)
{
bsls::Types::Int64 d = static_cast<bsls::Types::Int64>(days)
+ hours / TimeUnitRatio::k_H_PER_D
+ minutes / TimeUnitRatio::k_M_PER_D
+ seconds / TimeUnitRatio::k_S_PER_D
+ milliseconds / TimeUnitRatio::k_MS_PER_D
+ microseconds / TimeUnitRatio::k_US_PER_D;
hours %= TimeUnitRatio::k_H_PER_D;
minutes %= TimeUnitRatio::k_M_PER_D;
seconds %= TimeUnitRatio::k_S_PER_D;
milliseconds %= TimeUnitRatio::k_MS_PER_D;
microseconds %= TimeUnitRatio::k_US_PER_D;
bsls::Types::Int64 us = hours * TimeUnitRatio::k_US_PER_H
+ minutes * TimeUnitRatio::k_US_PER_M
+ seconds * TimeUnitRatio::k_US_PER_S
+ milliseconds * TimeUnitRatio::k_US_PER_MS
+ microseconds;
assign(static_cast<bsls::Types::Int64>(d_days) + d,
d_microseconds + us);
return *this;
}
void DatetimeInterval::setInterval(int days,
bsls::Types::Int64 hours,
bsls::Types::Int64 minutes,
bsls::Types::Int64 seconds,
bsls::Types::Int64 milliseconds,
bsls::Types::Int64 microseconds)
{
bsls::Types::Int64 d = static_cast<bsls::Types::Int64>(days)
+ hours / TimeUnitRatio::k_H_PER_D
+ minutes / TimeUnitRatio::k_M_PER_D
+ seconds / TimeUnitRatio::k_S_PER_D
+ milliseconds / TimeUnitRatio::k_MS_PER_D
+ microseconds / TimeUnitRatio::k_US_PER_D;
hours %= TimeUnitRatio::k_H_PER_D;
minutes %= TimeUnitRatio::k_M_PER_D;
seconds %= TimeUnitRatio::k_S_PER_D;
milliseconds %= TimeUnitRatio::k_MS_PER_D;
microseconds %= TimeUnitRatio::k_US_PER_D;
bsls::Types::Int64 us = hours * TimeUnitRatio::k_US_PER_H
+ minutes * TimeUnitRatio::k_US_PER_M
+ seconds * TimeUnitRatio::k_US_PER_S
+ milliseconds * TimeUnitRatio::k_US_PER_MS
+ microseconds;
assign(d, us);
}
// ACCESSORS
// Aspects
int DatetimeInterval::printToBuffer(char *result,
int numBytes,
int fractionalSecondPrecision) const
{
BSLS_ASSERT(result);
BSLS_ASSERT(0 <= numBytes);
BSLS_ASSERT(0 <= fractionalSecondPrecision );
BSLS_ASSERT( fractionalSecondPrecision <= 6);
int d = days();
int h = hours();
int m = minutes();
int s = seconds();
int ms = milliseconds();
int us = microseconds();
// Values with a non-negative day component will have the sign
// "pre-printed".
int printedLength = 0;
if (0 <= d_days) {
if (1 < numBytes) {
if (0 <= d_microseconds) {
*result++ = '+';
}
else {
*result++ = '-';
}
--numBytes;
}
printedLength = 1;
}
// Invert the time component values when the value is negative.
if (0 > d_days || 0 > d_microseconds) {
h = -h;
m = -m;
s = -s;
ms = -ms;
us = -us;
}
int value;
switch (fractionalSecondPrecision) {
case 0: {
char spec[] = "%d_%02d:%02d:%02d";
// Add one for the sign.
return printToBufferFormatted(result,
numBytes,
spec,
d,
h,
m,
s,
0,
0) + printedLength; // RETURN
} break;
case 1: {
value = ms / 100;
} break;
case 2: {
value = ms / 10 ;
} break;
case 3: {
value = ms;
} break;
case 4: {
value = ms * 10 + us / 100;
} break;
case 5: {
value = ms * 100 + us / 10;
} break;
default: {
value = ms * 1000 + us;
} break;
}
char spec[] = "%d_%02d:%02d:%02d.%0Xd";
const int PRECISION_INDEX = sizeof spec - 3;
spec[PRECISION_INDEX] = static_cast<char>('0' + fractionalSecondPrecision);
// Add one for the sign.
return printToBufferFormatted(result,
numBytes,
spec,
d,
h,
m,
s,
value,
fractionalSecondPrecision) + printedLength;
}
bsl::ostream& DatetimeInterval::print(bsl::ostream& stream,
int level,
int spacesPerLevel) const
{
// Format the output to a buffer first instead of inserting into 'stream'
// directly to improve performance and in case the caller has done
// something like:
//..
// os << bsl::setw(20) << myInterval;
//..
// The user-specified width will be effective when 'buffer' is written to
// the 'stream' (below).
const int k_BUFFER_SIZE = 32;
char buffer[k_BUFFER_SIZE];
int rc = printToBuffer(buffer,
k_BUFFER_SIZE,
k_DEFAULT_FRACTIONAL_SECOND_PRECISION);
(void)rc;
bslim::Printer printer(&stream, level, spacesPerLevel);
printer.start(true); // 'true' -> suppress '['
stream << buffer;
printer.end(true); // 'true' -> suppress ']'
return stream;
}
#ifndef BDE_OMIT_INTERNAL_DEPRECATED // BDE2.22
// DEPRECATED METHODS
bsl::ostream& DatetimeInterval::streamOut(bsl::ostream& stream) const
{
return stream << *this;
}
#endif // BDE_OMIT_INTERNAL_DEPRECATED -- BDE2.22
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2017 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>
|
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file ir_structure_splitting.cpp
*
* If a structure is only ever referenced by its components, then
* split those components out to individual variables so they can be
* handled normally by other optimization passes.
*
* This skips structures like uniforms, which need to be accessible as
* structures for their access by the GL.
*/
#include "ir.h"
#include "ir_visitor.h"
#include "ir_print_visitor.h"
#include "glsl_types.h"
static bool debug = false;
class variable_entry : public exec_node
{
public:
variable_entry(ir_variable *var)
{
this->var = var;
this->whole_structure_access = 0;
this->declaration = false;
this->components = NULL;
this->mem_ctx = NULL;
}
ir_variable *var; /* The key: the variable's pointer. */
/** Number of times the variable is referenced, including assignments. */
unsigned whole_structure_access;
bool declaration; /* If the variable had a decl in the instruction stream */
ir_variable **components;
/** talloc_parent(this->var) -- the shader's talloc context. */
void *mem_ctx;
};
class ir_structure_reference_visitor : public ir_hierarchical_visitor {
public:
ir_structure_reference_visitor(void)
{
this->mem_ctx = talloc_new(NULL);
this->variable_list.make_empty();
}
~ir_structure_reference_visitor(void)
{
talloc_free(mem_ctx);
}
virtual ir_visitor_status visit(ir_variable *);
virtual ir_visitor_status visit(ir_dereference_variable *);
virtual ir_visitor_status visit_enter(ir_dereference_record *);
virtual ir_visitor_status visit_enter(ir_assignment *);
virtual ir_visitor_status visit_enter(ir_function_signature *);
variable_entry *get_variable_entry(ir_variable *var);
/* List of variable_entry */
exec_list variable_list;
void *mem_ctx;
};
variable_entry *
ir_structure_reference_visitor::get_variable_entry(ir_variable *var)
{
assert(var);
if (!var->type->is_record() || var->mode == ir_var_uniform)
return NULL;
foreach_iter(exec_list_iterator, iter, this->variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (entry->var == var)
return entry;
}
variable_entry *entry = new(mem_ctx) variable_entry(var);
this->variable_list.push_tail(entry);
return entry;
}
ir_visitor_status
ir_structure_reference_visitor::visit(ir_variable *ir)
{
variable_entry *entry = this->get_variable_entry(ir);
if (entry)
entry->declaration = true;
return visit_continue;
}
ir_visitor_status
ir_structure_reference_visitor::visit(ir_dereference_variable *ir)
{
ir_variable *const var = ir->variable_referenced();
variable_entry *entry = this->get_variable_entry(var);
if (entry)
entry->whole_structure_access++;
return visit_continue;
}
ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_dereference_record *ir)
{
/* Don't descend into the ir_dereference_variable below. */
return visit_continue_with_parent;
}
ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_assignment *ir)
{
if (ir->lhs->as_dereference_variable() &&
ir->rhs->as_dereference_variable() &&
!ir->condition) {
/* We'll split copies of a structure to copies of components, so don't
* descend to the ir_dereference_variables.
*/
return visit_continue_with_parent;
}
return visit_continue;
}
ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_function_signature *ir)
{
/* We don't want to descend into the function parameters and
* dead-code eliminate them, so just accept the body here.
*/
visit_list_elements(this, &ir->body);
return visit_continue_with_parent;
}
class ir_structure_splitting_visitor : public ir_hierarchical_visitor {
public:
ir_structure_splitting_visitor(exec_list *vars)
{
this->variable_list = vars;
}
virtual ~ir_structure_splitting_visitor()
{
}
virtual ir_visitor_status visit_leave(ir_assignment *);
virtual ir_visitor_status visit_leave(ir_call *);
virtual ir_visitor_status visit_leave(ir_dereference_array *);
virtual ir_visitor_status visit_leave(ir_dereference_record *);
virtual ir_visitor_status visit_leave(ir_expression *);
virtual ir_visitor_status visit_leave(ir_if *);
virtual ir_visitor_status visit_leave(ir_return *);
virtual ir_visitor_status visit_leave(ir_swizzle *);
virtual ir_visitor_status visit_leave(ir_texture *);
void split_deref(ir_dereference **deref);
void split_rvalue(ir_rvalue **rvalue);
struct variable_entry *get_splitting_entry(ir_variable *var);
exec_list *variable_list;
void *mem_ctx;
};
struct variable_entry *
ir_structure_splitting_visitor::get_splitting_entry(ir_variable *var)
{
assert(var);
if (!var->type->is_record())
return NULL;
foreach_iter(exec_list_iterator, iter, *this->variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (entry->var == var) {
return entry;
}
}
return NULL;
}
void
ir_structure_splitting_visitor::split_deref(ir_dereference **deref)
{
if ((*deref)->ir_type != ir_type_dereference_record)
return;
ir_dereference_record *deref_record = (ir_dereference_record *)*deref;
ir_dereference_variable *deref_var = deref_record->record->as_dereference_variable();
if (!deref_var)
return;
variable_entry *entry = get_splitting_entry(deref_var->var);
if (!entry)
return;
unsigned int i;
for (i = 0; i < entry->var->type->length; i++) {
if (strcmp(deref_record->field,
entry->var->type->fields.structure[i].name) == 0)
break;
}
assert(i != entry->var->type->length);
*deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[i]);
}
void
ir_structure_splitting_visitor::split_rvalue(ir_rvalue **rvalue)
{
if (!*rvalue)
return;
ir_dereference *deref = (*rvalue)->as_dereference();
if (!deref)
return;
split_deref(&deref);
*rvalue = deref;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_expression *ir)
{
unsigned int operand;
for (operand = 0; operand < ir->get_num_operands(); operand++) {
split_rvalue(&ir->operands[operand]);
}
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_texture *ir)
{
split_rvalue(&ir->coordinate);
split_rvalue(&ir->projector);
split_rvalue(&ir->shadow_comparitor);
switch (ir->op) {
case ir_tex:
break;
case ir_txb:
split_rvalue(&ir->lod_info.bias);
break;
case ir_txf:
case ir_txl:
split_rvalue(&ir->lod_info.lod);
break;
case ir_txd:
split_rvalue(&ir->lod_info.grad.dPdx);
split_rvalue(&ir->lod_info.grad.dPdy);
break;
}
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_swizzle *ir)
{
split_rvalue(&ir->val);
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_dereference_array *ir)
{
split_rvalue(&ir->array_index);
split_rvalue(&ir->array);
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_dereference_record *ir)
{
split_rvalue(&ir->record);
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_assignment *ir)
{
ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable();
ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable();
variable_entry *lhs_entry = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL;
variable_entry *rhs_entry = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL;
const glsl_type *type = ir->rhs->type;
if ((lhs_entry || rhs_entry) && !ir->condition) {
for (unsigned int i = 0; i < type->length; i++) {
ir_dereference *new_lhs, *new_rhs;
void *mem_ctx = lhs_entry ? lhs_entry->mem_ctx : rhs_entry->mem_ctx;
if (lhs_entry) {
new_lhs = new(mem_ctx) ir_dereference_variable(lhs_entry->components[i]);
} else {
new_lhs = new(mem_ctx)
ir_dereference_record(ir->lhs->clone(mem_ctx, NULL),
type->fields.structure[i].name);
}
if (rhs_entry) {
new_rhs = new(mem_ctx) ir_dereference_variable(rhs_entry->components[i]);
} else {
new_rhs = new(mem_ctx)
ir_dereference_record(ir->rhs->clone(mem_ctx, NULL),
type->fields.structure[i].name);
}
ir->insert_before(new(mem_ctx) ir_assignment(new_lhs,
new_rhs,
NULL));
}
ir->remove();
} else {
split_rvalue(&ir->rhs);
split_deref(&ir->lhs);
}
split_rvalue(&ir->condition);
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_call *ir)
{
foreach_iter(exec_list_iterator, iter, *ir) {
ir_rvalue *param = (ir_rvalue *)iter.get();
ir_rvalue *new_param = param;
split_rvalue(&new_param);
if (new_param != param) {
param->replace_with(new_param);
}
}
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_return *ir)
{
split_rvalue(&ir->value);;
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_if *ir)
{
split_rvalue(&ir->condition);
return visit_continue;
}
bool
do_structure_splitting(exec_list *instructions)
{
ir_structure_reference_visitor refs;
visit_list_elements(&refs, instructions);
/* Trim out variables we can't split. */
foreach_iter(exec_list_iterator, iter, refs.variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (debug) {
printf("structure %s@%p: decl %d, whole_access %d\n",
entry->var->name, entry->var, entry->declaration,
entry->whole_structure_access);
}
if (!entry->declaration || entry->whole_structure_access) {
entry->remove();
}
}
if (refs.variable_list.is_empty())
return false;
void *mem_ctx = talloc_new(NULL);
/* Replace the decls of the structures to be split with their split
* components.
*/
foreach_iter(exec_list_iterator, iter, refs.variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
const struct glsl_type *type = entry->var->type;
entry->mem_ctx = talloc_parent(entry->var);
entry->components = talloc_array(mem_ctx,
ir_variable *,
type->length);
for (unsigned int i = 0; i < entry->var->type->length; i++) {
const char *name = talloc_asprintf(mem_ctx, "%s_%s",
entry->var->name,
type->fields.structure[i].name);
entry->components[i] =
new(entry->mem_ctx) ir_variable(type->fields.structure[i].type,
name,
ir_var_temporary);
entry->var->insert_before(entry->components[i]);
}
entry->var->remove();
}
ir_structure_splitting_visitor split(&refs.variable_list);
visit_list_elements(&split, instructions);
talloc_free(mem_ctx);
return true;
}
<commit_msg>glsl2: add cast to silence warning<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file ir_structure_splitting.cpp
*
* If a structure is only ever referenced by its components, then
* split those components out to individual variables so they can be
* handled normally by other optimization passes.
*
* This skips structures like uniforms, which need to be accessible as
* structures for their access by the GL.
*/
#include "ir.h"
#include "ir_visitor.h"
#include "ir_print_visitor.h"
#include "glsl_types.h"
static bool debug = false;
class variable_entry : public exec_node
{
public:
variable_entry(ir_variable *var)
{
this->var = var;
this->whole_structure_access = 0;
this->declaration = false;
this->components = NULL;
this->mem_ctx = NULL;
}
ir_variable *var; /* The key: the variable's pointer. */
/** Number of times the variable is referenced, including assignments. */
unsigned whole_structure_access;
bool declaration; /* If the variable had a decl in the instruction stream */
ir_variable **components;
/** talloc_parent(this->var) -- the shader's talloc context. */
void *mem_ctx;
};
class ir_structure_reference_visitor : public ir_hierarchical_visitor {
public:
ir_structure_reference_visitor(void)
{
this->mem_ctx = talloc_new(NULL);
this->variable_list.make_empty();
}
~ir_structure_reference_visitor(void)
{
talloc_free(mem_ctx);
}
virtual ir_visitor_status visit(ir_variable *);
virtual ir_visitor_status visit(ir_dereference_variable *);
virtual ir_visitor_status visit_enter(ir_dereference_record *);
virtual ir_visitor_status visit_enter(ir_assignment *);
virtual ir_visitor_status visit_enter(ir_function_signature *);
variable_entry *get_variable_entry(ir_variable *var);
/* List of variable_entry */
exec_list variable_list;
void *mem_ctx;
};
variable_entry *
ir_structure_reference_visitor::get_variable_entry(ir_variable *var)
{
assert(var);
if (!var->type->is_record() || var->mode == ir_var_uniform)
return NULL;
foreach_iter(exec_list_iterator, iter, this->variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (entry->var == var)
return entry;
}
variable_entry *entry = new(mem_ctx) variable_entry(var);
this->variable_list.push_tail(entry);
return entry;
}
ir_visitor_status
ir_structure_reference_visitor::visit(ir_variable *ir)
{
variable_entry *entry = this->get_variable_entry(ir);
if (entry)
entry->declaration = true;
return visit_continue;
}
ir_visitor_status
ir_structure_reference_visitor::visit(ir_dereference_variable *ir)
{
ir_variable *const var = ir->variable_referenced();
variable_entry *entry = this->get_variable_entry(var);
if (entry)
entry->whole_structure_access++;
return visit_continue;
}
ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_dereference_record *ir)
{
/* Don't descend into the ir_dereference_variable below. */
return visit_continue_with_parent;
}
ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_assignment *ir)
{
if (ir->lhs->as_dereference_variable() &&
ir->rhs->as_dereference_variable() &&
!ir->condition) {
/* We'll split copies of a structure to copies of components, so don't
* descend to the ir_dereference_variables.
*/
return visit_continue_with_parent;
}
return visit_continue;
}
ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_function_signature *ir)
{
/* We don't want to descend into the function parameters and
* dead-code eliminate them, so just accept the body here.
*/
visit_list_elements(this, &ir->body);
return visit_continue_with_parent;
}
class ir_structure_splitting_visitor : public ir_hierarchical_visitor {
public:
ir_structure_splitting_visitor(exec_list *vars)
{
this->variable_list = vars;
}
virtual ~ir_structure_splitting_visitor()
{
}
virtual ir_visitor_status visit_leave(ir_assignment *);
virtual ir_visitor_status visit_leave(ir_call *);
virtual ir_visitor_status visit_leave(ir_dereference_array *);
virtual ir_visitor_status visit_leave(ir_dereference_record *);
virtual ir_visitor_status visit_leave(ir_expression *);
virtual ir_visitor_status visit_leave(ir_if *);
virtual ir_visitor_status visit_leave(ir_return *);
virtual ir_visitor_status visit_leave(ir_swizzle *);
virtual ir_visitor_status visit_leave(ir_texture *);
void split_deref(ir_dereference **deref);
void split_rvalue(ir_rvalue **rvalue);
struct variable_entry *get_splitting_entry(ir_variable *var);
exec_list *variable_list;
void *mem_ctx;
};
struct variable_entry *
ir_structure_splitting_visitor::get_splitting_entry(ir_variable *var)
{
assert(var);
if (!var->type->is_record())
return NULL;
foreach_iter(exec_list_iterator, iter, *this->variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (entry->var == var) {
return entry;
}
}
return NULL;
}
void
ir_structure_splitting_visitor::split_deref(ir_dereference **deref)
{
if ((*deref)->ir_type != ir_type_dereference_record)
return;
ir_dereference_record *deref_record = (ir_dereference_record *)*deref;
ir_dereference_variable *deref_var = deref_record->record->as_dereference_variable();
if (!deref_var)
return;
variable_entry *entry = get_splitting_entry(deref_var->var);
if (!entry)
return;
unsigned int i;
for (i = 0; i < entry->var->type->length; i++) {
if (strcmp(deref_record->field,
entry->var->type->fields.structure[i].name) == 0)
break;
}
assert(i != entry->var->type->length);
*deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[i]);
}
void
ir_structure_splitting_visitor::split_rvalue(ir_rvalue **rvalue)
{
if (!*rvalue)
return;
ir_dereference *deref = (*rvalue)->as_dereference();
if (!deref)
return;
split_deref(&deref);
*rvalue = deref;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_expression *ir)
{
unsigned int operand;
for (operand = 0; operand < ir->get_num_operands(); operand++) {
split_rvalue(&ir->operands[operand]);
}
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_texture *ir)
{
split_rvalue(&ir->coordinate);
split_rvalue(&ir->projector);
split_rvalue(&ir->shadow_comparitor);
switch (ir->op) {
case ir_tex:
break;
case ir_txb:
split_rvalue(&ir->lod_info.bias);
break;
case ir_txf:
case ir_txl:
split_rvalue(&ir->lod_info.lod);
break;
case ir_txd:
split_rvalue(&ir->lod_info.grad.dPdx);
split_rvalue(&ir->lod_info.grad.dPdy);
break;
}
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_swizzle *ir)
{
split_rvalue(&ir->val);
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_dereference_array *ir)
{
split_rvalue(&ir->array_index);
split_rvalue(&ir->array);
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_dereference_record *ir)
{
split_rvalue(&ir->record);
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_assignment *ir)
{
ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable();
ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable();
variable_entry *lhs_entry = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL;
variable_entry *rhs_entry = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL;
const glsl_type *type = ir->rhs->type;
if ((lhs_entry || rhs_entry) && !ir->condition) {
for (unsigned int i = 0; i < type->length; i++) {
ir_dereference *new_lhs, *new_rhs;
void *mem_ctx = lhs_entry ? lhs_entry->mem_ctx : rhs_entry->mem_ctx;
if (lhs_entry) {
new_lhs = new(mem_ctx) ir_dereference_variable(lhs_entry->components[i]);
} else {
new_lhs = new(mem_ctx)
ir_dereference_record(ir->lhs->clone(mem_ctx, NULL),
type->fields.structure[i].name);
}
if (rhs_entry) {
new_rhs = new(mem_ctx) ir_dereference_variable(rhs_entry->components[i]);
} else {
new_rhs = new(mem_ctx)
ir_dereference_record(ir->rhs->clone(mem_ctx, NULL),
type->fields.structure[i].name);
}
ir->insert_before(new(mem_ctx) ir_assignment(new_lhs,
new_rhs,
NULL));
}
ir->remove();
} else {
split_rvalue(&ir->rhs);
split_deref(&ir->lhs);
}
split_rvalue(&ir->condition);
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_call *ir)
{
foreach_iter(exec_list_iterator, iter, *ir) {
ir_rvalue *param = (ir_rvalue *)iter.get();
ir_rvalue *new_param = param;
split_rvalue(&new_param);
if (new_param != param) {
param->replace_with(new_param);
}
}
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_return *ir)
{
split_rvalue(&ir->value);;
return visit_continue;
}
ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_if *ir)
{
split_rvalue(&ir->condition);
return visit_continue;
}
bool
do_structure_splitting(exec_list *instructions)
{
ir_structure_reference_visitor refs;
visit_list_elements(&refs, instructions);
/* Trim out variables we can't split. */
foreach_iter(exec_list_iterator, iter, refs.variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (debug) {
printf("structure %s@%p: decl %d, whole_access %d\n",
entry->var->name, (void *) entry->var, entry->declaration,
entry->whole_structure_access);
}
if (!entry->declaration || entry->whole_structure_access) {
entry->remove();
}
}
if (refs.variable_list.is_empty())
return false;
void *mem_ctx = talloc_new(NULL);
/* Replace the decls of the structures to be split with their split
* components.
*/
foreach_iter(exec_list_iterator, iter, refs.variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
const struct glsl_type *type = entry->var->type;
entry->mem_ctx = talloc_parent(entry->var);
entry->components = talloc_array(mem_ctx,
ir_variable *,
type->length);
for (unsigned int i = 0; i < entry->var->type->length; i++) {
const char *name = talloc_asprintf(mem_ctx, "%s_%s",
entry->var->name,
type->fields.structure[i].name);
entry->components[i] =
new(entry->mem_ctx) ir_variable(type->fields.structure[i].type,
name,
ir_var_temporary);
entry->var->insert_before(entry->components[i]);
}
entry->var->remove();
}
ir_structure_splitting_visitor split(&refs.variable_list);
visit_list_elements(&split, instructions);
talloc_free(mem_ctx);
return true;
}
<|endoftext|>
|
<commit_before>/*-
* Copyright 2009 Colin Percival
* 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 AUTHOR 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 AUTHOR 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.
*
* This file was originally written by Colin Percival as part of the Tarsnap
* online backup system.
*/
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "cipher/scrypt/sha256.hpp"
#include "cipher/scrypt/sysendian.hpp"
#include "cipher/scrypt/crypto_scrypt.hpp"
static void blkcpy(uint8_t *, uint8_t *, size_t);
static void blkxor(uint8_t *, uint8_t *, size_t);
static void salsa20_8(uint8_t[64]);
static void blockmix_salsa8(uint8_t *, uint8_t *, size_t);
static uint64_t integerify(uint8_t *, size_t);
static void smix(uint8_t *, size_t, uint64_t, uint8_t *, uint8_t *);
static void
blkcpy(uint8_t * dest, uint8_t * src, size_t len)
{
size_t i;
for (i = 0; i < len; i++)
dest[i] = src[i];
}
static void
blkxor(uint8_t * dest, uint8_t * src, size_t len)
{
size_t i;
for (i = 0; i < len; i++)
dest[i] ^= src[i];
}
/**
* salsa20_8(B):
* Apply the salsa20/8 core to the provided block.
*/
static void
salsa20_8(uint8_t B[64])
{
uint32_t B32[16];
uint32_t x[16];
size_t i;
/* Convert little-endian values in. */
for (i = 0; i < 16; i++)
B32[i] = le32dec(&B[i * 4]);
/* Compute x = doubleround^4(B32). */
for (i = 0; i < 16; i++)
x[i] = B32[i];
for (i = 0; i < 8; i += 2) {
#define R(a,b) (((a) << (b)) | ((a) >> (32 - (b))))
/* Operate on columns. */
x[ 4] ^= R(x[ 0]+x[12], 7); x[ 8] ^= R(x[ 4]+x[ 0], 9);
x[12] ^= R(x[ 8]+x[ 4],13); x[ 0] ^= R(x[12]+x[ 8],18);
x[ 9] ^= R(x[ 5]+x[ 1], 7); x[13] ^= R(x[ 9]+x[ 5], 9);
x[ 1] ^= R(x[13]+x[ 9],13); x[ 5] ^= R(x[ 1]+x[13],18);
x[14] ^= R(x[10]+x[ 6], 7); x[ 2] ^= R(x[14]+x[10], 9);
x[ 6] ^= R(x[ 2]+x[14],13); x[10] ^= R(x[ 6]+x[ 2],18);
x[ 3] ^= R(x[15]+x[11], 7); x[ 7] ^= R(x[ 3]+x[15], 9);
x[11] ^= R(x[ 7]+x[ 3],13); x[15] ^= R(x[11]+x[ 7],18);
/* Operate on rows. */
x[ 1] ^= R(x[ 0]+x[ 3], 7); x[ 2] ^= R(x[ 1]+x[ 0], 9);
x[ 3] ^= R(x[ 2]+x[ 1],13); x[ 0] ^= R(x[ 3]+x[ 2],18);
x[ 6] ^= R(x[ 5]+x[ 4], 7); x[ 7] ^= R(x[ 6]+x[ 5], 9);
x[ 4] ^= R(x[ 7]+x[ 6],13); x[ 5] ^= R(x[ 4]+x[ 7],18);
x[11] ^= R(x[10]+x[ 9], 7); x[ 8] ^= R(x[11]+x[10], 9);
x[ 9] ^= R(x[ 8]+x[11],13); x[10] ^= R(x[ 9]+x[ 8],18);
x[12] ^= R(x[15]+x[14], 7); x[13] ^= R(x[12]+x[15], 9);
x[14] ^= R(x[13]+x[12],13); x[15] ^= R(x[14]+x[13],18);
#undef R
}
/* Compute B32 = B32 + x. */
for (i = 0; i < 16; i++)
B32[i] += x[i];
/* Convert little-endian values out. */
for (i = 0; i < 16; i++)
le32enc(&B[4 * i], B32[i]);
}
/**
* blockmix_salsa8(B, Y, r):
* Compute B = BlockMix_{salsa20/8, r}(B). The input B must be 128r bytes in
* length; the temporary space Y must also be the same size.
*/
static void
blockmix_salsa8(uint8_t * B, uint8_t * Y, size_t r)
{
uint8_t X[64];
size_t i;
/* 1: X <-- B_{2r - 1} */
blkcpy(X, &B[(2 * r - 1) * 64], 64);
/* 2: for i = 0 to 2r - 1 do */
for (i = 0; i < 2 * r; i++) {
/* 3: X <-- H(X \xor B_i) */
blkxor(X, &B[i * 64], 64);
salsa20_8(X);
/* 4: Y_i <-- X */
blkcpy(&Y[i * 64], X, 64);
}
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
for (i = 0; i < r; i++)
blkcpy(&B[i * 64], &Y[(i * 2) * 64], 64);
for (i = 0; i < r; i++)
blkcpy(&B[(i + r) * 64], &Y[(i * 2 + 1) * 64], 64);
}
/**
* integerify(B, r):
* Return the result of parsing B_{2r-1} as a little-endian integer.
*/
static uint64_t
integerify(uint8_t * B, size_t r)
{
uint8_t * X = &B[(2 * r - 1) * 64];
return (le64dec(X));
}
/**
* smix(B, r, N, V, XY):
* Compute B = SMix_r(B, N). The input B must be 128r bytes in length; the
* temporary storage V must be 128rN bytes in length; the temporary storage
* XY must be 256r bytes in length. The value N must be a power of 2.
*/
static void
smix(uint8_t * B, size_t r, uint64_t N, uint8_t * V, uint8_t * XY)
{
uint8_t * X = XY;
uint8_t * Y = &XY[128 * r];
uint64_t i;
uint64_t j;
/* 1: X <-- B */
blkcpy(X, B, 128 * r);
/* 2: for i = 0 to N - 1 do */
for (i = 0; i < N; i++) {
/* 3: V_i <-- X */
blkcpy(&V[i * (128 * r)], X, 128 * r);
/* 4: X <-- H(X) */
blockmix_salsa8(X, Y, r);
}
/* 6: for i = 0 to N - 1 do */
for (i = 0; i < N; i++) {
/* 7: j <-- Integerify(X) mod N */
j = integerify(X, r) & (N - 1);
/* 8: X <-- H(X \xor V_j) */
blkxor(X, &V[j * (128 * r)], 128 * r);
blockmix_salsa8(X, Y, r);
}
/* 10: B' <-- X */
blkcpy(B, X, 128 * r);
}
/**
* crypto_scrypt(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen):
* Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r,
* p, buflen) and write the result into buf. The parameters r, p, and buflen
* must satisfy r * p < 2^30 and buflen <= (2^32 - 1) * 32. The parameter N
* must be a power of 2.
*
* Return 0 on success; or -1 on error.
*/
int
crypto_scrypt(const uint8_t * passwd, size_t passwdlen,
const uint8_t * salt, size_t saltlen, uint64_t N, uint32_t r, uint32_t p,
uint8_t * buf, size_t buflen)
{
uint8_t * B;
uint8_t * V;
uint8_t * XY;
uint32_t i;
/* Sanity-check parameters. */
#if SIZE_MAX > UINT32_MAX
if (buflen > (((uint64_t)(1) << 32) - 1) * 32) {
errno = EFBIG;
goto err0;
}
#endif
if ((uint64_t)(r) * (uint64_t)(p) >= (1 << 30)) {
errno = EFBIG;
goto err0;
}
if (((N & (N - 1)) != 0) || (N == 0)) {
errno = EINVAL;
goto err0;
}
if ((r > SIZE_MAX / 128 / p) ||
#if SIZE_MAX / 256 <= UINT32_MAX
(r > SIZE_MAX / 256) ||
#endif
(N > SIZE_MAX / 128 / r)) {
errno = ENOMEM;
goto err0;
}
/* Allocate memory. */
if ((B = (uint8_t*)malloc(128 * r * p)) == NULL)
goto err0;
if ((XY = (uint8_t*)malloc(256 * r)) == NULL)
goto err1;
if ((V = (uint8_t*)malloc(128 * r * N)) == NULL)
goto err2;
/* 1: (B_0 ... B_{p-1}) <-- PBKDF2(P, S, 1, p * MFLen) */
PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, 1, B, p * 128 * r);
/* 2: for i = 0 to p - 1 do */
for (i = 0; i < p; i++) {
/* 3: B_i <-- MF(B_i, N) */
smix(&B[i * 128 * r], r, N, V, XY);
}
/* 5: DK <-- PBKDF2(P, B, 1, dkLen) */
PBKDF2_SHA256(passwd, passwdlen, B, p * 128 * r, 1, buf, buflen);
/* Free memory. */
free(V);
free(XY);
free(B);
/* Success! */
return (0);
err2:
free(XY);
err1:
free(B);
err0:
/* Failure! */
return (-1);
}
<commit_msg>SIZE_MAX couldn't be found for sanity test in scrypt code. Commented out for the time-being<commit_after>/*-
* Copyright 2009 Colin Percival
* 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 AUTHOR 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 AUTHOR 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.
*
* This file was originally written by Colin Percival as part of the Tarsnap
* online backup system.
*/
#include <errno.h>
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "cipher/scrypt/sha256.hpp"
#include "cipher/scrypt/sysendian.hpp"
#include "cipher/scrypt/crypto_scrypt.hpp"
static void blkcpy(uint8_t *, uint8_t *, size_t);
static void blkxor(uint8_t *, uint8_t *, size_t);
static void salsa20_8(uint8_t[64]);
static void blockmix_salsa8(uint8_t *, uint8_t *, size_t);
static uint64_t integerify(uint8_t *, size_t);
static void smix(uint8_t *, size_t, uint64_t, uint8_t *, uint8_t *);
static void
blkcpy(uint8_t * dest, uint8_t * src, size_t len)
{
size_t i;
for (i = 0; i < len; i++)
dest[i] = src[i];
}
static void
blkxor(uint8_t * dest, uint8_t * src, size_t len)
{
size_t i;
for (i = 0; i < len; i++)
dest[i] ^= src[i];
}
/**
* salsa20_8(B):
* Apply the salsa20/8 core to the provided block.
*/
static void
salsa20_8(uint8_t B[64])
{
uint32_t B32[16];
uint32_t x[16];
size_t i;
/* Convert little-endian values in. */
for (i = 0; i < 16; i++)
B32[i] = le32dec(&B[i * 4]);
/* Compute x = doubleround^4(B32). */
for (i = 0; i < 16; i++)
x[i] = B32[i];
for (i = 0; i < 8; i += 2) {
#define R(a,b) (((a) << (b)) | ((a) >> (32 - (b))))
/* Operate on columns. */
x[ 4] ^= R(x[ 0]+x[12], 7); x[ 8] ^= R(x[ 4]+x[ 0], 9);
x[12] ^= R(x[ 8]+x[ 4],13); x[ 0] ^= R(x[12]+x[ 8],18);
x[ 9] ^= R(x[ 5]+x[ 1], 7); x[13] ^= R(x[ 9]+x[ 5], 9);
x[ 1] ^= R(x[13]+x[ 9],13); x[ 5] ^= R(x[ 1]+x[13],18);
x[14] ^= R(x[10]+x[ 6], 7); x[ 2] ^= R(x[14]+x[10], 9);
x[ 6] ^= R(x[ 2]+x[14],13); x[10] ^= R(x[ 6]+x[ 2],18);
x[ 3] ^= R(x[15]+x[11], 7); x[ 7] ^= R(x[ 3]+x[15], 9);
x[11] ^= R(x[ 7]+x[ 3],13); x[15] ^= R(x[11]+x[ 7],18);
/* Operate on rows. */
x[ 1] ^= R(x[ 0]+x[ 3], 7); x[ 2] ^= R(x[ 1]+x[ 0], 9);
x[ 3] ^= R(x[ 2]+x[ 1],13); x[ 0] ^= R(x[ 3]+x[ 2],18);
x[ 6] ^= R(x[ 5]+x[ 4], 7); x[ 7] ^= R(x[ 6]+x[ 5], 9);
x[ 4] ^= R(x[ 7]+x[ 6],13); x[ 5] ^= R(x[ 4]+x[ 7],18);
x[11] ^= R(x[10]+x[ 9], 7); x[ 8] ^= R(x[11]+x[10], 9);
x[ 9] ^= R(x[ 8]+x[11],13); x[10] ^= R(x[ 9]+x[ 8],18);
x[12] ^= R(x[15]+x[14], 7); x[13] ^= R(x[12]+x[15], 9);
x[14] ^= R(x[13]+x[12],13); x[15] ^= R(x[14]+x[13],18);
#undef R
}
/* Compute B32 = B32 + x. */
for (i = 0; i < 16; i++)
B32[i] += x[i];
/* Convert little-endian values out. */
for (i = 0; i < 16; i++)
le32enc(&B[4 * i], B32[i]);
}
/**
* blockmix_salsa8(B, Y, r):
* Compute B = BlockMix_{salsa20/8, r}(B). The input B must be 128r bytes in
* length; the temporary space Y must also be the same size.
*/
static void
blockmix_salsa8(uint8_t * B, uint8_t * Y, size_t r)
{
uint8_t X[64];
size_t i;
/* 1: X <-- B_{2r - 1} */
blkcpy(X, &B[(2 * r - 1) * 64], 64);
/* 2: for i = 0 to 2r - 1 do */
for (i = 0; i < 2 * r; i++) {
/* 3: X <-- H(X \xor B_i) */
blkxor(X, &B[i * 64], 64);
salsa20_8(X);
/* 4: Y_i <-- X */
blkcpy(&Y[i * 64], X, 64);
}
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
for (i = 0; i < r; i++)
blkcpy(&B[i * 64], &Y[(i * 2) * 64], 64);
for (i = 0; i < r; i++)
blkcpy(&B[(i + r) * 64], &Y[(i * 2 + 1) * 64], 64);
}
/**
* integerify(B, r):
* Return the result of parsing B_{2r-1} as a little-endian integer.
*/
static uint64_t
integerify(uint8_t * B, size_t r)
{
uint8_t * X = &B[(2 * r - 1) * 64];
return (le64dec(X));
}
/**
* smix(B, r, N, V, XY):
* Compute B = SMix_r(B, N). The input B must be 128r bytes in length; the
* temporary storage V must be 128rN bytes in length; the temporary storage
* XY must be 256r bytes in length. The value N must be a power of 2.
*/
static void
smix(uint8_t * B, size_t r, uint64_t N, uint8_t * V, uint8_t * XY)
{
uint8_t * X = XY;
uint8_t * Y = &XY[128 * r];
uint64_t i;
uint64_t j;
/* 1: X <-- B */
blkcpy(X, B, 128 * r);
/* 2: for i = 0 to N - 1 do */
for (i = 0; i < N; i++) {
/* 3: V_i <-- X */
blkcpy(&V[i * (128 * r)], X, 128 * r);
/* 4: X <-- H(X) */
blockmix_salsa8(X, Y, r);
}
/* 6: for i = 0 to N - 1 do */
for (i = 0; i < N; i++) {
/* 7: j <-- Integerify(X) mod N */
j = integerify(X, r) & (N - 1);
/* 8: X <-- H(X \xor V_j) */
blkxor(X, &V[j * (128 * r)], 128 * r);
blockmix_salsa8(X, Y, r);
}
/* 10: B' <-- X */
blkcpy(B, X, 128 * r);
}
/**
* crypto_scrypt(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen):
* Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r,
* p, buflen) and write the result into buf. The parameters r, p, and buflen
* must satisfy r * p < 2^30 and buflen <= (2^32 - 1) * 32. The parameter N
* must be a power of 2.
*
* Return 0 on success; or -1 on error.
*/
int
crypto_scrypt(const uint8_t * passwd, size_t passwdlen,
const uint8_t * salt, size_t saltlen, uint64_t N, uint32_t r, uint32_t p,
uint8_t * buf, size_t buflen)
{
uint8_t * B;
uint8_t * V;
uint8_t * XY;
uint32_t i;
/* Sanity-check parameters. */
// UNTIL I can find out where SIZE_MAX is defined, will comment this sanity check out
/*
#if SIZE_MAX > UINT32_MAX
if (buflen > (((uint64_t)(1) << 32) - 1) * 32) {
errno = EFBIG;
goto err0;
}
#endif
if ((uint64_t)(r) * (uint64_t)(p) >= (1 << 30)) {
errno = EFBIG;
goto err0;
}
if (((N & (N - 1)) != 0) || (N == 0)) {
errno = EINVAL;
goto err0;
}
if ((r > SIZE_MAX / 128 / p) ||
#if SIZE_MAX / 256 <= UINT32_MAX
(r > SIZE_MAX / 256) ||
#endif
(N > SIZE_MAX / 128 / r)) {
errno = ENOMEM;
goto err0;
}*/
/* Allocate memory. */
if ((B = (uint8_t*)malloc(128 * r * p)) == NULL)
goto err0;
if ((XY = (uint8_t*)malloc(256 * r)) == NULL)
goto err1;
if ((V = (uint8_t*)malloc(128 * r * N)) == NULL)
goto err2;
/* 1: (B_0 ... B_{p-1}) <-- PBKDF2(P, S, 1, p * MFLen) */
PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, 1, B, p * 128 * r);
/* 2: for i = 0 to p - 1 do */
for (i = 0; i < p; i++) {
/* 3: B_i <-- MF(B_i, N) */
smix(&B[i * 128 * r], r, N, V, XY);
}
/* 5: DK <-- PBKDF2(P, B, 1, dkLen) */
PBKDF2_SHA256(passwd, passwdlen, B, p * 128 * r, 1, buf, buflen);
/* Free memory. */
free(V);
free(XY);
free(B);
/* Success! */
return (0);
err2:
free(XY);
err1:
free(B);
err0:
/* Failure! */
return (-1);
}
<|endoftext|>
|
<commit_before>//Mancala AI
//Copyright Matthew Chandler 2012
#include <iostream>
#include <iomanip>
#include <vector>
#include <limits>
#include <cstdlib>
//board:
//2 rows of 6 bowls
//2 larger bowls for scoring (stores)
//
//Rules
//play is CCW
//ending in player's own store yields extra turn
//ending in empty bowl earns that piece and all those in the bowl across from it
//game ends when a player has no legal moves left
//
//good heuristics:
//score - opponent's score
//possibly good:
//number of availible moves
//seeds in play
//seed distribution (large piles waiting to be collected? seed ratio between sides)
//possibilty of extra turns
//if we wanted to, we could use a genetic algorithm for determining the importance of each of these
//
//representation
//circular array?
// 11 10 9 8 7 6
// 0 1 2 3 4 5
// p1 store, p2 store
//From there, we would need logic to add to player's own store and skip the opponents.
//if we abstract out the actual array indexes, we can use 2 starting pointers to easily flip the board
//With that in mind, it might be better to use a Digraph, so we can have a truly circular setup
//each node could have a next, prev, and across pointer, and one that points to the stores for the ends (NULL otherwise)
//
//
//
//If we wanted to get really fancy, we could do 3D graphics with particle physics for the seeds.
struct Bowl
{
public:
Bowl(const int Count = 0, const int Next = 0, const int Across = 0):
count(Count), next(Next), across(Across)
{}
int count;
int next, across;
};
class Board
{
public:
Board(const int Num_bowls = 6, const int Num_seeds = 4):
num_bowls(Num_bowls), num_seeds(Num_seeds)
{
bowls.resize(2 * num_bowls + 2);
p1_start = 0;
p1_store = num_bowls;
p2_start = num_bowls + 1;
p2_store = 2 * num_bowls + 1;
for(size_t i = 0; i < bowls.size(); ++i)
{
if(i < bowls.size() - 1)
bowls[i].next = i + 1;
else
bowls[i].next = 0;
if(i != (size_t)num_bowls && i != 2 * (size_t)num_bowls + 1)
{
bowls[i].across = 2 * num_bowls - i;
bowls[i].count = num_seeds;
}
}
}
//perform a move
//returns true if the move earns an extra turn
bool move(int bowl)
{
if(bowl < 0 || bowl >= num_bowls)
return false;
bowl += p1_start;
int seeds = bowls[bowl].count;
if(seeds == 0)
return false;
bowls[bowl].count = 0;
//make the move
for(int i = 0; i < seeds; ++i)
{
bowl = bowls[bowl].next;
if(bowl == p2_store)
bowl = bowls[bowl].next;
bowls[bowl].count += 1;
}
//extra turn if we land in our own store
if(bowl == p1_store)
return true;
//if we land in an empty bowl, we get the last seed sown and all the seeds from the bowl across
if(bowls[bowl].count == 1 && bowls[bowls[bowl].across].count > 0)
{
bowls[p1_store].count += 1 + bowls[bowls[bowl].across].count;
bowls[bowls[bowl].across].count = 0;
bowls[bowl].count = 0;
}
return false;
}
//swap sides of the board
void swapsides()
{
std::swap(p1_start, p2_start);
std::swap(p1_store, p2_store);
}
//is the game over
bool finished() const
{
int p1_side = 0;
for(int i = p1_start; i < p1_start + 6; ++i)
p1_side |= bowls[i].count;
if(p1_side == 0)
return true;
int p2_side = 0;
for(int i = p2_start; i < p2_start + 6; ++i)
p2_side |= bowls[i].count;
return p2_side == 0;
}
//heuristics to evaluate the board status
int evaluate() const
{
//simple
return bowls[p1_store].count - bowls[p2_store].count;
}
void crapprint() const //delete me!
{
std::cout<<" ";
for(int i = p1_start; i < p1_start + 6; ++i)
std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[bowls[i].across].count<<" ";
std::cout<<std::endl;
std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[p2_store].count<<std::setw(3*7)<<" "<<std::setw(2)<<bowls[p1_store].count<<std::endl;
std::cout<<" ";
for(int i = p1_start; i < p1_start + 6; ++i)
std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[i].count<<" ";
std::cout<<std::endl;
std::cout<<" ";
for(int i = 0; i < 6 ; ++i)
std::cout<<std::setw(2)<<std::setfill(' ')<<i<<" ";
std::cout<<std::endl;
}
int num_bowls, num_seeds;
std::vector<Bowl> bowls;
int p1_start, p2_start;
int p1_store, p2_store;
};
enum PLAYER {PLAYER_MIN, PLAYER_MAX};
int choosemove_minimax(Board b, int depth, PLAYER player)
{
if(player == PLAYER_MAX)
{
if(depth == 0)
return b.evaluate();
if(b.finished())
{
int diff = b.evaluate();
if(diff > 0)
return 1000 + depth;
else
return -1000 - depth;
}
int max = std::numeric_limits<int>::min();
for(int i = 0; i < 6; ++i)
{
if(b.bowls[b.p1_start + i].count == 0)
continue;
Board sub_b = b;
sub_b.move(i); // do we get another move?
sub_b.swapsides();
//max = std::max(max, choosemove_minimax(sub_b, depth - 1, PLAYER_MIN));
//sub_b.crapprint();
//for(int i = 3-depth; i >=0; --i)
// std::cout<<" ";
//std::cout<<"i: "<<i<<std::endl;
int score = choosemove_minimax(sub_b, depth - 1, PLAYER_MIN);
max = std::max(max,score);
//for(int i = 3-depth; i >=0; --i)
// std::cout<<" ";
//std::cout<<"score: "<<score<<std::endl;
}
return max;
}
else
{
if(depth == 0)
return -b.evaluate();
if(b.finished())
{
int diff = b.evaluate();
if(diff > 0)
return -1000 - depth;
else
return 1000 + depth;
}
int min = std::numeric_limits<int>::max();
for(int i = 0; i < 6; ++i)
{
if(b.bowls[b.p1_start + i].count == 0)
continue;
Board sub_b = b;
sub_b.move(i); // do we get another move?
sub_b.swapsides();
//min = std::min(min, choosemove_minimax(sub_b, depth - 1, PLAYER_MAX));
//sub_b.crapprint();
//for(int i = 3-depth; i >=0; --i)
// std::cout<<" ";
//std::cout<<"i: "<<i<<std::endl;
int score = choosemove_minimax(sub_b, depth - 1, PLAYER_MAX);
min = std::min(min, score);
//for(int i = 3-depth; i >=0; --i)
// std::cout<<" ";
//std::cout<<"score: "<<score<<std::endl;
}
return min;
}
}
int choosemove(Board b) //purposely doing pass by value here as to not corrupt passed board (we may want to use different method when we do actual move search)
{
int best = std::numeric_limits<int>::min();
std::vector<int> best_i;
//loop over available moves
for(int i =0; i < 6; ++i)
{
if(b.bowls[b.p1_start + i].count == 0)
continue;
Board sub_b = b;
sub_b.move(i);
sub_b.swapsides();
int score = choosemove_minimax(sub_b, 10, PLAYER_MIN);
std::cout<<"choose: "<<i<<" "<<score<<" "<<-sub_b.evaluate()<<std::endl;
if(score > best)
{
best = score;
best_i.clear();
best_i.push_back(i);
}
if(score == best);
best_i.push_back(i);
}
return best_i[0];//rand() % best_i.size()];
}
int main()
{
srand(time(0));
Board b;
//b.bowls=std::vector<Bowl>({Bowl(3,1,12), Bowl(2,2,11), Bowl(1,3,10), Bowl(0,4,9), Bowl(10,5,8), Bowl(0,6,7), Bowl(0,7,0), Bowl(1,8,5), Bowl(0,9,4), Bowl(10,10,3), Bowl(1,11,2), Bowl(1,12,1), Bowl(1,13,0), Bowl(0,0,0)});
char nextmove = '\0';
int player = 1;
while(!b.finished() && nextmove != 'q' && nextmove != 'Q')
{
std::cout<<"Player "<<player<<std::endl;
b.crapprint();
std::cout<<"Best move: "<<choosemove(b)<<std::endl;
std::cout<<"Next move: ";
std::cin>>nextmove;
std::cout<<std::endl;
if(nextmove == 'S' || nextmove == 's')
{
b.swapsides();
player = (player == 1) ? 2 : 1;
}
if(nextmove >= '0' && nextmove <= '5')
{
if(!b.move(nextmove - '0'));
{
b.swapsides();
player = (player == 1) ? 2 : 1;
}
}
}
if(b.finished())
{
std::cout<<"Player "<<player<<std::endl;
b.crapprint();
if(b.bowls[b.p1_store].count == b.bowls[b.p2_store].count)
std::cout<<"Tie"<<std::endl;
else if(player == 1)
if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count)
std::cout<<"Player 1 wins"<<std::endl;
else
std::cout<<"Player 2 wins"<<std::endl;
else
if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count)
std::cout<<"Player 2 wins"<<std::endl;
else
std::cout<<"Player 1 wins"<<std::endl;
if(abs(b.bowls[b.p1_store].count - b.bowls[b.p2_store].count) >= 10)
std::cout<<"FATALITY"<<std::endl;
}
return 0;
}
<commit_msg>cleaned up a bit<commit_after>//Mancala AI
//Copyright Matthew Chandler 2012
#include <iostream>
#include <iomanip>
#include <vector>
#include <limits>
#include <cstdlib>
//board:
//2 rows of 6 bowls
//2 larger bowls for scoring (stores)
//
//Rules
//play is CCW
//ending in player's own store yields extra turn
//ending in empty bowl earns that piece and all those in the bowl across from it
//game ends when a player has no legal moves left
//
//good heuristics:
//score - opponent's score
//possibly good:
//number of availible moves
//seeds in play
//seed distribution (large piles waiting to be collected? seed ratio between sides)
//possibilty of extra turns
//if we wanted to, we could use a genetic algorithm for determining the importance of each of these
//
//representation
//circular array?
// 11 10 9 8 7 6
// 0 1 2 3 4 5
// p1 store, p2 store
//From there, we would need logic to add to player's own store and skip the opponents.
//if we abstract out the actual array indexes, we can use 2 starting pointers to easily flip the board
//With that in mind, it might be better to use a Digraph, so we can have a truly circular setup
//each node could have a next, prev, and across pointer, and one that points to the stores for the ends (NULL otherwise)
//
//
//
//If we wanted to get really fancy, we could do 3D graphics with particle physics for the seeds.
struct Bowl
{
public:
Bowl(const int Count = 0, const int Next = 0, const int Across = 0):
count(Count), next(Next), across(Across)
{}
int count;
int next, across;
};
class Board
{
public:
Board(const int Num_bowls = 6, const int Num_seeds = 4):
num_bowls(Num_bowls), num_seeds(Num_seeds)
{
bowls.resize(2 * num_bowls + 2);
p1_start = 0;
p1_store = num_bowls;
p2_start = num_bowls + 1;
p2_store = 2 * num_bowls + 1;
for(size_t i = 0; i < bowls.size(); ++i)
{
if(i < bowls.size() - 1)
bowls[i].next = i + 1;
else
bowls[i].next = 0;
if(i != (size_t)num_bowls && i != 2 * (size_t)num_bowls + 1)
{
bowls[i].across = 2 * num_bowls - i;
bowls[i].count = num_seeds;
}
}
}
//perform a move
//returns true if the move earns an extra turn
bool move(int bowl)
{
if(bowl < 0 || bowl >= num_bowls)
return false;
bowl += p1_start;
int seeds = bowls[bowl].count;
if(seeds == 0)
return false;
bowls[bowl].count = 0;
//make the move
for(int i = 0; i < seeds; ++i)
{
bowl = bowls[bowl].next;
if(bowl == p2_store)
bowl = bowls[bowl].next;
bowls[bowl].count += 1;
}
//extra turn if we land in our own store
if(bowl == p1_store)
return true;
//if we land in an empty bowl, we get the last seed sown and all the seeds from the bowl across
if(bowls[bowl].count == 1 && bowls[bowls[bowl].across].count > 0)
{
bowls[p1_store].count += 1 + bowls[bowls[bowl].across].count;
bowls[bowls[bowl].across].count = 0;
bowls[bowl].count = 0;
}
return false;
}
//swap sides of the board
void swapsides()
{
std::swap(p1_start, p2_start);
std::swap(p1_store, p2_store);
}
//is the game over
bool finished() const
{
int p1_side = 0;
for(int i = p1_start; i < p1_start + 6; ++i)
p1_side |= bowls[i].count;
if(p1_side == 0)
return true;
int p2_side = 0;
for(int i = p2_start; i < p2_start + 6; ++i)
p2_side |= bowls[i].count;
return p2_side == 0;
}
//heuristics to evaluate the board status
int evaluate() const
{
//simple
return bowls[p1_store].count - bowls[p2_store].count;
}
void crapprint() const //delete me!
{
std::cout<<" ";
for(int i = p1_start; i < p1_start + 6; ++i)
std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[bowls[i].across].count<<" ";
std::cout<<std::endl;
std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[p2_store].count<<std::setw(3*7)<<" "<<std::setw(2)<<bowls[p1_store].count<<std::endl;
std::cout<<" ";
for(int i = p1_start; i < p1_start + 6; ++i)
std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[i].count<<" ";
std::cout<<std::endl;
std::cout<<" ";
for(int i = 0; i < 6 ; ++i)
std::cout<<std::setw(2)<<std::setfill(' ')<<i<<" ";
std::cout<<std::endl;
}
int num_bowls, num_seeds;
std::vector<Bowl> bowls;
int p1_start, p2_start;
int p1_store, p2_store;
};
enum PLAYER {PLAYER_MIN, PLAYER_MAX};
int choosemove_minimax(Board b, int depth, PLAYER player)
{
if(player == PLAYER_MAX)
{
if(depth == 0)
return b.evaluate();
//move toward closest win, avoid loss as long as possible
if(b.finished())
{
int diff = b.evaluate();
if(diff > 0)
return 1000 + depth;
else
return -1000 - depth;
}
int max = std::numeric_limits<int>::min();
for(int i = 0; i < 6; ++i)
{
if(b.bowls[b.p1_start + i].count == 0)
continue;
Board sub_b = b;
sub_b.move(i); // do we get another move?
sub_b.swapsides();
max = std::max(max, choosemove_minimax(sub_b, depth - 1, PLAYER_MIN));
}
return max;
}
else
{
if(depth == 0)
return -b.evaluate();
//move toward closest win, avoid loss as long as possible
if(b.finished())
{
int diff = b.evaluate();
if(diff > 0)
return -1000 - depth;
else
return 1000 + depth;
}
int min = std::numeric_limits<int>::max();
for(int i = 0; i < 6; ++i)
{
if(b.bowls[b.p1_start + i].count == 0)
continue;
Board sub_b = b;
sub_b.move(i); // do we get another move?
sub_b.swapsides();
min = std::min(min, choosemove_minimax(sub_b, depth - 1, PLAYER_MAX));
}
return min;
}
}
int choosemove(Board b) //purposely doing pass by value here as to not corrupt passed board (we may want to use different method when we do actual move search)
{
int best = std::numeric_limits<int>::min();
std::vector<int> best_i;
//loop over available moves
for(int i =0; i < 6; ++i)
{
if(b.bowls[b.p1_start + i].count == 0)
continue;
Board sub_b = b;
sub_b.move(i);
sub_b.swapsides();
int score = choosemove_minimax(sub_b, 10, PLAYER_MIN);
std::cout<<"choose: "<<i<<" "<<score<<" "<<-sub_b.evaluate()<<std::endl;
if(score > best)
{
best = score;
best_i.clear();
best_i.push_back(i);
}
if(score == best);
best_i.push_back(i);
}
return best_i[0];//rand() % best_i.size()];
}
int main()
{
srand(time(0));
Board b;
//b.bowls=std::vector<Bowl>({Bowl(3,1,12), Bowl(2,2,11), Bowl(1,3,10), Bowl(0,4,9), Bowl(10,5,8), Bowl(0,6,7), Bowl(0,7,0), Bowl(1,8,5), Bowl(0,9,4), Bowl(10,10,3), Bowl(1,11,2), Bowl(1,12,1), Bowl(1,13,0), Bowl(0,0,0)});
char nextmove = '\0';
int player = 1;
while(!b.finished() && nextmove != 'q' && nextmove != 'Q')
{
std::cout<<"Player "<<player<<std::endl;
b.crapprint();
std::cout<<"Best move: "<<choosemove(b)<<std::endl;
std::cout<<"Next move: ";
std::cin>>nextmove;
std::cout<<std::endl;
if(nextmove == 'S' || nextmove == 's')
{
b.swapsides();
player = (player == 1) ? 2 : 1;
}
if(nextmove >= '0' && nextmove <= '5')
{
if(!b.move(nextmove - '0'));
{
b.swapsides();
player = (player == 1) ? 2 : 1;
}
}
}
if(b.finished())
{
std::cout<<"Player "<<player<<std::endl;
b.crapprint();
if(b.bowls[b.p1_store].count == b.bowls[b.p2_store].count)
std::cout<<"Tie"<<std::endl;
else if(player == 1)
if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count)
std::cout<<"Player 1 wins"<<std::endl;
else
std::cout<<"Player 2 wins"<<std::endl;
else
if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count)
std::cout<<"Player 2 wins"<<std::endl;
else
std::cout<<"Player 1 wins"<<std::endl;
if(abs(b.bowls[b.p1_store].count - b.bowls[b.p2_store].count) >= 10)
std::cout<<"FATALITY"<<std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "xmlrpc.h"
#include <QDebug>
#include <QMap>
#include <QVariant>
#include <QDateTime>
#include <QStringList>
#include <QTextStream>
static void marshall( QXmlStreamWriter *writer, const QVariant &value)
{
writer->writeStartElement("value");
switch( value.type() )
{
case QVariant::Int:
case QVariant::UInt:
case QVariant::LongLong:
case QVariant::ULongLong:
writer->writeTextElement("i4", value.toString());
break;
case QVariant::Double:
writer->writeTextElement("double", value.toString());
break;
case QVariant::Bool:
writer->writeTextElement("boolean", (value.toBool()?"true":"false") );
break;
case QVariant::Date:
writer->writeTextElement("dateTime.iso8601", value.toDate().toString( Qt::ISODate ) );
break;
case QVariant::DateTime:
writer->writeTextElement("dateTime.iso8601", value.toDateTime().toString( Qt::ISODate ) );
break;
case QVariant::Time:
writer->writeTextElement("dateTime.iso8601", value.toTime().toString( Qt::ISODate ) );
break;
case QVariant::StringList:
case QVariant::List:
{
writer->writeStartElement("array");
writer->writeStartElement("data");
foreach(const QVariant &item, value.toList())
marshall(writer, item);
writer->writeEndElement();
writer->writeEndElement();
break;
}
case QVariant::Map:
{
writer->writeStartElement("struct");
QMap<QString, QVariant> map = value.toMap();
QMap<QString, QVariant>::ConstIterator index = map.begin();
while( index != map.end() )
{
writer->writeStartElement("member");
writer->writeTextElement("name", index.key());
marshall( writer, *index );
writer->writeEndElement();
++index;
}
writer->writeEndElement();
break;
}
case QVariant::ByteArray:
{
writer->writeTextElement("base64", value.toByteArray().toBase64() );
break;
}
default:
{
if( value.canConvert(QVariant::String) )
{
writer->writeTextElement( "string", value.toString() );
}
break;
}
}
writer->writeEndElement();
}
static QVariant demarshall(const QDomElement &elem, QStringList &errors)
{
if ( elem.tagName().toLower() != "value" )
{
errors << "Bad param value";
return QVariant();
}
if ( !elem.firstChild().isElement() )
{
return QVariant( elem.text() );
}
const QDomElement typeData = elem.firstChild().toElement();
const QString typeName = typeData.tagName().toLower();
if ( typeName == "string" )
{
return QVariant( typeData.text() );
}
else if (typeName == "int" || typeName == "i4" )
{
bool ok = false;
QVariant val( typeData.text().toInt( &ok ) );
if (ok)
return val;
errors << "I was looking for an integer but data was courupt";
return QVariant();
}
else if( typeName == "double" )
{
bool ok = false;
QVariant val( typeData.text().toDouble( &ok ) );
if (ok)
return val;
errors << "I was looking for an double but data was corrupt";
}
else if( typeName == "boolean" )
return QVariant( ( typeData.text().toLower() == "true" || typeData.text() == "1")?true:false );
else if( typeName == "datetime" || typeName == "dateTime.iso8601" )
return QVariant( QDateTime::fromString( typeData.text(), Qt::ISODate ) );
else if( typeName == "array" )
{
QVariantList arr;
QDomNode valueNode = typeData.firstChild().firstChild();
while (!valueNode.isNull() && errors.isEmpty())
{
arr.append(demarshall(valueNode.toElement(), errors));
valueNode = valueNode.nextSibling();
}
return QVariant( arr );
}
else if( typeName == "struct" )
{
QMap<QString,QVariant> stct;
QDomNode valueNode = typeData.firstChild();
while(!valueNode.isNull() && errors.isEmpty())
{
const QDomElement memberNode = valueNode.toElement().elementsByTagName("name").item(0).toElement();
const QDomElement dataNode = valueNode.toElement().elementsByTagName("value").item(0).toElement();
stct[ memberNode.text() ] = demarshall(dataNode, errors);
valueNode = valueNode.nextSibling();
}
return QVariant(stct);
}
else if( typeName == "base64" )
{
QVariant returnVariant;
QByteArray dest;
QByteArray src = typeData.text().toLatin1();
dest = QByteArray::fromBase64( src );
QDataStream ds(&dest, QIODevice::ReadOnly);
ds.setVersion(QDataStream::Qt_4_0);
ds >> returnVariant;
if (returnVariant.isValid())
return returnVariant;
else
return QVariant( dest );
}
errors << QString( "Cannot handle type %1").arg(typeName);
return QVariant();
}
bool XMLRPC::RequestMessage::parse(const QDomElement &element)
{
QStringList errors;
m_args.clear();
m_method.clear();
const QDomElement methodName = element.firstChildElement("methodName");
if( !methodName.isNull() )
{
m_method = methodName.text().toLatin1();
}
else
{
errors << "Missing methodName property";
return false;
}
const QDomElement methodParams = element.firstChildElement("params");
if( !methodParams.isNull() )
{
QDomNode param = methodParams.firstChild();
while (!param.isNull())
{
QVariant arg = demarshall(param.firstChild().toElement(), errors);
if (!errors.isEmpty())
return false;
m_args << arg;
param = param.nextSibling();
}
}
return true;
}
QVariantList XMLRPC::RequestMessage::arguments() const
{
return m_args;
}
void XMLRPC::RequestMessage::setArguments(const QVariantList &args)
{
m_args = args;
}
QByteArray XMLRPC::RequestMessage::method() const
{
return m_method;
}
void XMLRPC::RequestMessage::setMethod(const QByteArray &method)
{
m_method = method;
}
void XMLRPC::RequestMessage::writeXml( QXmlStreamWriter *writer ) const
{
writer->writeStartElement("methodCall");
writer->writeTextElement("methodName", m_method );
if( !m_args.isEmpty() )
{
writer->writeStartElement("params");
foreach(const QVariant &arg, m_args)
{
writer->writeStartElement("param");
marshall(writer, arg);
writer->writeEndElement();
}
writer->writeEndElement();
}
writer->writeEndElement();
}
bool XMLRPC::ResponseMessage::parse(const QDomElement &element)
{
QStringList errors;
const QDomElement contents = element.firstChild().toElement();
if( contents.tagName().toLower() == "params")
{
QDomNode param = contents.firstChild();
while (!param.isNull())
{
const QVariant value = demarshall(param.firstChild().toElement(), errors);
if (!errors.isEmpty())
return false;
m_values << value;
param = param.nextSibling();
}
return true;
}
else if( contents.tagName().toLower() == "fault")
{
const QDomElement errElement = contents.firstChild().toElement();
const QVariant error = demarshall(errElement, errors);
qWarning() << QString("XMLRPC Fault %1: %2")
.arg(error.toMap()["faultCode"].toString() )
.arg(error.toMap()["faultString"].toString() );
return true;
}
else
{
qWarning("Bad XML response");
return false;
}
}
QVariantList XMLRPC::ResponseMessage::values() const
{
return m_values;
}
void XMLRPC::ResponseMessage::setValues(const QVariantList &values)
{
m_values = values;
}
void XMLRPC::ResponseMessage::writeXml( QXmlStreamWriter *writer ) const
{
writer->writeStartElement("methodResponse");
if( !m_values.isEmpty() )
{
writer->writeStartElement("params");
foreach (const QVariant &arg, m_values)
{
writer->writeStartElement("param");
marshall(writer, arg);
writer->writeEndElement();
}
writer->writeEndElement();
}
writer->writeEndElement();
}
<commit_msg>tighten XML RPC parsing<commit_after>#include "xmlrpc.h"
#include <QDebug>
#include <QMap>
#include <QVariant>
#include <QDateTime>
#include <QStringList>
#include <QTextStream>
static void marshall( QXmlStreamWriter *writer, const QVariant &value)
{
writer->writeStartElement("value");
switch( value.type() )
{
case QVariant::Int:
case QVariant::UInt:
case QVariant::LongLong:
case QVariant::ULongLong:
writer->writeTextElement("i4", value.toString());
break;
case QVariant::Double:
writer->writeTextElement("double", value.toString());
break;
case QVariant::Bool:
writer->writeTextElement("boolean", (value.toBool()?"true":"false") );
break;
case QVariant::Date:
writer->writeTextElement("dateTime.iso8601", value.toDate().toString( Qt::ISODate ) );
break;
case QVariant::DateTime:
writer->writeTextElement("dateTime.iso8601", value.toDateTime().toString( Qt::ISODate ) );
break;
case QVariant::Time:
writer->writeTextElement("dateTime.iso8601", value.toTime().toString( Qt::ISODate ) );
break;
case QVariant::StringList:
case QVariant::List:
{
writer->writeStartElement("array");
writer->writeStartElement("data");
foreach(const QVariant &item, value.toList())
marshall(writer, item);
writer->writeEndElement();
writer->writeEndElement();
break;
}
case QVariant::Map:
{
writer->writeStartElement("struct");
QMap<QString, QVariant> map = value.toMap();
QMap<QString, QVariant>::ConstIterator index = map.begin();
while( index != map.end() )
{
writer->writeStartElement("member");
writer->writeTextElement("name", index.key());
marshall( writer, *index );
writer->writeEndElement();
++index;
}
writer->writeEndElement();
break;
}
case QVariant::ByteArray:
{
writer->writeTextElement("base64", value.toByteArray().toBase64() );
break;
}
default:
{
if( value.canConvert(QVariant::String) )
{
writer->writeTextElement( "string", value.toString() );
}
break;
}
}
writer->writeEndElement();
}
static QVariant demarshall(const QDomElement &elem, QStringList &errors)
{
if ( elem.tagName().toLower() != "value" )
{
errors << "Bad param value";
return QVariant();
}
if ( !elem.firstChild().isElement() )
{
return QVariant( elem.text() );
}
const QDomElement typeData = elem.firstChild().toElement();
const QString typeName = typeData.tagName().toLower();
if ( typeName == "string" )
{
return QVariant( typeData.text() );
}
else if (typeName == "int" || typeName == "i4" )
{
bool ok = false;
QVariant val( typeData.text().toInt( &ok ) );
if (ok)
return val;
errors << "I was looking for an integer but data was courupt";
return QVariant();
}
else if( typeName == "double" )
{
bool ok = false;
QVariant val( typeData.text().toDouble( &ok ) );
if (ok)
return val;
errors << "I was looking for an double but data was corrupt";
}
else if( typeName == "boolean" )
return QVariant( ( typeData.text().toLower() == "true" || typeData.text() == "1")?true:false );
else if( typeName == "datetime" || typeName == "dateTime.iso8601" )
return QVariant( QDateTime::fromString( typeData.text(), Qt::ISODate ) );
else if( typeName == "array" )
{
QVariantList arr;
QDomNode valueNode = typeData.firstChild().firstChild();
while (!valueNode.isNull() && errors.isEmpty())
{
arr.append(demarshall(valueNode.toElement(), errors));
valueNode = valueNode.nextSibling();
}
return QVariant( arr );
}
else if( typeName == "struct" )
{
QMap<QString,QVariant> stct;
QDomNode valueNode = typeData.firstChild();
while(!valueNode.isNull() && errors.isEmpty())
{
const QDomElement memberNode = valueNode.toElement().elementsByTagName("name").item(0).toElement();
const QDomElement dataNode = valueNode.toElement().elementsByTagName("value").item(0).toElement();
stct[ memberNode.text() ] = demarshall(dataNode, errors);
valueNode = valueNode.nextSibling();
}
return QVariant(stct);
}
else if( typeName == "base64" )
{
QVariant returnVariant;
QByteArray dest;
QByteArray src = typeData.text().toLatin1();
dest = QByteArray::fromBase64( src );
QDataStream ds(&dest, QIODevice::ReadOnly);
ds.setVersion(QDataStream::Qt_4_0);
ds >> returnVariant;
if (returnVariant.isValid())
return returnVariant;
else
return QVariant( dest );
}
errors << QString( "Cannot handle type %1").arg(typeName);
return QVariant();
}
bool XMLRPC::RequestMessage::parse(const QDomElement &element)
{
QStringList errors;
m_args.clear();
m_method.clear();
const QDomElement methodName = element.firstChildElement("methodName");
if( !methodName.isNull() )
{
m_method = methodName.text().toLatin1();
}
else
{
errors << "Missing methodName property";
return false;
}
const QDomElement methodParams = element.firstChildElement("params");
if( !methodParams.isNull() )
{
QDomNode param = methodParams.firstChildElement("param");
while (!param.isNull())
{
QVariant arg = demarshall(param.firstChild().toElement(), errors);
if (!errors.isEmpty())
return false;
m_args << arg;
param = param.nextSiblingElement("param");
}
}
return true;
}
QVariantList XMLRPC::RequestMessage::arguments() const
{
return m_args;
}
void XMLRPC::RequestMessage::setArguments(const QVariantList &args)
{
m_args = args;
}
QByteArray XMLRPC::RequestMessage::method() const
{
return m_method;
}
void XMLRPC::RequestMessage::setMethod(const QByteArray &method)
{
m_method = method;
}
void XMLRPC::RequestMessage::writeXml( QXmlStreamWriter *writer ) const
{
writer->writeStartElement("methodCall");
writer->writeTextElement("methodName", m_method );
if( !m_args.isEmpty() )
{
writer->writeStartElement("params");
foreach(const QVariant &arg, m_args)
{
writer->writeStartElement("param");
marshall(writer, arg);
writer->writeEndElement();
}
writer->writeEndElement();
}
writer->writeEndElement();
}
bool XMLRPC::ResponseMessage::parse(const QDomElement &element)
{
QStringList errors;
const QDomElement contents = element.firstChild().toElement();
if( contents.tagName().toLower() == "params")
{
QDomNode param = contents.firstChildElement("param");
while (!param.isNull())
{
const QVariant value = demarshall(param.firstChildElement(), errors);
if (!errors.isEmpty())
return false;
m_values << value;
param = param.nextSiblingElement("param");
}
return true;
}
else if( contents.tagName().toLower() == "fault")
{
const QDomElement errElement = contents.firstChildElement();
const QVariant error = demarshall(errElement, errors);
qWarning() << QString("XMLRPC Fault %1: %2")
.arg(error.toMap()["faultCode"].toString() )
.arg(error.toMap()["faultString"].toString() );
return true;
}
else
{
qWarning("Bad XML response");
return false;
}
}
QVariantList XMLRPC::ResponseMessage::values() const
{
return m_values;
}
void XMLRPC::ResponseMessage::setValues(const QVariantList &values)
{
m_values = values;
}
void XMLRPC::ResponseMessage::writeXml( QXmlStreamWriter *writer ) const
{
writer->writeStartElement("methodResponse");
if( !m_values.isEmpty() )
{
writer->writeStartElement("params");
foreach (const QVariant &arg, m_values)
{
writer->writeStartElement("param");
marshall(writer, arg);
writer->writeEndElement();
}
writer->writeEndElement();
}
writer->writeEndElement();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "entry.h"
#include "journal.h"
#include "format.h"
#include "report.h"
namespace ledger {
entry_base_t::entry_base_t(const entry_base_t& e)
: item_t(), journal(NULL)
{
TRACE_CTOR(entry_base_t, "copy");
#if 0
xacts.insert(xacts.end(), e.xacts.begin(), e.xacts.end());
#endif
}
entry_base_t::~entry_base_t()
{
TRACE_DTOR(entry_base_t);
foreach (xact_t * xact, xacts) {
// If the transaction is a temporary, it will be destructed when the
// temporary is.
if (! xact->has_flags(ITEM_TEMP))
checked_delete(xact);
}
}
item_t::state_t entry_base_t::state() const
{
bool first = true;
state_t result = CLEARED;
foreach (xact_t * xact, xacts) {
if (xact->_state == UNCLEARED)
return UNCLEARED;
else if (xact->_state == PENDING)
result = PENDING;
}
return result;
}
void entry_base_t::add_xact(xact_t * xact)
{
xacts.push_back(xact);
}
bool entry_base_t::remove_xact(xact_t * xact)
{
xacts.remove(xact);
xact->entry = NULL;
return true;
}
bool entry_base_t::finalize()
{
// Scan through and compute the total balance for the entry. This is used
// for auto-calculating the value of entries with no cost, and the per-unit
// price of unpriced commodities.
// (let ((balance 0)
// null-xact)
value_t balance;
xact_t * null_xact = NULL;
foreach (xact_t * xact, xacts) {
if (xact->must_balance()) {
amount_t& p(xact->cost ? *xact->cost : xact->amount);
DEBUG("entry.finalize", "xact must balance = " << p);
if (! p.is_null()) {
if (p.keep_precision()) {
// If the amount was a cost, it very likely has the "keep_precision"
// flag set, meaning commodity display precision is ignored when
// displaying the amount. We never want this set for the balance,
// so we must clear the flag in a temporary to avoid it propagating
// into the balance.
add_or_set_value(balance, p.rounded());
} else {
add_or_set_value(balance, p);
}
} else {
if (null_xact)
throw_(std::logic_error,
"Only one xact with null amount allowed per entry");
else
null_xact = xact;
}
}
}
assert(balance.valid());
DEBUG("entry.finalize", "initial balance = " << balance);
// If there is only one xact, balance against the default account if
// one has been set.
if (journal && journal->basket && xacts.size() == 1 && ! balance.is_null()) {
// jww (2008-07-24): Need to make the rest of the code aware of what to do
// when it sees a generated xact.
null_xact = new xact_t(journal->basket, ITEM_GENERATED);
null_xact->_state = (*xacts.begin())->_state;
add_xact(null_xact);
}
if (null_xact != NULL) {
// If one xact has no value at all, its value will become the
// inverse of the rest. If multiple commodities are involved, multiple
// xacts are generated to balance them all.
if (balance.is_balance()) {
bool first = true;
const balance_t& bal(balance.as_balance());
foreach (const balance_t::amounts_map::value_type& pair, bal.amounts) {
if (first) {
null_xact->amount = pair.second.negate();
first = false;
} else {
add_xact(new xact_t(null_xact->account, pair.second.negate(),
ITEM_GENERATED));
}
}
}
else if (balance.is_amount()) {
null_xact->amount = balance.as_amount().negate();
null_xact->add_flags(XACT_CALCULATED);
}
else if (! balance.is_null() && ! balance.is_realzero()) {
throw_(balance_error, "Entry does not balance");
}
balance = NULL_VALUE;
}
else if (balance.is_balance() &&
balance.as_balance().amounts.size() == 2) {
// When an entry involves two different commodities (regardless of how
// many xacts there are) determine the conversion ratio by dividing
// the total value of one commodity by the total value of the other. This
// establishes the per-unit cost for this xact for both
// commodities.
const balance_t& bal(balance.as_balance());
balance_t::amounts_map::const_iterator a = bal.amounts.begin();
const amount_t& x((*a++).second);
const amount_t& y((*a++).second);
if (! y.is_realzero()) {
amount_t per_unit_cost = (x / y).abs();
commodity_t& comm(x.commodity());
foreach (xact_t * xact, xacts) {
const amount_t& amt(xact->amount);
if (! (xact->cost || ! xact->must_balance() ||
amt.commodity() == comm)) {
balance -= amt;
xact->cost = per_unit_cost * amt;
balance += *xact->cost;
}
}
}
DEBUG("entry.finalize", "resolved balance = " << balance);
}
// Now that the xact list has its final form, calculate the balance
// once more in terms of total cost, accounting for any possible gain/loss
// amounts.
foreach (xact_t * xact, xacts) {
if (xact->cost) {
if (xact->amount.commodity() == xact->cost->commodity())
throw_(balance_error, "Transaction's cost must be of a different commodity");
commodity_t::cost_breakdown_t breakdown =
commodity_t::exchange(xact->amount, *xact->cost);
if (xact->amount.is_annotated())
add_or_set_value(balance, (breakdown.basis_cost -
breakdown.final_cost).rounded());
else
xact->amount = breakdown.amount;
}
}
DEBUG("entry.finalize", "final balance = " << balance);
if (! balance.is_null() && ! balance.is_zero()) {
add_error_context(item_context(*this, "While balancing entry"));
add_error_context("Unbalanced remainder is:");
add_error_context(value_context(balance));
throw_(balance_error, "Entry does not balance");
}
// Add the final calculated totals each to their related account
if (dynamic_cast<entry_t *>(this)) {
bool all_null = true;
foreach (xact_t * xact, xacts) {
if (! xact->amount.is_null()) {
all_null = false;
// jww (2008-08-09): For now, this feature only works for
// non-specific commodities.
add_or_set_value(xact->account->xdata().value, xact->amount);
DEBUG("entry.finalize.totals",
"Total for " << xact->account->fullname() << " + "
<< xact->amount << ": " << xact->account->xdata().value);
}
}
if (all_null)
return false; // ignore this entry completely
}
return true;
}
entry_t::entry_t(const entry_t& e)
: entry_base_t(e), code(e.code), payee(e.payee)
{
TRACE_CTOR(entry_t, "copy");
#if 0
foreach (xact_t * xact, xacts)
xact->entry = this;
#endif
}
void entry_t::add_xact(xact_t * xact)
{
xact->entry = this;
entry_base_t::add_xact(xact);
}
namespace {
value_t get_code(entry_t& entry) {
if (entry.code)
return string_value(*entry.code);
else
return string_value(empty_string);
}
value_t get_payee(entry_t& entry) {
return string_value(entry.payee);
}
template <value_t (*Func)(entry_t&)>
value_t get_wrapper(call_scope_t& scope) {
return (*Func)(find_scope<entry_t>(scope));
}
}
expr_t::ptr_op_t entry_t::lookup(const string& name)
{
switch (name[0]) {
case 'c':
if (name == "code")
return WRAP_FUNCTOR(get_wrapper<&get_code>);
break;
case 'p':
if (name[1] == '\0' || name == "payee")
return WRAP_FUNCTOR(get_wrapper<&get_payee>);
break;
}
return item_t::lookup(name);
}
bool entry_t::valid() const
{
if (! _date || ! journal) {
DEBUG("ledger.validate", "entry_t: ! _date || ! journal");
return false;
}
foreach (xact_t * xact, xacts)
if (xact->entry != this || ! xact->valid()) {
DEBUG("ledger.validate", "entry_t: xact not valid");
return false;
}
return true;
}
void auto_entry_t::extend_entry(entry_base_t& entry, bool post)
{
xacts_list initial_xacts(entry.xacts.begin(),
entry.xacts.end());
foreach (xact_t * initial_xact, initial_xacts) {
if (predicate(*initial_xact)) {
foreach (xact_t * xact, xacts) {
amount_t amt;
assert(xact->amount);
if (! xact->amount.commodity()) {
if (! post)
continue;
assert(initial_xact->amount);
amt = initial_xact->amount * xact->amount;
} else {
if (post)
continue;
amt = xact->amount;
}
IF_DEBUG("entry.extend") {
DEBUG("entry.extend",
"Initial xact on line " << initial_xact->beg_line << ": "
<< "amount " << initial_xact->amount << " (precision "
<< initial_xact->amount.precision() << ")");
if (initial_xact->amount.keep_precision())
DEBUG("entry.extend", " precision is kept");
DEBUG("entry.extend",
"Transaction on line " << xact->beg_line << ": "
<< "amount " << xact->amount << ", amt " << amt
<< " (precision " << xact->amount.precision()
<< " != " << amt.precision() << ")");
if (xact->amount.keep_precision())
DEBUG("entry.extend", " precision is kept");
if (amt.keep_precision())
DEBUG("entry.extend", " amt precision is kept");
}
account_t * account = xact->account;
string fullname = account->fullname();
assert(! fullname.empty());
if (fullname == "$account" || fullname == "@account")
account = initial_xact->account;
// Copy over details so that the resulting xact is a mirror of
// the automated entry's one.
xact_t * new_xact = new xact_t(account, amt);
new_xact->copy_details(*xact);
new_xact->add_flags(XACT_AUTO);
entry.add_xact(new_xact);
}
}
}
}
void extend_entry_base(journal_t * journal, entry_base_t& base, bool post)
{
foreach (auto_entry_t * entry, journal->auto_entries)
entry->extend_entry(base, post);
}
} // namespace ledger
<commit_msg>Don't apply an automated entry to a generated transaction.<commit_after>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "entry.h"
#include "journal.h"
#include "format.h"
#include "report.h"
namespace ledger {
entry_base_t::entry_base_t(const entry_base_t& e)
: item_t(), journal(NULL)
{
TRACE_CTOR(entry_base_t, "copy");
#if 0
xacts.insert(xacts.end(), e.xacts.begin(), e.xacts.end());
#endif
}
entry_base_t::~entry_base_t()
{
TRACE_DTOR(entry_base_t);
foreach (xact_t * xact, xacts) {
// If the transaction is a temporary, it will be destructed when the
// temporary is.
if (! xact->has_flags(ITEM_TEMP))
checked_delete(xact);
}
}
item_t::state_t entry_base_t::state() const
{
bool first = true;
state_t result = CLEARED;
foreach (xact_t * xact, xacts) {
if (xact->_state == UNCLEARED)
return UNCLEARED;
else if (xact->_state == PENDING)
result = PENDING;
}
return result;
}
void entry_base_t::add_xact(xact_t * xact)
{
xacts.push_back(xact);
}
bool entry_base_t::remove_xact(xact_t * xact)
{
xacts.remove(xact);
xact->entry = NULL;
return true;
}
bool entry_base_t::finalize()
{
// Scan through and compute the total balance for the entry. This is used
// for auto-calculating the value of entries with no cost, and the per-unit
// price of unpriced commodities.
// (let ((balance 0)
// null-xact)
value_t balance;
xact_t * null_xact = NULL;
foreach (xact_t * xact, xacts) {
if (xact->must_balance()) {
amount_t& p(xact->cost ? *xact->cost : xact->amount);
DEBUG("entry.finalize", "xact must balance = " << p);
if (! p.is_null()) {
if (p.keep_precision()) {
// If the amount was a cost, it very likely has the "keep_precision"
// flag set, meaning commodity display precision is ignored when
// displaying the amount. We never want this set for the balance,
// so we must clear the flag in a temporary to avoid it propagating
// into the balance.
add_or_set_value(balance, p.rounded());
} else {
add_or_set_value(balance, p);
}
} else {
if (null_xact)
throw_(std::logic_error,
"Only one xact with null amount allowed per entry");
else
null_xact = xact;
}
}
}
assert(balance.valid());
DEBUG("entry.finalize", "initial balance = " << balance);
// If there is only one xact, balance against the default account if
// one has been set.
if (journal && journal->basket && xacts.size() == 1 && ! balance.is_null()) {
// jww (2008-07-24): Need to make the rest of the code aware of what to do
// when it sees a generated xact.
null_xact = new xact_t(journal->basket, ITEM_GENERATED);
null_xact->_state = (*xacts.begin())->_state;
add_xact(null_xact);
}
if (null_xact != NULL) {
// If one xact has no value at all, its value will become the
// inverse of the rest. If multiple commodities are involved, multiple
// xacts are generated to balance them all.
if (balance.is_balance()) {
bool first = true;
const balance_t& bal(balance.as_balance());
foreach (const balance_t::amounts_map::value_type& pair, bal.amounts) {
if (first) {
null_xact->amount = pair.second.negate();
first = false;
} else {
add_xact(new xact_t(null_xact->account, pair.second.negate(),
ITEM_GENERATED));
}
}
}
else if (balance.is_amount()) {
null_xact->amount = balance.as_amount().negate();
null_xact->add_flags(XACT_CALCULATED);
}
else if (! balance.is_null() && ! balance.is_realzero()) {
throw_(balance_error, "Entry does not balance");
}
balance = NULL_VALUE;
}
else if (balance.is_balance() &&
balance.as_balance().amounts.size() == 2) {
// When an entry involves two different commodities (regardless of how
// many xacts there are) determine the conversion ratio by dividing
// the total value of one commodity by the total value of the other. This
// establishes the per-unit cost for this xact for both
// commodities.
const balance_t& bal(balance.as_balance());
balance_t::amounts_map::const_iterator a = bal.amounts.begin();
const amount_t& x((*a++).second);
const amount_t& y((*a++).second);
if (! y.is_realzero()) {
amount_t per_unit_cost = (x / y).abs();
commodity_t& comm(x.commodity());
foreach (xact_t * xact, xacts) {
const amount_t& amt(xact->amount);
if (! (xact->cost || ! xact->must_balance() ||
amt.commodity() == comm)) {
balance -= amt;
xact->cost = per_unit_cost * amt;
balance += *xact->cost;
}
}
}
DEBUG("entry.finalize", "resolved balance = " << balance);
}
// Now that the xact list has its final form, calculate the balance
// once more in terms of total cost, accounting for any possible gain/loss
// amounts.
foreach (xact_t * xact, xacts) {
if (xact->cost) {
if (xact->amount.commodity() == xact->cost->commodity())
throw_(balance_error, "Transaction's cost must be of a different commodity");
commodity_t::cost_breakdown_t breakdown =
commodity_t::exchange(xact->amount, *xact->cost);
if (xact->amount.is_annotated())
add_or_set_value(balance, (breakdown.basis_cost -
breakdown.final_cost).rounded());
else
xact->amount = breakdown.amount;
}
}
DEBUG("entry.finalize", "final balance = " << balance);
if (! balance.is_null() && ! balance.is_zero()) {
add_error_context(item_context(*this, "While balancing entry"));
add_error_context("Unbalanced remainder is:");
add_error_context(value_context(balance));
throw_(balance_error, "Entry does not balance");
}
// Add the final calculated totals each to their related account
if (dynamic_cast<entry_t *>(this)) {
bool all_null = true;
foreach (xact_t * xact, xacts) {
if (! xact->amount.is_null()) {
all_null = false;
// jww (2008-08-09): For now, this feature only works for
// non-specific commodities.
add_or_set_value(xact->account->xdata().value, xact->amount);
DEBUG("entry.finalize.totals",
"Total for " << xact->account->fullname() << " + "
<< xact->amount << ": " << xact->account->xdata().value);
}
}
if (all_null)
return false; // ignore this entry completely
}
return true;
}
entry_t::entry_t(const entry_t& e)
: entry_base_t(e), code(e.code), payee(e.payee)
{
TRACE_CTOR(entry_t, "copy");
#if 0
foreach (xact_t * xact, xacts)
xact->entry = this;
#endif
}
void entry_t::add_xact(xact_t * xact)
{
xact->entry = this;
entry_base_t::add_xact(xact);
}
namespace {
value_t get_code(entry_t& entry) {
if (entry.code)
return string_value(*entry.code);
else
return string_value(empty_string);
}
value_t get_payee(entry_t& entry) {
return string_value(entry.payee);
}
template <value_t (*Func)(entry_t&)>
value_t get_wrapper(call_scope_t& scope) {
return (*Func)(find_scope<entry_t>(scope));
}
}
expr_t::ptr_op_t entry_t::lookup(const string& name)
{
switch (name[0]) {
case 'c':
if (name == "code")
return WRAP_FUNCTOR(get_wrapper<&get_code>);
break;
case 'p':
if (name[1] == '\0' || name == "payee")
return WRAP_FUNCTOR(get_wrapper<&get_payee>);
break;
}
return item_t::lookup(name);
}
bool entry_t::valid() const
{
if (! _date || ! journal) {
DEBUG("ledger.validate", "entry_t: ! _date || ! journal");
return false;
}
foreach (xact_t * xact, xacts)
if (xact->entry != this || ! xact->valid()) {
DEBUG("ledger.validate", "entry_t: xact not valid");
return false;
}
return true;
}
void auto_entry_t::extend_entry(entry_base_t& entry, bool post)
{
xacts_list initial_xacts(entry.xacts.begin(), entry.xacts.end());
foreach (xact_t * initial_xact, initial_xacts) {
if (! initial_xact->has_flags(XACT_AUTO) && predicate(*initial_xact)) {
foreach (xact_t * xact, xacts) {
amount_t amt;
assert(xact->amount);
if (! xact->amount.commodity()) {
if (! post)
continue;
assert(initial_xact->amount);
amt = initial_xact->amount * xact->amount;
} else {
if (post)
continue;
amt = xact->amount;
}
IF_DEBUG("entry.extend") {
DEBUG("entry.extend",
"Initial xact on line " << initial_xact->beg_line << ": "
<< "amount " << initial_xact->amount << " (precision "
<< initial_xact->amount.precision() << ")");
if (initial_xact->amount.keep_precision())
DEBUG("entry.extend", " precision is kept");
DEBUG("entry.extend",
"Transaction on line " << xact->beg_line << ": "
<< "amount " << xact->amount << ", amt " << amt
<< " (precision " << xact->amount.precision()
<< " != " << amt.precision() << ")");
if (xact->amount.keep_precision())
DEBUG("entry.extend", " precision is kept");
if (amt.keep_precision())
DEBUG("entry.extend", " amt precision is kept");
}
account_t * account = xact->account;
string fullname = account->fullname();
assert(! fullname.empty());
if (fullname == "$account" || fullname == "@account")
account = initial_xact->account;
// Copy over details so that the resulting xact is a mirror of
// the automated entry's one.
xact_t * new_xact = new xact_t(account, amt);
new_xact->copy_details(*xact);
new_xact->add_flags(XACT_AUTO);
entry.add_xact(new_xact);
}
}
}
}
void extend_entry_base(journal_t * journal, entry_base_t& base, bool post)
{
foreach (auto_entry_t * entry, journal->auto_entries)
entry->extend_entry(base, post);
}
} // namespace ledger
<|endoftext|>
|
<commit_before>/** \addtogroup examples
* @{
* \defgroup fft fft
* @{
* \brief FFT iterative method using gemv and spmv
*/
#include <ctf.hpp>
using namespace CTF;
namespace CTF_int{
void factorize(int n, int *nfactor, int **factor);
}
Matrix< std::complex<double> > DFT_matrix(int n, World & wrld){
int64_t np;
int64_t * idx;
std::complex<double> imag(0,1);
std::complex<double> * data;
Matrix < std::complex<double> >DFT(n, n, NS, wrld, "DFT");
DFT.read_local(&np, &idx, &data);
for (int64_t i=0; i<np; i++){
data[i] = exp(-2.*(idx[i]/n)*(idx[i]%n)*(M_PI/n)*imag);
}
DFT.write(np, idx, data);
free(idx);
free(data);
return DFT;
}
void fft(Vector< std::complex<double> > & v, int n){
int64_t np;
int64_t * idx;
std::complex<double> * data;
int logn=0;
while (1<<logn < n){
logn++;
}
assert(1<<logn == n);
int nfact;
int * factors;
CTF_int::factorize(n, &nfact, &factors);
assert(nfact == logn);
Tensor< std::complex<double> > V(nfact, factors, *v.wrld, *v.sr, "V");
v.read_local(&np, &idx, &data);
V.write(np, idx, data);
free(idx);
free(data);
char inds[nfact+1];
char rev_inds[nfact];
for (int i=0; i<nfact; i++){
inds[i]='a'+i;
rev_inds[i]='a'+nfact-i-1;
}
inds[nfact] = 'a';
//reverse tensor index order (corresponds to no-op recursion in FFT that picks odds/evens) so that I am less confused
V[rev_inds] = V[inds];
for (int i=0; i<nfact; i++){
inds[nfact+i]='a'+i;
}
V.print();
Matrix< std::complex<double> > DFT = DFT_matrix(2,*v.wrld);
for (int i=0; i<nfact; i++){
Tensor< std::complex<double> > S(i+1, factors, *v.wrld, *v.sr, "S");
S.read_local(&np, &idx, &data);
std::complex<double> imag(0,1);
for(int64_t i=0; i<np; i++){
if (idx[i]%2 == 1){
data[i] = exp(-2.*(idx[i]/2)*(M_PI/n)*imag);
} else {
data[i] = std::complex<double>(1.0,0.0);
}
}
S.write(np, idx, data);
S.print();
V[inds+1] *= S[inds];
char inds_in[nfact];
char inds_out[nfact];
char inds_DFT[2];
memcpy(inds_in, inds, nfact*sizeof(char));
inds_in[i] = 'z';
memcpy(inds_out, inds, nfact*sizeof(char));
inds_DFT[0] = inds_out[i];
inds_DFT[1] = 'z';
V[inds_out] = DFT[inds_DFT]*V[inds_in];
}
free(idx);
free(data);
V.read_local(&np, &idx, &data);
v.write(np, idx, data);
free(idx);
free(data);
}
int fft(int n,
World & dw){
Vector< std::complex<double> > a(n, dw, "a");
Vector< std::complex<double> > da(n, dw, "da");
srand48(2*dw.rank);
Transform< std::complex<double> > set_rand([](std::complex<double> & d){ d=std::complex<double>(drand48(),drand48()); } );
set_rand(a["i"]);
/*if (dw.rank == 0){
std::complex<double> val (1.0, 0.0);
int64_t idx = 2;
a.write(1, &idx, &val);
} else a.write(0,NULL,NULL);
*/
// a.sparsify([](std::complex<double> d){ return fabs(d.real()) > .8; });
Matrix< std::complex<double> > DFT = DFT_matrix(n,dw);
da["i"] = DFT["ij"]*a["j"];
Vector< std::complex<double> > fa(n, dw, "fa");
fa["i"] = a["i"];
fft(fa, n);
fa.print();
da.print();
da["i"] -= fa["i"];
std::complex<double> dnrm;
Scalar< std::complex<double> > s(dnrm, dw);
s.print();
s[""] += da["i"]*da["i"];
s.print();
dnrm = s;
bool pass = fabs(dnrm.real()) <= 1.E-6 && fabs(dnrm.imag()) <= 1.E-6;
if (dw.rank == 0){
if (pass)
printf("{ FFT = DFT } passed \n");
else
printf("{ FFT = DFT } failed \n");
}
return pass;
}
#ifndef TEST_SUITE
char* getCmdOption(char ** begin,
char ** end,
const std::string & option){
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end){
return *itr;
}
return 0;
}
int main(int argc, char ** argv){
int rank, np, n, pass;
int const in_num = argc;
char ** input_str = argv;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &np);
if (getCmdOption(input_str, input_str+in_num, "-n")){
n = atoi(getCmdOption(input_str, input_str+in_num, "-n"));
if (n < 0) n = 7;
} else n = 7;
{
World dw(argc, argv);
if (rank == 0){
printf("Running FFT on random dimension %d vector\n",n);
}
pass = fft(n, dw);
assert(pass);
}
MPI_Finalize();
return 0;
}
/**
* @}
* @}
*/
#endif
<commit_msg>FFT works!<commit_after>/** \addtogroup examples
* @{
* \defgroup fft fft
* @{
* \brief FFT iterative method using gemv and spmv
*/
#include <ctf.hpp>
using namespace CTF;
namespace CTF_int{
void factorize(int n, int *nfactor, int **factor);
}
std::complex<double> omega(int i, int n){
std::complex<double> imag(0,1);
return exp(-2.*i*(M_PI/n)*imag);
}
Matrix< std::complex<double> > DFT_matrix(int n, World & wrld){
int64_t np;
int64_t * idx;
std::complex<double> * data;
Matrix < std::complex<double> >DFT(n, n, NS, wrld, "DFT");
DFT.read_local(&np, &idx, &data);
for (int64_t i=0; i<np; i++){
data[i] = omega((idx[i]/n)*(idx[i]%n), n);
}
DFT.write(np, idx, data);
free(idx);
free(data);
return DFT;
}
void fft(Vector< std::complex<double> > & v, int n){
int64_t np;
int64_t * idx;
std::complex<double> * data;
int logn=0;
while (1<<logn < n){
logn++;
}
assert(1<<logn == n);
int nfact;
int * factors;
CTF_int::factorize(n, &nfact, &factors);
assert(nfact == logn);
Tensor< std::complex<double> > V(nfact, factors, *v.wrld, *v.sr, "V");
v.read_local(&np, &idx, &data);
V.write(np, idx, data);
free(idx);
free(data);
char inds[nfact+1];
char rev_inds[nfact];
for (int i=0; i<nfact; i++){
inds[i]='a'+i;
rev_inds[i]='a'+nfact-i-1;
}
inds[nfact] = 'a';
//reverse tensor index order (corresponds to no-op recursion in FFT that picks odds/evens) so that I am less confused
V[rev_inds] = V[inds];
for (int i=0; i<nfact; i++){
inds[nfact+i]='a'+i;
}
Matrix< std::complex<double> > DFT = DFT_matrix(2,*v.wrld);
int i2 = 1;
for (int i=0; i<nfact; i++){
i2*=2;
Tensor< std::complex<double> > S(i+1, factors, *v.wrld, *v.sr, "S");
S.read_local(&np, &idx, &data);
std::complex<double> imag(0,1);
for(int64_t j=0; j<np; j++){
if (idx[j]*2/i2 == 1){
data[j] = omega(idx[j]%(i2/2),i2);
} else {
data[j] = std::complex<double>(1.0,0.0);
}
}
S.write(np, idx, data);
V[inds] *= S[inds];
char inds_in[nfact];
char inds_out[nfact];
char inds_DFT[2];
memcpy(inds_in, inds, nfact*sizeof(char));
inds_in[i] = 'z';
memcpy(inds_out, inds, nfact*sizeof(char));
inds_DFT[0] = inds_out[i];
inds_DFT[1] = 'z';
V[inds_out] = DFT[inds_DFT]*V[inds_in];
}
free(idx);
free(data);
V.read_local(&np, &idx, &data);
v.write(np, idx, data);
free(idx);
free(data);
}
int fft(int n,
World & dw){
Vector< std::complex<double> > a(n, dw, "a");
Vector< std::complex<double> > da(n, dw, "da");
srand48(2*dw.rank);
Transform< std::complex<double> > set_rand([](std::complex<double> & d){ d=std::complex<double>(drand48(),drand48()); } );
set_rand(a["i"]);
/*if (dw.rank == 0){
std::complex<double> val (1.0, 0.0);
int64_t idx = 2;
a.write(1, &idx, &val);
} else a.write(0,NULL,NULL);
*/
// a.sparsify([](std::complex<double> d){ return fabs(d.real()) > .8; });
Matrix< std::complex<double> > DFT = DFT_matrix(n,dw);
da["i"] = DFT["ij"]*a["j"];
Vector< std::complex<double> > fa(n, dw, "fa");
fa["i"] = a["i"];
fft(fa, n);
da["i"] -= fa["i"];
std::complex<double> dnrm;
Scalar< std::complex<double> > s(dnrm, dw);
s[""] += da["i"]*da["i"];
dnrm = s;
bool pass = fabs(dnrm.real()) <= 1.E-6 && fabs(dnrm.imag()) <= 1.E-6;
if (dw.rank == 0){
if (pass)
printf("{ FFT = DFT } passed \n");
else
printf("{ FFT = DFT } failed \n");
}
return pass;
}
#ifndef TEST_SUITE
char* getCmdOption(char ** begin,
char ** end,
const std::string & option){
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end){
return *itr;
}
return 0;
}
int main(int argc, char ** argv){
int rank, np, n, pass;
int const in_num = argc;
char ** input_str = argv;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &np);
if (getCmdOption(input_str, input_str+in_num, "-n")){
n = atoi(getCmdOption(input_str, input_str+in_num, "-n"));
if (n < 0) n = 7;
} else n = 7;
{
World dw(argc, argv);
if (rank == 0){
printf("Running FFT on random dimension %d vector\n",n);
}
pass = fft(n, dw);
assert(pass);
}
MPI_Finalize();
return 0;
}
/**
* @}
* @}
*/
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/config.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef TORRENT_WINDOWS
// windows part
#include "libtorrent/utf8.hpp"
#include <windows.h>
#include <winioctl.h>
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// posix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
#ifdef TORRENT_WINDOWS
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
#ifdef TORRENT_WINDOWS
const file::open_mode file::in(GENERIC_READ);
const file::open_mode file::out(GENERIC_WRITE);
const file::seek_mode file::begin(FILE_BEGIN);
const file::seek_mode file::end(FILE_END);
#else
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(SEEK_SET);
const file::seek_mode file::end(SEEK_END);
#endif
file::file()
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{}
file::file(fs::path const& path, open_mode mode, error_code& ec)
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{
open(path, mode, ec);
}
file::~file()
{
close();
}
bool file::open(fs::path const& path, open_mode mode, error_code& ec)
{
close();
#ifdef TORRENT_WINDOWS
#ifdef UNICODE
std::wstring file_path(safe_convert(path.native_file_string()));
#else
std::string file_path = utf8_native(path.native_file_string());
#endif
m_file_handle = CreateFile(
file_path.c_str()
, mode.m_mask
, FILE_SHARE_READ
, 0
, (mode & out)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
if (m_file_handle == INVALID_HANDLE_VALUE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
// try to make the file sparse if supported
if (mode & out)
{
DWORD temp;
::DeviceIoControl(m_file_handle, FSCTL_SET_SPARSE, 0, 0
, 0, 0, &temp, 0);
}
#else
// rely on default umask to filter x and w permissions
// for group and others
int permissions = S_IRUSR | S_IWUSR
| S_IRGRP | S_IWGRP
| S_IROTH | S_IWOTH;
m_fd = ::open(path.native_file_string().c_str()
, map_open_mode(mode.m_mask), permissions);
if (m_fd == -1)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
#ifndef NDEBUG
m_open_mode = mode;
#endif
TORRENT_ASSERT(is_open());
return true;
}
bool file::is_open() const
{
#ifdef TORRENT_WINDOWS
return m_file_handle != INVALID_HANDLE_VALUE;
#else
return m_fd != -1;
#endif
}
void file::close()
{
#ifdef TORRENT_WINDOWS
if (m_file_handle == INVALID_HANDLE_VALUE) return;
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
#else
if (m_fd == -1) return;
::close(m_fd);
m_fd = -1;
#endif
#ifndef NDEBUG
m_open_mode = 0;
#endif
}
size_type file::read(char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & in) == in);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
TORRENT_ASSERT(DWORD(num_bytes) == num_bytes);
DWORD ret = 0;
if (num_bytes != 0)
{
if (ReadFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::read(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & out) == out);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
DWORD ret = 0;
if (num_bytes != 0)
{
if (WriteFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::write(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
bool file::set_size(size_type s, error_code& ec)
{
TORRENT_ASSERT(is_open());
TORRENT_ASSERT(s >= 0);
#ifdef TORRENT_WINDOWS
size_type pos = tell(ec);
if (ec) return false;
seek(s, begin, ec);
if (ec) return false;
if (::SetEndOfFile(m_file_handle) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
#else
if (ftruncate(m_fd, s) < 0)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
return true;
}
size_type file::seek(size_type offset, seek_mode m, error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = offset;
if (SetFilePointerEx(m_file_handle, offs, &offs, m.m_val) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret = lseek(m_fd, offset, m.m_val);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
size_type file::tell(error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (SetFilePointerEx(m_file_handle, offs, &offs
, FILE_CURRENT) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret;
ret = lseek(m_fd, 0, SEEK_CUR);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
}
<commit_msg>fixed typecast typo in file.cpp<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/config.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef TORRENT_WINDOWS
// windows part
#include "libtorrent/utf8.hpp"
#include <windows.h>
#include <winioctl.h>
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// posix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
#ifdef TORRENT_WINDOWS
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == std::size_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
#ifdef TORRENT_WINDOWS
const file::open_mode file::in(GENERIC_READ);
const file::open_mode file::out(GENERIC_WRITE);
const file::seek_mode file::begin(FILE_BEGIN);
const file::seek_mode file::end(FILE_END);
#else
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(SEEK_SET);
const file::seek_mode file::end(SEEK_END);
#endif
file::file()
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{}
file::file(fs::path const& path, open_mode mode, error_code& ec)
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{
open(path, mode, ec);
}
file::~file()
{
close();
}
bool file::open(fs::path const& path, open_mode mode, error_code& ec)
{
close();
#ifdef TORRENT_WINDOWS
#ifdef UNICODE
std::wstring file_path(safe_convert(path.native_file_string()));
#else
std::string file_path = utf8_native(path.native_file_string());
#endif
m_file_handle = CreateFile(
file_path.c_str()
, mode.m_mask
, FILE_SHARE_READ
, 0
, (mode & out)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
if (m_file_handle == INVALID_HANDLE_VALUE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
// try to make the file sparse if supported
if (mode & out)
{
DWORD temp;
::DeviceIoControl(m_file_handle, FSCTL_SET_SPARSE, 0, 0
, 0, 0, &temp, 0);
}
#else
// rely on default umask to filter x and w permissions
// for group and others
int permissions = S_IRUSR | S_IWUSR
| S_IRGRP | S_IWGRP
| S_IROTH | S_IWOTH;
m_fd = ::open(path.native_file_string().c_str()
, map_open_mode(mode.m_mask), permissions);
if (m_fd == -1)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
#ifndef NDEBUG
m_open_mode = mode;
#endif
TORRENT_ASSERT(is_open());
return true;
}
bool file::is_open() const
{
#ifdef TORRENT_WINDOWS
return m_file_handle != INVALID_HANDLE_VALUE;
#else
return m_fd != -1;
#endif
}
void file::close()
{
#ifdef TORRENT_WINDOWS
if (m_file_handle == INVALID_HANDLE_VALUE) return;
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
#else
if (m_fd == -1) return;
::close(m_fd);
m_fd = -1;
#endif
#ifndef NDEBUG
m_open_mode = 0;
#endif
}
size_type file::read(char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & in) == in);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
TORRENT_ASSERT(DWORD(num_bytes) == num_bytes);
DWORD ret = 0;
if (num_bytes != 0)
{
if (ReadFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::read(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & out) == out);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
DWORD ret = 0;
if (num_bytes != 0)
{
if (WriteFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::write(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
bool file::set_size(size_type s, error_code& ec)
{
TORRENT_ASSERT(is_open());
TORRENT_ASSERT(s >= 0);
#ifdef TORRENT_WINDOWS
size_type pos = tell(ec);
if (ec) return false;
seek(s, begin, ec);
if (ec) return false;
if (::SetEndOfFile(m_file_handle) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
#else
if (ftruncate(m_fd, s) < 0)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
return true;
}
size_type file::seek(size_type offset, seek_mode m, error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = offset;
if (SetFilePointerEx(m_file_handle, offs, &offs, m.m_val) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret = lseek(m_fd, offset, m.m_val);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
size_type file::tell(error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (SetFilePointerEx(m_file_handle, offs, &offs
, FILE_CURRENT) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret;
ret = lseek(m_fd, 0, SEEK_CUR);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/ork.hpp"
#define ORK_STL_INC_FILE <fstream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <iostream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <mutex>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <sstream>
#include"ork/core/stl_include.inl"
#include"ork/memory.hpp"
namespace ork {
const ork::string debug_trace(ORK("debug_trace"));
const ork::string output_data(ORK("output_data"));
const ork::string&to_string(const log_channel val) {
switch(val) {
case log_channel::debug_trace:
return debug_trace;
case log_channel::output_data:
return output_data;
};
ORK_UNREACHABLE
}
log_channel string2log_channel(const ork::string&str) {
if(str == output_data) {
return log_channel::output_data;
}
if(str == output_data) {
return log_channel::output_data;
}
ORK_THROW(ORK("Invalid log_channel: ") << str);
}
const ork::string trace(ORK("trace"));
const ork::string debug(ORK("debug"));
const ork::string info(ORK("info"));
const ork::string warning(ORK("warning"));
const ork::string error(ORK("error"));
const ork::string fatal(ORK("fatal"));
const ork::string&to_string(const severity_level val) {
switch(val) {
case severity_level::trace:
return trace;
case severity_level::debug:
return debug;
case severity_level::info:
return info;
case severity_level::warning:
return warning;
case severity_level::error:
return error;
case severity_level::fatal:
return fatal;
};
ORK_UNREACHABLE
}
severity_level string2severity_level(const ork::string&str) {
if(str == trace) {
return severity_level::trace;
}
if(str == debug) {
return severity_level::debug;
}
if(str == info) {
return severity_level::info;
}
if(str == warning) {
return severity_level::warning;
}
if(str == error) {
return severity_level::error;
}
if(str == fatal) {
return severity_level::fatal;
}
ORK_THROW(ORK("Invalid severity_level: ") << str);
}
//This is little more than a synchronous wrapper around an o_stream
class log_stream {
public:
using stream_ptr = std::shared_ptr<o_stream>;
private:
stream_ptr _stream;
std::mutex _mutex;
public:
explicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}
ORK_NON_COPYABLE(log_stream)
public:
void log(const string&message) {
std::lock_guard<std::mutex>lock(_mutex);
*_stream << message;
}
void flush() {
_stream->flush();
}
};
class log_sink {
public:
using stream_ptr = std::shared_ptr<log_stream>;
private:
std::vector<stream_ptr>_streams = {};
bool _auto_flush = true;
public:
log_sink() {}
log_sink(const bool auto_flush) : _auto_flush{auto_flush} {}
public:
void insert(const stream_ptr&ptr) {
_streams.push_back(ptr);
}
void log(const string&message) {
for(auto&stream : _streams) {
stream->log(message);
if(_auto_flush) {
stream->flush();
}
}
}
void set_auto_flush(const bool auto_flush) {
_auto_flush = auto_flush;
}
void flush() {
for(auto&stream : _streams) {
stream->flush();
}
}
};
std::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {
if(!file::ensure_directory(file_name)) {
ORK_THROW(ORK("Could not create directory : ") << file_name.ORK_GEN_STR())
}
of_stream* p_stream = new of_stream();
p_stream->open(file_name);//std::ios::app | std::ios::ate
if(p_stream->fail()) {
ORK_THROW(ORK("Error opening log : ") << file_name)
}
//p_stream->rdbuf()->pubsetbuf(0, 0);//Less performance, more likely to catch error messages
return std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));
}
//This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place
class log_multiplexer {
private:
std::array<log_sink, severity_levels.size()>_severity_sinks = {};
log_sink _data_sink = {};
public:
log_multiplexer(const file::path&root_directory){
auto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};
auto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};
auto flog = open_file_log_stream(root_directory / ORK("trace.log"));
auto fdata = open_file_log_stream(root_directory / ORK("output.log"));
for(const auto sv : severity_levels) {
auto sink = _severity_sinks[static_cast<size_t>(sv)];
if(sv < severity_level::error) {
sink.insert(lout);
sink.set_auto_flush(true);
}
else {
sink.insert(lerr);
}
sink.insert(flog);
}
_data_sink.insert(lout);
_data_sink.insert(fdata);
}
public:
void log(const log_channel channel, const severity_level severity, const o_string_stream&stream) {
const string message = stream.str();
switch(channel) {
case log_channel::debug_trace:
log_severity(severity, message);
break;
case log_channel::output_data:
_data_sink.log(stream.str());
break;
default:
ORK_UNREACHABLE
};
}
void flush_all() {
for(auto&sink : _severity_sinks) {
sink.flush();
}
_data_sink.flush();
}
private:
void log_severity(const severity_level severity, const string&message) {
const bool do_it = ORK_DEBUG || severity > severity_level::debug;
if(do_it) {//To avoid constant conditional expression
_severity_sinks[static_cast<size_t>(severity)].log(message);
}
}
};
struct log_scope::impl {
public:
std::shared_ptr<log_multiplexer>multiplexer;
log_channel channel;
severity_level severity;
o_string_stream stream;
public:
impl(std::shared_ptr<log_multiplexer>&mp, const log_channel lc, const severity_level sv)
: multiplexer{mp}
, channel{lc}
, severity{sv}
, stream{}
{}
~impl() {
multiplexer->log(channel, severity, stream);
}
ORK_MOVE_ONLY(impl)
};
log_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}
log_scope::~log_scope() {}
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << val;\
return *this;\
}
LOG_STREAM_OPERATOR(bool)
LOG_STREAM_OPERATOR(short)
LOG_STREAM_OPERATOR(unsigned short)
LOG_STREAM_OPERATOR(int)
LOG_STREAM_OPERATOR(unsigned)
LOG_STREAM_OPERATOR(long)
LOG_STREAM_OPERATOR(unsigned long)
LOG_STREAM_OPERATOR(long long)
LOG_STREAM_OPERATOR(unsigned long long)
LOG_STREAM_OPERATOR(float)
LOG_STREAM_OPERATOR(double)
LOG_STREAM_OPERATOR(long double)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_BYTE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(char)
LOG_STREAM_OPERATOR(char*)
LOG_STREAM_OPERATOR(bstring&)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_WIDE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(wchar_t)
LOG_STREAM_OPERATOR(wchar_t*)
LOG_STREAM_OPERATOR(wstring&)
log_scope& log_scope::operator<< (const void* val) {
_pimpl->stream << val;
return *this;
}
log_scope& log_scope::operator<< (const std::streambuf* sb) {
_pimpl->stream << sb;
return *this;
}
log_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {
_pimpl->stream << pf;
return *this;
}
const string&to_formatted_string(const severity_level sv) {
static const std::array<const string, severity_levels.size()>strings = {{
ORK("TRACE")
, ORK("DEBUG")
, ORK("INFO ")
, ORK("WARN ")
, ORK("ERROR")
, ORK("FATAL")
}};
return strings[static_cast<size_t>(sv)];
}
struct logger::impl {
public:
file::path root_directory;
std::shared_ptr<log_multiplexer>multiplexer;
public:
impl(const file::path&directory)
: root_directory(directory)
, multiplexer{new log_multiplexer(directory)}
{}
void flush_all() {
multiplexer->flush_all();
}
};
logger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}
logger::~logger() {}
const file::path& logger::root_directory() {
return _pimpl->root_directory;
}
log_scope logger::get_log_scope(
const string&file_
, const string&line_
, const string&function_
, const log_channel channel
, const severity_level severity)
{
const file::path fullpath(file_);
string file(fullpath.filename().ORK_GEN_STR());
file.resize(28, ORK(' '));
string line(line_);
line.resize(4, ORK(' '));
string function(function_);
function.resize(40, ORK(' '));
std::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(_pimpl->multiplexer, channel, severity));
log_scope scope(std::move(ls_impl));
//Output formatted context first
scope << ORK("[") << to_formatted_string(severity) << ORK("]:") << file << ORK("(") << line << ORK("):") << function << ORK("-- ");
//Finally, return the stream to the client
return std::move(scope);
}
void logger::flush_all() {
_pimpl->flush_all();
}
logger*_g_log = nullptr;
int make_global_log(const string&directory) {
static logger log(directory);
_g_log = &log;
return 0;
}
logger& get_global_log() {
return *_g_log;
}
}//namespace ork
<commit_msg>Disabled log filtering<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/ork.hpp"
#define ORK_STL_INC_FILE <fstream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <iostream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <mutex>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <sstream>
#include"ork/core/stl_include.inl"
#include"ork/memory.hpp"
namespace ork {
const ork::string debug_trace(ORK("debug_trace"));
const ork::string output_data(ORK("output_data"));
const ork::string&to_string(const log_channel val) {
switch(val) {
case log_channel::debug_trace:
return debug_trace;
case log_channel::output_data:
return output_data;
};
ORK_UNREACHABLE
}
log_channel string2log_channel(const ork::string&str) {
if(str == output_data) {
return log_channel::output_data;
}
if(str == output_data) {
return log_channel::output_data;
}
ORK_THROW(ORK("Invalid log_channel: ") << str);
}
const ork::string trace(ORK("trace"));
const ork::string debug(ORK("debug"));
const ork::string info(ORK("info"));
const ork::string warning(ORK("warning"));
const ork::string error(ORK("error"));
const ork::string fatal(ORK("fatal"));
const ork::string&to_string(const severity_level val) {
switch(val) {
case severity_level::trace:
return trace;
case severity_level::debug:
return debug;
case severity_level::info:
return info;
case severity_level::warning:
return warning;
case severity_level::error:
return error;
case severity_level::fatal:
return fatal;
};
ORK_UNREACHABLE
}
severity_level string2severity_level(const ork::string&str) {
if(str == trace) {
return severity_level::trace;
}
if(str == debug) {
return severity_level::debug;
}
if(str == info) {
return severity_level::info;
}
if(str == warning) {
return severity_level::warning;
}
if(str == error) {
return severity_level::error;
}
if(str == fatal) {
return severity_level::fatal;
}
ORK_THROW(ORK("Invalid severity_level: ") << str);
}
//This is little more than a synchronous wrapper around an o_stream
class log_stream {
public:
using stream_ptr = std::shared_ptr<o_stream>;
private:
stream_ptr _stream;
std::mutex _mutex;
public:
explicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}
ORK_NON_COPYABLE(log_stream)
public:
void log(const string&message) {
std::lock_guard<std::mutex>lock(_mutex);
*_stream << message;
}
void flush() {
_stream->flush();
}
};
class log_sink {
public:
using stream_ptr = std::shared_ptr<log_stream>;
private:
std::vector<stream_ptr>_streams = {};
bool _auto_flush = true;
public:
log_sink() {}
log_sink(const bool auto_flush) : _auto_flush{auto_flush} {}
public:
void insert(const stream_ptr&ptr) {
_streams.push_back(ptr);
}
void log(const string&message) {
for(auto&stream : _streams) {
stream->log(message);
if(_auto_flush) {
stream->flush();
}
}
}
void set_auto_flush(const bool auto_flush) {
_auto_flush = auto_flush;
}
void flush() {
for(auto&stream : _streams) {
stream->flush();
}
}
};
std::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {
if(!file::ensure_directory(file_name)) {
ORK_THROW(ORK("Could not create directory : ") << file_name.ORK_GEN_STR())
}
of_stream* p_stream = new of_stream();
p_stream->open(file_name);//std::ios::app | std::ios::ate
if(p_stream->fail()) {
ORK_THROW(ORK("Error opening log : ") << file_name)
}
//p_stream->rdbuf()->pubsetbuf(0, 0);//Less performance, more likely to catch error messages
return std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));
}
//This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place
class log_multiplexer {
private:
std::array<log_sink, severity_levels.size()>_severity_sinks = {};
log_sink _data_sink = {};
public:
log_multiplexer(const file::path&root_directory){
auto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};
auto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};
auto flog = open_file_log_stream(root_directory / ORK("trace.log"));
auto fdata = open_file_log_stream(root_directory / ORK("output.log"));
for(const auto sv : severity_levels) {
auto sink = _severity_sinks[static_cast<size_t>(sv)];
if(sv < severity_level::error) {
sink.insert(lout);
sink.set_auto_flush(true);
}
else {
sink.insert(lerr);
}
sink.insert(flog);
}
_data_sink.insert(lout);
_data_sink.insert(fdata);
}
public:
void log(const log_channel channel, const severity_level severity, const o_string_stream&stream) {
const string message = stream.str();
switch(channel) {
case log_channel::debug_trace:
log_severity(severity, message);
break;
case log_channel::output_data:
_data_sink.log(stream.str());
break;
default:
ORK_UNREACHABLE
};
}
void flush_all() {
for(auto&sink : _severity_sinks) {
sink.flush();
}
_data_sink.flush();
}
private:
void log_severity(const severity_level severity, const string&message) {
const bool do_it = ORK_DEBUG || severity > severity_level::debug;
if(do_it || true) {//To avoid constant conditional expression
_severity_sinks[static_cast<size_t>(severity)].log(message);
}
}
};
struct log_scope::impl {
public:
std::shared_ptr<log_multiplexer>multiplexer;
log_channel channel;
severity_level severity;
o_string_stream stream;
public:
impl(std::shared_ptr<log_multiplexer>&mp, const log_channel lc, const severity_level sv)
: multiplexer{mp}
, channel{lc}
, severity{sv}
, stream{}
{}
~impl() {
multiplexer->log(channel, severity, stream);
}
ORK_MOVE_ONLY(impl)
};
log_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}
log_scope::~log_scope() {}
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << val;\
return *this;\
}
LOG_STREAM_OPERATOR(bool)
LOG_STREAM_OPERATOR(short)
LOG_STREAM_OPERATOR(unsigned short)
LOG_STREAM_OPERATOR(int)
LOG_STREAM_OPERATOR(unsigned)
LOG_STREAM_OPERATOR(long)
LOG_STREAM_OPERATOR(unsigned long)
LOG_STREAM_OPERATOR(long long)
LOG_STREAM_OPERATOR(unsigned long long)
LOG_STREAM_OPERATOR(float)
LOG_STREAM_OPERATOR(double)
LOG_STREAM_OPERATOR(long double)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_BYTE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(char)
LOG_STREAM_OPERATOR(char*)
LOG_STREAM_OPERATOR(bstring&)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_WIDE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(wchar_t)
LOG_STREAM_OPERATOR(wchar_t*)
LOG_STREAM_OPERATOR(wstring&)
log_scope& log_scope::operator<< (const void* val) {
_pimpl->stream << val;
return *this;
}
log_scope& log_scope::operator<< (const std::streambuf* sb) {
_pimpl->stream << sb;
return *this;
}
log_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {
_pimpl->stream << pf;
return *this;
}
const string&to_formatted_string(const severity_level sv) {
static const std::array<const string, severity_levels.size()>strings = {{
ORK("TRACE")
, ORK("DEBUG")
, ORK("INFO ")
, ORK("WARN ")
, ORK("ERROR")
, ORK("FATAL")
}};
return strings[static_cast<size_t>(sv)];
}
struct logger::impl {
public:
file::path root_directory;
std::shared_ptr<log_multiplexer>multiplexer;
public:
impl(const file::path&directory)
: root_directory(directory)
, multiplexer{new log_multiplexer(directory)}
{}
void flush_all() {
multiplexer->flush_all();
}
};
logger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}
logger::~logger() {}
const file::path& logger::root_directory() {
return _pimpl->root_directory;
}
log_scope logger::get_log_scope(
const string&file_
, const string&line_
, const string&function_
, const log_channel channel
, const severity_level severity)
{
const file::path fullpath(file_);
string file(fullpath.filename().ORK_GEN_STR());
file.resize(28, ORK(' '));
string line(line_);
line.resize(4, ORK(' '));
string function(function_);
function.resize(40, ORK(' '));
std::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(_pimpl->multiplexer, channel, severity));
log_scope scope(std::move(ls_impl));
//Output formatted context first
scope << ORK("[") << to_formatted_string(severity) << ORK("]:") << file << ORK("(") << line << ORK("):") << function << ORK("-- ");
//Finally, return the stream to the client
return std::move(scope);
}
void logger::flush_all() {
_pimpl->flush_all();
}
logger*_g_log = nullptr;
int make_global_log(const string&directory) {
static logger log(directory);
_g_log = &log;
return 0;
}
logger& get_global_log() {
return *_g_log;
}
}//namespace ork
<|endoftext|>
|
<commit_before>/*
* opencog/ubigraph/UbigraphModule.cc
*
* Copyright (C) 2009 by Singularity Institute for Artificial Intelligence
* All Rights Reserved
*
* Written by Jared Wigmore <jared.wigmore@gmail.com>
* Adapted from DottyModule (which is by Trent Waddington <trent.waddington@gmail.com>)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <queue>
#include <sstream>
#include <string>
#include <tr1/functional>
using namespace std::tr1::placeholders;
#include "UbigraphModule.h"
#include <opencog/util/Logger.h>
#include <opencog/atomspace/utils.h>
#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atomspace/Link.h>
#include <opencog/atomspace/Node.h>
#include <opencog/atomspace/TLB.h>
#include <opencog/server/CogServer.h>
extern "C" {
#include <UbigraphAPI.h>
}
using namespace opencog;
DECLARE_MODULE(UbigraphModule);
std::string initials(std::string s)
{
std::string ret;
foreach (char c, s) {
if (/*isUpperCase(c)*/ Isox(c) == c) {
ret += c;
}
}
return ret;
}
class Ubigrapher
{
public:
Ubigrapher(AtomSpace *space) : space(space), withIncoming(false), compact(true)
{
compactLabels = true;
space->addAtomSignal().connect(std::tr1::bind(&Ubigrapher::add_vertex, this, _1));
space->addAtomSignal().connect(std::tr1::bind(&Ubigrapher::add_edges, this, _1));
space->removeAtomSignal().connect(std::tr1::bind(&Ubigrapher::remove_vertex, this, _1));
space->removeAtomSignal().connect(std::tr1::bind(&Ubigrapher::remove_edges, this, _1));
ubigraph_clear();
}
AtomSpace *space;
bool withIncoming;
bool compact;
//! Makes much more compact labels. Currently uses the initials of the typename.
bool compactLabels;
/**
* Outputs a ubigraph node for an atom.
*/
bool add_vertex(Handle h)
{
Atom *a = TLB::getAtom(h);
if (compact)
{
// don't make nodes for binary links with no incoming
Link *l = dynamic_cast<Link*>(a);
if (l && l->getOutgoingSet().size() == 2 &&
l->getIncomingSet() == NULL)
return false;
}
// std::ostringstream ost;
// ost << h.value() << " [";
int id = (int)h.value();
int status = ubigraph_new_vertex_w_id(id);
if (space->isNode(a->getType()))
ubigraph_set_vertex_attribute(id, "shape", "sphere");
else {
// ost << "shape=\"diamond\" ";
ubigraph_set_vertex_attribute(id, "shape", "octahedron");
ubigraph_set_vertex_attribute(id, "color", "#ff0000");
}
std::ostringstream ost;
// ost << "label=\"[" << ClassServer::getTypeName(a->getType()) << "]";
std::string type = ClassServer::getTypeName(a->getType());
if (compactLabels) {
ost << initials(type);
} else {
ost << type;
}
if (space->isNode(a->getType())) {
Node *n = (Node*)a;
ost << " " << n->getName();
} else {
Link *l = (Link*)a;
l = l; // TODO: anything to output for links?
}
ubigraph_set_vertex_attribute(id, "label", ost.str().c_str());
// ost << "\"];\n";
// answer += ost.str();*/
return false;
}
/**
* Outputs ubigraph links for an atom's outgoing connections.
*/
bool add_edges(Handle h)
{
Atom *a = TLB::getAtom(h);
// std::ostringstream ost;
const Link *l = dynamic_cast<const Link *>(a);
if (l)
{
const std::vector<Handle> &out = l->getOutgoingSet();
// int id = ;// make IDs based on the type and outgoing set, in case
// // it's later necessary to change this edge
// int status = ubigraph_new_edge_w_id(id,x,y);
if (compact && out.size() == 2 && l->getIncomingSet() == NULL)
{
// ost << out[0] << " -> " << out[1] << " [label=\""
// << ClassServer::getTypeName(a->getType()) << "\"];\n";
// answer += ost.str();
int id = h.value();
int status = ubigraph_new_edge_w_id(id, out[0].value(),out[1].value());
std::string type = ClassServer::getTypeName(a->getType());
std::ostringstream ost;
if (compactLabels) {
ost << initials(type);
} else {
ost << type;
}
ubigraph_set_edge_attribute(id, "label", ost.str().c_str());
ubigraph_set_edge_attribute(id, "arrow", "true");
// Makes it easier to see the direction of the arrows (cones),
// but hides the type labels
// ubigraph_set_edge_attribute(id, "arrow_radius", "1.5");
ubigraph_set_edge_attribute(id, "arrow_length", "2.0");
return false;
}
for (size_t i = 0; i < out.size(); i++) {
int id = ubigraph_new_edge(h.value(),out[i].value());
ubigraph_set_edge_attribute(id, "label", toString(i).c_str());
ubigraph_set_edge_attribute(id, "arrow", "true");
// Makes it easier to see the direction of the arrows (cones),
// but hides the number labels
// ubigraph_set_edge_attribute(id, "arrow_radius", "1.5");
ubigraph_set_edge_attribute(id, "arrow_length", "2.0");
// ost << h << "->" << out[i] << " [label=\"" << i << "\"];\n";
}
}
/* if (withIncoming) {
HandleEntry *he = a->getIncomingSet();
int i = 0;
while (he) {
// ost << h << "->" << he->handle << " [style=\"dotted\" label=\"" << i << "\"];\n";
he = he->next;
i++;
}
}*/
// answer += ost.str();
return false;
}
/**
* Removes the ubigraph node for an atom.
*/
bool remove_vertex(Handle h)
{
Atom *a = TLB::getAtom(h);
if (compact)
{
// Won't have made a node for a binary link with no incoming
Link *l = dynamic_cast<Link*>(a);
if (l && l->getOutgoingSet().size() == 2 &&
l->getIncomingSet() == NULL)
return false;
}
int id = (int)h.value();
int status = ubigraph_remove_vertex(id);
return false;
}
bool remove_edges(Handle h)
{
Atom *a = TLB::getAtom(h);
// This method is only relevant to binary Links with no incoming.
// Any other atoms will be represented by vertexes, and the edges
// to them will be automatically deleted by ubigraph when the
// vertexes are deleted.
if (compact)
{
// Won't have made a node for a binary link with no incoming
Link *l = dynamic_cast<Link*>(a);
if (l && l->getOutgoingSet().size() == 2 &&
l->getIncomingSet() == NULL)
{
int id = h.value();
int status = ubigraph_remove_edge(id);
}
}
return false;
}
void graph()
{
space->foreach_handle_of_type((Type)ATOM, &Ubigrapher::add_vertex, this, true);
space->foreach_handle_of_type((Type)ATOM, &Ubigrapher::add_edges, this, true);
}
};
UbigraphModule::UbigraphModule() : Module()
{
logger().info("[UbigraphModule] constructor");
do_ubigraph_register();
}
UbigraphModule::~UbigraphModule()
{
logger().info("[UbigraphModule] destructor");
do_ubigraph_unregister();
}
void UbigraphModule::init()
{
logger().info("[UbigraphModule] init");
}
std::string UbigraphModule::do_ubigraph(Request *dummy, std::list<std::string> args)
{
AtomSpace *space = CogServer::getAtomSpace();
Ubigrapher g(space);
while (!args.empty()) {
if (args.front() == "with-incoming")
g.withIncoming = true;
if (args.front() == "--compact")
g.compact = true;
args.pop_front();
}
g.graph();
return "";
}
<commit_msg>Misc ubigraphclient cleanup<commit_after>/*
* opencog/ubigraph/UbigraphModule.cc
*
* Copyright (C) 2009 by Singularity Institute for Artificial Intelligence
* All Rights Reserved
*
* Written by Jared Wigmore <jared.wigmore@gmail.com>
* Adapted from DottyModule (which is by Trent Waddington <trent.waddington@gmail.com>)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <queue>
#include <sstream>
#include <string>
#include <tr1/functional>
using namespace std::tr1::placeholders;
#include "UbigraphModule.h"
#include <opencog/util/Logger.h>
#include <opencog/atomspace/utils.h>
#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atomspace/Link.h>
#include <opencog/atomspace/Node.h>
#include <opencog/atomspace/TLB.h>
#include <opencog/server/CogServer.h>
extern "C" {
#include <UbigraphAPI.h>
}
using namespace opencog;
DECLARE_MODULE(UbigraphModule);
std::string initials(std::string s)
{
std::string ret;
foreach (char c, s) {
if (/*isUpperCase(c)*/ Isox(c) == c) {
ret += c;
}
}
return ret;
}
class Ubigrapher
{
public:
Ubigrapher(AtomSpace *space) : space(space), withIncoming(false), compact(false)
{
compactLabels = true;
space->addAtomSignal().connect(std::tr1::bind(&Ubigrapher::add_vertex, this, _1));
space->addAtomSignal().connect(std::tr1::bind(&Ubigrapher::add_edges, this, _1));
space->removeAtomSignal().connect(std::tr1::bind(&Ubigrapher::remove_vertex, this, _1));
space->removeAtomSignal().connect(std::tr1::bind(&Ubigrapher::remove_edges, this, _1));
ubigraph_clear();
// Set the styles for various types of edges and vertexes in the graph
nodeStyle = ubigraph_new_vertex_style(0);
ubigraph_set_vertex_style_attribute(nodeStyle, "shape", "sphere");
linkStyle = ubigraph_new_vertex_style(0);
ubigraph_set_vertex_style_attribute(linkStyle, "shape", "octahedron");
ubigraph_set_vertex_style_attribute(linkStyle, "color", "#ff0000");
outgoingStyle = ubigraph_new_edge_style(0);
ubigraph_set_edge_style_attribute(outgoingStyle, "arrow", "true");
// Makes it easier to see the direction of the arrows (cones),
// but hides the number/type labels
// ubigraph_set_edge_style_attribute(outgoingStyle, "arrow_radius", "1.5");
ubigraph_set_edge_style_attribute(outgoingStyle, "arrow_length", "2.0");
compactLinkStyle = ubigraph_new_edge_style(outgoingStyle);
}
AtomSpace *space;
bool withIncoming;
bool compact;
//! Makes much more compact labels. Currently uses the initials of the typename.
bool compactLabels;
//! Styles corresponding to different types of Atom,
//! except outgoingStyle which is for the edges that collectively represent outgoing sets
int nodeStyle, linkStyle, compactLinkStyle, outgoingStyle;
/**
* Outputs a ubigraph node for an atom.
*/
bool add_vertex(Handle h)
{
Atom *a = TLB::getAtom(h);
if (compact)
{
// don't make nodes for binary links with no incoming
Link *l = dynamic_cast<Link*>(a);
if (l && l->getOutgoingSet().size() == 2 &&
l->getIncomingSet() == NULL)
return false;
}
int id = (int)h.value();
int status = ubigraph_new_vertex_w_id(id);
if (space->isNode(a->getType()))
ubigraph_change_vertex_style(id, nodeStyle);
else {
ubigraph_change_vertex_style(id, linkStyle);
}
std::ostringstream ost;
std::string type = ClassServer::getTypeName(a->getType());
if (compactLabels) {
ost << initials(type);
} else {
ost << type;
}
if (space->isNode(a->getType())) {
Node *n = (Node*)a;
ost << " " << n->getName();
} else {
Link *l = (Link*)a;
l = l; // TODO: anything to output for links?
}
ubigraph_set_vertex_attribute(id, "label", ost.str().c_str());
return false;
}
/**
* Outputs ubigraph links for an atom's outgoing connections.
*/
bool add_edges(Handle h)
{
Atom *a = TLB::getAtom(h);
const Link *l = dynamic_cast<const Link *>(a);
if (l)
{
const std::vector<Handle> &out = l->getOutgoingSet();
// int id = ;// make IDs based on the type and outgoing set, in case
// // it's later necessary to change this edge
// int status = ubigraph_new_edge_w_id(id,x,y);
if (compact && out.size() == 2 && l->getIncomingSet() == NULL)
{
int id = h.value();
int status = ubigraph_new_edge_w_id(id, out[0].value(),out[1].value());
std::string type = ClassServer::getTypeName(a->getType());
std::ostringstream ost;
if (compactLabels) {
ost << initials(type);
} else {
ost << type;
}
ubigraph_change_edge_style(id, compactLinkStyle);
ubigraph_set_edge_attribute(id, "label", ost.str().c_str());
return false;
}
for (size_t i = 0; i < out.size(); i++) {
int id = ubigraph_new_edge(h.value(),out[i].value());
ubigraph_change_edge_style(id, outgoingStyle);
ubigraph_set_edge_attribute(id, "label", toString(i).c_str());
}
}
/* if (withIncoming) {
HandleEntry *he = a->getIncomingSet();
int i = 0;
while (he) {
// ost << h << "->" << he->handle << " [style=\"dotted\" label=\"" << i << "\"];\n";
he = he->next;
i++;
}
}*/
return false;
}
/**
* Removes the ubigraph node for an atom.
*/
bool remove_vertex(Handle h)
{
Atom *a = TLB::getAtom(h);
if (compact)
{
// Won't have made a node for a binary link with no incoming
Link *l = dynamic_cast<Link*>(a);
if (l && l->getOutgoingSet().size() == 2 &&
l->getIncomingSet() == NULL)
return false;
}
int id = (int)h.value();
int status = ubigraph_remove_vertex(id);
return false;
}
bool remove_edges(Handle h)
{
Atom *a = TLB::getAtom(h);
// This method is only relevant to binary Links with no incoming.
// Any other atoms will be represented by vertexes, and the edges
// to them will be automatically deleted by ubigraph when the
// vertexes are deleted.
if (compact)
{
// Won't have made a node for a binary link with no incoming
Link *l = dynamic_cast<Link*>(a);
if (l && l->getOutgoingSet().size() == 2 &&
l->getIncomingSet() == NULL)
{
int id = h.value();
int status = ubigraph_remove_edge(id);
}
}
return false;
}
void graph()
{
space->foreach_handle_of_type((Type)ATOM, &Ubigrapher::add_vertex, this, true);
space->foreach_handle_of_type((Type)ATOM, &Ubigrapher::add_edges, this, true);
}
};
UbigraphModule::UbigraphModule() : Module()
{
logger().info("[UbigraphModule] constructor");
do_ubigraph_register();
}
UbigraphModule::~UbigraphModule()
{
logger().info("[UbigraphModule] destructor");
do_ubigraph_unregister();
}
void UbigraphModule::init()
{
logger().info("[UbigraphModule] init");
}
std::string UbigraphModule::do_ubigraph(Request *dummy, std::list<std::string> args)
{
AtomSpace *space = CogServer::getAtomSpace();
Ubigrapher g(space);
while (!args.empty()) {
if (args.front() == "with-incoming")
g.withIncoming = true;
if (args.front() == "--compact")
g.compact = true;
args.pop_front();
}
g.graph();
return "";
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: polyscan.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-07-24 10:01:11 $
*
* 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 _SV_POLYSCAN_HXX
#define _SV_POLYSCAN_HXX
#ifndef _GEN_HXX
#include <tools/gen.hxx>
#endif
// -----------------
// - ScanlinePoint -
// -----------------
struct ScanlinePoint
{
long mnX;
ScanlinePoint* mpNext;
ScanlinePoint() : mnX( 0L ), mpNext( NULL ) {};
ScanlinePoint( long nX, ScanlinePoint* pNext ) : mnX( nX ), mpNext( pNext ) {};
~ScanlinePoint() {};
void Set( long nX, ScanlinePoint* pNext ) { mnX = nX, mpNext = pNext; }
};
// -------------------
// - PolyScanSegment -
// -------------------
struct PolyScanSegment
{
long mnStart;
long mnEnd;
PolyScanSegment() : mnStart( 0L ), mnEnd( 0L ) {};
PolyScanSegment( long nStart, long nEnd ) : mnStart( nStart ), mnEnd( nEnd ) {};
~PolyScanSegment() {};
};
// ----------------
// - PolyScanline -
// ----------------
struct ScanlinePoint;
class Polygon;
class PolyPolygon;
class PolyScanline
{
private:
ScanlinePoint* mpFirst;
ScanlinePoint* mpLast;
ScanlinePoint* mpAct;
long mnLeft;
long mnRight;
void ImplDelete();
public:
PolyScanline();
~PolyScanline();
void Insert( long nX );
void Set( long nStart, long nEnd );
void Set( const PolyScanSegment& rSegment ) { Set( rSegment.mnStart, rSegment.mnEnd ); }
inline BOOL GetFirstX( long& rX );
inline BOOL GetNextX( long& rX );
BOOL GetFirstSegment( PolyScanSegment& rSegment );
BOOL GetNextSegment( PolyScanSegment& rSegment );
};
// ------------------------------------------------------------------------
inline BOOL PolyScanline::GetFirstX( long& rX )
{
mpAct = mpFirst;
return( mpAct ? ( rX = mpAct->mnX, mpAct = mpAct->mpNext, TRUE ) : FALSE );
}
// ------------------------------------------------------------------------
inline BOOL PolyScanline::GetNextX( long& rX )
{
return( mpAct ? ( rX = mpAct->mnX, mpAct = mpAct->mpNext, TRUE ) : FALSE );
}
// ---------------
// - PolyScanner -
// ---------------
class PolyScanner
{
private:
PolyScanline* mpArray;
long mnLeft;
long mnTop;
long mnRight;
long mnBottom;
PolyScanner() {};
protected:
void InsertLine( const Point& rStart, const Point& rEnd );
public:
PolyScanner( const Rectangle& rRect );
PolyScanner( const Polygon& rPoly );
PolyScanner( const PolyPolygon& rPolyPoly );
~PolyScanner();
long Left() const { return mnLeft; }
long Top() const { return mnTop; }
long Right() const { return mnRight; }
long Bottom() const { return mnBottom; }
long Width() const { return( mnRight - mnLeft + 1L ); }
long Height() const { return( mnBottom - mnTop + 1L ); }
Rectangle GetBoundRect() const { return Rectangle( mnLeft, mnTop, mnRight, mnBottom ); }
ULONG Count() const { return Height(); }
PolyScanline* operator[]( ULONG nPos ) const;
};
#endif // _SV_POLYSCAN_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.224); FILE MERGED 2008/04/01 16:05:20 thb 1.2.224.2: #i85898# Stripping all external header guards 2008/03/28 15:44:15 rt 1.2.224.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: polyscan.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.
*
************************************************************************/
#ifndef _SV_POLYSCAN_HXX
#define _SV_POLYSCAN_HXX
#include <tools/gen.hxx>
// -----------------
// - ScanlinePoint -
// -----------------
struct ScanlinePoint
{
long mnX;
ScanlinePoint* mpNext;
ScanlinePoint() : mnX( 0L ), mpNext( NULL ) {};
ScanlinePoint( long nX, ScanlinePoint* pNext ) : mnX( nX ), mpNext( pNext ) {};
~ScanlinePoint() {};
void Set( long nX, ScanlinePoint* pNext ) { mnX = nX, mpNext = pNext; }
};
// -------------------
// - PolyScanSegment -
// -------------------
struct PolyScanSegment
{
long mnStart;
long mnEnd;
PolyScanSegment() : mnStart( 0L ), mnEnd( 0L ) {};
PolyScanSegment( long nStart, long nEnd ) : mnStart( nStart ), mnEnd( nEnd ) {};
~PolyScanSegment() {};
};
// ----------------
// - PolyScanline -
// ----------------
struct ScanlinePoint;
class Polygon;
class PolyPolygon;
class PolyScanline
{
private:
ScanlinePoint* mpFirst;
ScanlinePoint* mpLast;
ScanlinePoint* mpAct;
long mnLeft;
long mnRight;
void ImplDelete();
public:
PolyScanline();
~PolyScanline();
void Insert( long nX );
void Set( long nStart, long nEnd );
void Set( const PolyScanSegment& rSegment ) { Set( rSegment.mnStart, rSegment.mnEnd ); }
inline BOOL GetFirstX( long& rX );
inline BOOL GetNextX( long& rX );
BOOL GetFirstSegment( PolyScanSegment& rSegment );
BOOL GetNextSegment( PolyScanSegment& rSegment );
};
// ------------------------------------------------------------------------
inline BOOL PolyScanline::GetFirstX( long& rX )
{
mpAct = mpFirst;
return( mpAct ? ( rX = mpAct->mnX, mpAct = mpAct->mpNext, TRUE ) : FALSE );
}
// ------------------------------------------------------------------------
inline BOOL PolyScanline::GetNextX( long& rX )
{
return( mpAct ? ( rX = mpAct->mnX, mpAct = mpAct->mpNext, TRUE ) : FALSE );
}
// ---------------
// - PolyScanner -
// ---------------
class PolyScanner
{
private:
PolyScanline* mpArray;
long mnLeft;
long mnTop;
long mnRight;
long mnBottom;
PolyScanner() {};
protected:
void InsertLine( const Point& rStart, const Point& rEnd );
public:
PolyScanner( const Rectangle& rRect );
PolyScanner( const Polygon& rPoly );
PolyScanner( const PolyPolygon& rPolyPoly );
~PolyScanner();
long Left() const { return mnLeft; }
long Top() const { return mnTop; }
long Right() const { return mnRight; }
long Bottom() const { return mnBottom; }
long Width() const { return( mnRight - mnLeft + 1L ); }
long Height() const { return( mnBottom - mnTop + 1L ); }
Rectangle GetBoundRect() const { return Rectangle( mnLeft, mnTop, mnRight, mnBottom ); }
ULONG Count() const { return Height(); }
PolyScanline* operator[]( ULONG nPos ) const;
};
#endif // _SV_POLYSCAN_HXX
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/thread/mutex.hpp>
#include <cstdlib>
#include <boost/config.hpp>
using boost::bind;
using namespace libtorrent;
namespace libtorrent
{
// defined in broadcast_socket.cpp
address guess_local_address(asio::io_service&);
}
lsd::lsd(io_service& ios, address const& listen_interface
, peer_callback_t const& cb)
: m_callback(cb)
, m_retry_count(0)
, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143"), 6771)
, bind(&lsd::on_announce, self(), _1, _2, _3))
, m_broadcast_timer(ios)
, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}
lsd::~lsd() {}
void lsd::announce(sha1_hash const& ih, int listen_port)
{
if (m_disabled) return;
std::stringstream btsearch;
btsearch << "BT-SEARCH * HTTP/1.1\r\n"
"Host: 239.192.152.143:6771\r\n"
"Port: " << listen_port << "\r\n"
"Infohash: " << ih << "\r\n"
"\r\n\r\n";
std::string const& msg = btsearch.str();
m_retry_count = 0;
asio::error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
if (ec)
{
m_disabled = true;
return;
}
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " ==> announce: ih: " << ih << " port: " << listen_port << std::endl;
#endif
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
void lsd::resend_announce(asio::error_code const& e, std::string msg) try
{
if (e) return;
asio::error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
++m_retry_count;
if (m_retry_count >= 5)
return;
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
catch (std::exception&)
{}
void lsd::on_announce(udp::endpoint const& from, char* buffer
, std::size_t bytes_transferred)
{
using namespace libtorrent::detail;
http_parser p;
p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred));
if (!p.header_finished())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: incomplete HTTP message\n";
#endif
return;
}
if (p.method() != "bt-search")
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
return;
}
std::string const& port_str = p.header("port");
if (port_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
return;
}
std::string const& ih_str = p.header("infohash");
if (ih_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
return;
}
sha1_hash ih(0);
std::istringstream ih_sstr(ih_str);
ih_sstr >> ih;
int port = atoi(port_str.c_str());
if (!ih.is_all_zeros() && port != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " *** incoming local announce " << from.address()
<< ":" << port << " ih: " << ih << std::endl;
#endif
// we got an announce, pass it on through the callback
try { m_callback(tcp::endpoint(from.address(), port), ih); }
catch (std::exception&) {}
}
}
void lsd::close()
{
m_socket.close();
}
<commit_msg>lsd close fix<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/thread/mutex.hpp>
#include <cstdlib>
#include <boost/config.hpp>
using boost::bind;
using namespace libtorrent;
namespace libtorrent
{
// defined in broadcast_socket.cpp
address guess_local_address(asio::io_service&);
}
lsd::lsd(io_service& ios, address const& listen_interface
, peer_callback_t const& cb)
: m_callback(cb)
, m_retry_count(0)
, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143"), 6771)
, bind(&lsd::on_announce, self(), _1, _2, _3))
, m_broadcast_timer(ios)
, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}
lsd::~lsd() {}
void lsd::announce(sha1_hash const& ih, int listen_port)
{
if (m_disabled) return;
std::stringstream btsearch;
btsearch << "BT-SEARCH * HTTP/1.1\r\n"
"Host: 239.192.152.143:6771\r\n"
"Port: " << listen_port << "\r\n"
"Infohash: " << ih << "\r\n"
"\r\n\r\n";
std::string const& msg = btsearch.str();
m_retry_count = 0;
asio::error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
if (ec)
{
m_disabled = true;
return;
}
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " ==> announce: ih: " << ih << " port: " << listen_port << std::endl;
#endif
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
void lsd::resend_announce(asio::error_code const& e, std::string msg) try
{
if (e) return;
asio::error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
++m_retry_count;
if (m_retry_count >= 5)
return;
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
catch (std::exception&)
{}
void lsd::on_announce(udp::endpoint const& from, char* buffer
, std::size_t bytes_transferred)
{
using namespace libtorrent::detail;
http_parser p;
p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred));
if (!p.header_finished())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: incomplete HTTP message\n";
#endif
return;
}
if (p.method() != "bt-search")
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
return;
}
std::string const& port_str = p.header("port");
if (port_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
return;
}
std::string const& ih_str = p.header("infohash");
if (ih_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
return;
}
sha1_hash ih(0);
std::istringstream ih_sstr(ih_str);
ih_sstr >> ih;
int port = atoi(port_str.c_str());
if (!ih.is_all_zeros() && port != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " *** incoming local announce " << from.address()
<< ":" << port << " ih: " << ih << std::endl;
#endif
// we got an announce, pass it on through the callback
try { m_callback(tcp::endpoint(from.address(), port), ih); }
catch (std::exception&) {}
}
}
void lsd::close()
{
asio::error_code ec;
m_socket.close(ec);
m_broadcast_timer.cancel();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: hatch.cxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 17:05:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#define _SV_HATCH_CXX
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _VCOMPAT_HXX
#include <tools/vcompat.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_HATCX_HXX
#include <hatch.hxx>
#endif
DBG_NAME( Hatch );
// --------------
// - ImplHatch -
// --------------
ImplHatch::ImplHatch() :
mnRefCount ( 1 ),
maColor ( COL_BLACK ),
meStyle ( HATCH_SINGLE ),
mnDistance ( 1 ),
mnAngle ( 0 )
{
}
// -----------------------------------------------------------------------
ImplHatch::ImplHatch( const ImplHatch& rImplHatch ) :
mnRefCount ( 1 ),
maColor ( rImplHatch.maColor ),
meStyle ( rImplHatch.meStyle ),
mnDistance ( rImplHatch.mnDistance ),
mnAngle ( rImplHatch.mnAngle )
{
}
// ---------
// - Hatch -
// ---------
Hatch::Hatch()
{
DBG_CTOR( Hatch, NULL );
mpImplHatch = new ImplHatch;
}
// -----------------------------------------------------------------------
Hatch::Hatch( const Hatch& rHatch )
{
DBG_CTOR( Hatch, NULL );
DBG_CHKOBJ( &rHatch, Hatch, NULL );
mpImplHatch = rHatch.mpImplHatch;
mpImplHatch->mnRefCount++;
}
// -----------------------------------------------------------------------
Hatch::Hatch( HatchStyle eStyle, const Color& rColor,
long nDistance, USHORT nAngle10 )
{
DBG_CTOR( Hatch, NULL );
mpImplHatch = new ImplHatch;
mpImplHatch->maColor = rColor;
mpImplHatch->meStyle = eStyle;
mpImplHatch->mnDistance = nDistance;
mpImplHatch->mnAngle = nAngle10;
}
// -----------------------------------------------------------------------
Hatch::~Hatch()
{
DBG_DTOR( Hatch, NULL );
if( !( --mpImplHatch->mnRefCount ) )
delete mpImplHatch;
}
// -----------------------------------------------------------------------
Hatch& Hatch::operator=( const Hatch& rHatch )
{
DBG_CHKTHIS( Hatch, NULL );
DBG_CHKOBJ( &rHatch, Hatch, NULL );
rHatch.mpImplHatch->mnRefCount++;
if( !( --mpImplHatch->mnRefCount ) )
delete mpImplHatch;
mpImplHatch = rHatch.mpImplHatch;
return *this;
}
// -----------------------------------------------------------------------
BOOL Hatch::operator==( const Hatch& rHatch ) const
{
DBG_CHKTHIS( Hatch, NULL );
DBG_CHKOBJ( &rHatch, Hatch, NULL );
return( mpImplHatch == rHatch.mpImplHatch ||
( mpImplHatch->maColor == rHatch.mpImplHatch->maColor &&
mpImplHatch->meStyle == rHatch.mpImplHatch->meStyle &&
mpImplHatch->mnDistance == rHatch.mpImplHatch->mnDistance &&
mpImplHatch->mnAngle == rHatch.mpImplHatch->mnAngle ) );
}
// -----------------------------------------------------------------------
void Hatch::ImplMakeUnique()
{
if( mpImplHatch->mnRefCount != 1 )
{
if( mpImplHatch->mnRefCount )
mpImplHatch->mnRefCount--;
mpImplHatch = new ImplHatch( *mpImplHatch );
}
}
// -----------------------------------------------------------------------
void Hatch::SetStyle( HatchStyle eStyle )
{
DBG_CHKTHIS( Hatch, NULL );
ImplMakeUnique();
mpImplHatch->meStyle = eStyle;
}
// -----------------------------------------------------------------------
void Hatch::SetColor( const Color& rColor )
{
DBG_CHKTHIS( Hatch, NULL );
ImplMakeUnique();
mpImplHatch->maColor = rColor;
}
// -----------------------------------------------------------------------
void Hatch::SetDistance( long nDistance )
{
DBG_CHKTHIS( Hatch, NULL );
ImplMakeUnique();
mpImplHatch->mnDistance = nDistance;
}
// -----------------------------------------------------------------------
void Hatch::SetAngle( USHORT nAngle10 )
{
DBG_CHKTHIS( Hatch, NULL );
ImplMakeUnique();
mpImplHatch->mnAngle = nAngle10;
}
// -----------------------------------------------------------------------
SvStream& operator>>( SvStream& rIStm, ImplHatch& rImplHatch )
{
VersionCompat aCompat( rIStm, STREAM_READ );
UINT16 nTmp16;
rIStm >> nTmp16; rImplHatch.meStyle = (HatchStyle) nTmp16;
rIStm >> rImplHatch.maColor >> rImplHatch.mnDistance >> rImplHatch.mnAngle;
return rIStm;
}
// -----------------------------------------------------------------------
SvStream& operator<<( SvStream& rOStm, const ImplHatch& rImplHatch )
{
VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );
rOStm << (UINT16) rImplHatch.meStyle << rImplHatch.maColor;
rOStm << rImplHatch.mnDistance << rImplHatch.mnAngle;
return rOStm;
}
// -----------------------------------------------------------------------
SvStream& operator>>( SvStream& rIStm, Hatch& rHatch )
{
rHatch.ImplMakeUnique();
return( rIStm >> *rHatch.mpImplHatch );
}
// -----------------------------------------------------------------------
SvStream& operator<<( SvStream& rOStm, const Hatch& rHatch )
{
return( rOStm << *rHatch.mpImplHatch );
}
<commit_msg>INTEGRATION: CWS vclcleanup02 (1.1.1.1.386); FILE MERGED 2003/12/17 16:04:26 mt 1.1.1.1.386.1: #i23061# header cleanup, remove #ifdef ???_CXX and #define ???_CXX, also removed .impl files and fixed soke windows compiler warnings<commit_after>/*************************************************************************
*
* $RCSfile: hatch.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2004-01-06 13:40:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _VCOMPAT_HXX
#include <tools/vcompat.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_HATCX_HXX
#include <hatch.hxx>
#endif
DBG_NAME( Hatch );
// --------------
// - ImplHatch -
// --------------
ImplHatch::ImplHatch() :
mnRefCount ( 1 ),
maColor ( COL_BLACK ),
meStyle ( HATCH_SINGLE ),
mnDistance ( 1 ),
mnAngle ( 0 )
{
}
// -----------------------------------------------------------------------
ImplHatch::ImplHatch( const ImplHatch& rImplHatch ) :
mnRefCount ( 1 ),
maColor ( rImplHatch.maColor ),
meStyle ( rImplHatch.meStyle ),
mnDistance ( rImplHatch.mnDistance ),
mnAngle ( rImplHatch.mnAngle )
{
}
// ---------
// - Hatch -
// ---------
Hatch::Hatch()
{
DBG_CTOR( Hatch, NULL );
mpImplHatch = new ImplHatch;
}
// -----------------------------------------------------------------------
Hatch::Hatch( const Hatch& rHatch )
{
DBG_CTOR( Hatch, NULL );
DBG_CHKOBJ( &rHatch, Hatch, NULL );
mpImplHatch = rHatch.mpImplHatch;
mpImplHatch->mnRefCount++;
}
// -----------------------------------------------------------------------
Hatch::Hatch( HatchStyle eStyle, const Color& rColor,
long nDistance, USHORT nAngle10 )
{
DBG_CTOR( Hatch, NULL );
mpImplHatch = new ImplHatch;
mpImplHatch->maColor = rColor;
mpImplHatch->meStyle = eStyle;
mpImplHatch->mnDistance = nDistance;
mpImplHatch->mnAngle = nAngle10;
}
// -----------------------------------------------------------------------
Hatch::~Hatch()
{
DBG_DTOR( Hatch, NULL );
if( !( --mpImplHatch->mnRefCount ) )
delete mpImplHatch;
}
// -----------------------------------------------------------------------
Hatch& Hatch::operator=( const Hatch& rHatch )
{
DBG_CHKTHIS( Hatch, NULL );
DBG_CHKOBJ( &rHatch, Hatch, NULL );
rHatch.mpImplHatch->mnRefCount++;
if( !( --mpImplHatch->mnRefCount ) )
delete mpImplHatch;
mpImplHatch = rHatch.mpImplHatch;
return *this;
}
// -----------------------------------------------------------------------
BOOL Hatch::operator==( const Hatch& rHatch ) const
{
DBG_CHKTHIS( Hatch, NULL );
DBG_CHKOBJ( &rHatch, Hatch, NULL );
return( mpImplHatch == rHatch.mpImplHatch ||
( mpImplHatch->maColor == rHatch.mpImplHatch->maColor &&
mpImplHatch->meStyle == rHatch.mpImplHatch->meStyle &&
mpImplHatch->mnDistance == rHatch.mpImplHatch->mnDistance &&
mpImplHatch->mnAngle == rHatch.mpImplHatch->mnAngle ) );
}
// -----------------------------------------------------------------------
void Hatch::ImplMakeUnique()
{
if( mpImplHatch->mnRefCount != 1 )
{
if( mpImplHatch->mnRefCount )
mpImplHatch->mnRefCount--;
mpImplHatch = new ImplHatch( *mpImplHatch );
}
}
// -----------------------------------------------------------------------
void Hatch::SetStyle( HatchStyle eStyle )
{
DBG_CHKTHIS( Hatch, NULL );
ImplMakeUnique();
mpImplHatch->meStyle = eStyle;
}
// -----------------------------------------------------------------------
void Hatch::SetColor( const Color& rColor )
{
DBG_CHKTHIS( Hatch, NULL );
ImplMakeUnique();
mpImplHatch->maColor = rColor;
}
// -----------------------------------------------------------------------
void Hatch::SetDistance( long nDistance )
{
DBG_CHKTHIS( Hatch, NULL );
ImplMakeUnique();
mpImplHatch->mnDistance = nDistance;
}
// -----------------------------------------------------------------------
void Hatch::SetAngle( USHORT nAngle10 )
{
DBG_CHKTHIS( Hatch, NULL );
ImplMakeUnique();
mpImplHatch->mnAngle = nAngle10;
}
// -----------------------------------------------------------------------
SvStream& operator>>( SvStream& rIStm, ImplHatch& rImplHatch )
{
VersionCompat aCompat( rIStm, STREAM_READ );
UINT16 nTmp16;
rIStm >> nTmp16; rImplHatch.meStyle = (HatchStyle) nTmp16;
rIStm >> rImplHatch.maColor >> rImplHatch.mnDistance >> rImplHatch.mnAngle;
return rIStm;
}
// -----------------------------------------------------------------------
SvStream& operator<<( SvStream& rOStm, const ImplHatch& rImplHatch )
{
VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );
rOStm << (UINT16) rImplHatch.meStyle << rImplHatch.maColor;
rOStm << rImplHatch.mnDistance << rImplHatch.mnAngle;
return rOStm;
}
// -----------------------------------------------------------------------
SvStream& operator>>( SvStream& rIStm, Hatch& rHatch )
{
rHatch.ImplMakeUnique();
return( rIStm >> *rHatch.mpImplHatch );
}
// -----------------------------------------------------------------------
SvStream& operator<<( SvStream& rOStm, const Hatch& rHatch )
{
return( rOStm << *rHatch.mpImplHatch );
}
<|endoftext|>
|
<commit_before>#include "ParticleConnector.h"
#include <maya/MGlobal.h>
#include <maya/MSelectionList.h>
#include <maya/MItMeshVertex.h>
#include <maya/MItSelectionList.h>
#include <maya/MFnParticleSystem.h>
#include <maya/MPlug.h>
ParticleConnector::ParticleConnector() {
}
ParticleConnector::~ParticleConnector() {
}
MStatus ParticleConnector::doIt(const MArgList& argList) {
MStatus stat = MS::kFailure;
// Create iterator on selection.
MSelectionList selection;
MGlobal::getActiveSelectionList(selection);
MItSelectionList iter(selection);
// Iterate through selected meshes and convert to particles.
for (; !iter.isDone(); iter.next()) {
MDagPath mdagPath;
MPointArray pts;
iter.getDagPath(mdagPath);
stat = collectMeshData(mdagPath, &pts);
if (checkStatus(stat)) {
// Create particle system
MFnParticleSystem prtSystem;
// Create particle system with the same parent as the source mesh.
MObject particle = prtSystem.create(mdagPath.node());
prtSystem.setObject(particle);
// Emit all particles
prtSystem.emit(pts);
// Change the particles render type
MFnDependencyNode fromNode(particle);
MPlug plug = fromNode.findPlug("particleRenderType");
plug.setValue(SPHERES);
// Save state so the particles do not disappear
prtSystem.saveInitialState();
stat = deleteMesh(mdagPath);
if(!checkStatus(stat)) break;
}
}
return stat;
}
MStatus ParticleConnector::redoIt() {
return MS::kSuccess;
}
void* ParticleConnector::creator() {
return new ParticleConnector;
}
bool ParticleConnector::checkStatus (const MStatus& stat) {
if (stat != MS::kSuccess) {
MGlobal::displayError(stat.errorString());
return false;
}
return true;
}
/// Deletes the mesh connected to the dagpath by
/// using a MEL-command to delete it.
MStatus ParticleConnector::deleteMesh(MDagPath& object) {
MStatus stat;
object.extendToShapeDirectlyBelow(0);
MString deleteOriginalStr = "delete " + object.fullPathName();
// MGlobal::displayInfo(object.node().apiTypeStr());
stat = MGlobal::executeCommand(deleteOriginalStr);
if(!checkStatus(stat)) return MS::kFailure;
return MS::kSuccess;
}
/// Collects the positions for the selected mesh and stores
/// it in the given MPointArray.
MStatus ParticleConnector::collectMeshData(const MDagPath& mdagPath, MPointArray* dest) {
MStatus stat;
MPoint pt;
// Create iterator on the current dagpath.
MItMeshVertex vertIter(mdagPath, MObject::kNullObj, &stat);
if(!checkStatus(stat)) return MS::kFailure;
// Iterate through vertices and append their positions to dest.
for (; !vertIter.isDone(); vertIter.next()) {
pt = vertIter.position(MSpace::kWorld, &stat);
dest->append(pt);
}
return MS::kSuccess;
}<commit_msg>Particle system now appears under the correct kTransform<commit_after>#include "ParticleConnector.h"
#include <maya/MGlobal.h>
#include <maya/MSelectionList.h>
#include <maya/MItMeshVertex.h>
#include <maya/MItSelectionList.h>
#include <maya/MFnParticleSystem.h>
#include <maya/MPlug.h>
#include <maya/MFnTransform.h>
ParticleConnector::ParticleConnector() {
}
ParticleConnector::~ParticleConnector() {
}
MStatus ParticleConnector::doIt(const MArgList& argList) {
MStatus stat = MS::kFailure;
// Create iterator on selection.
MSelectionList selection;
MGlobal::getActiveSelectionList(selection);
MItSelectionList iter(selection);
// Iterate through selected meshes and convert to particles.
for (; !iter.isDone(); iter.next()) {
MDagPath mdagPath, particleDag;
MPointArray pts;
iter.getDagPath(mdagPath);
stat = collectMeshData(mdagPath, &pts);
// Get the transformation matrix of the parent.
MFnTransform transformFn(mdagPath.node());
MTransformationMatrix parentTransform = transformFn.transformation(&stat);
if (checkStatus(stat)) {
// Create particle system
MFnParticleSystem prtSystem(mdagPath);
MObject particle = prtSystem.create();
prtSystem.setObject(particle);
// Create function set to manipulate dagNode of the particlesystem.
MFnDagNode fnDagNode(particle);
if (fnDagNode.parentCount() > 0) {
// Sets the transformation to the one of its parent.
// We can't explicitly set it in the MFnParticleSystem.create() method since
// some attributes essential for the particle system are lost.
MObject parent = fnDagNode.parent(0);
if (parent.apiType() == MFn::kTransform) {
MFnTransform parentFn(parent);
parentFn.set(parentTransform);
}
}
// Emit all particles
prtSystem.emit(pts);
// Change the particles render type
MFnDependencyNode fromNode(particle);
MPlug plug = fromNode.findPlug("particleRenderType");
plug.setValue(SPHERES);
// Save state so the particles do not disappear
prtSystem.saveInitialState();
stat = deleteMesh(mdagPath);
if(!checkStatus(stat)) break;
}
}
return stat;
}
MStatus ParticleConnector::redoIt() {
return MS::kSuccess;
}
void* ParticleConnector::creator() {
return new ParticleConnector;
}
/// Utility function to check if a status is ok.
bool ParticleConnector::checkStatus (const MStatus& stat) {
if (stat != MS::kSuccess) {
MGlobal::displayError(stat.errorString());
return false;
}
return true;
}
/// Deletes the mesh connected to the dagpath by
/// using a MEL-command to delete it.
MStatus ParticleConnector::deleteMesh(MDagPath& object) {
MStatus stat;
MString deleteOriginalStr = "delete " + object.fullPathName();
stat = MGlobal::executeCommand(deleteOriginalStr);
if(!checkStatus(stat)) return MS::kFailure;
return MS::kSuccess;
}
/// Collects the positions for the selected mesh and stores
/// it in the given MPointArray.
MStatus ParticleConnector::collectMeshData(const MDagPath& mdagPath, MPointArray* dest) {
MStatus stat;
MPoint pt;
// Create iterator on the current dagpath.
MItMeshVertex vertIter(mdagPath, MObject::kNullObj, &stat);
if(!checkStatus(stat)) return MS::kFailure;
// Iterate through vertices and append their positions to dest.
for (; !vertIter.isDone(); vertIter.next()) {
pt = vertIter.position(MSpace::kWorld, &stat);
dest->append(pt);
}
return MS::kSuccess;
}<|endoftext|>
|
<commit_before>#include "PostscriptPrinter.hpp"
namespace hpl
{
PostscriptPrinter::PostscriptPrinter(Orientation orientation) : AbstractPlotter(), PlotPrinter(orientation)
{
}
PostscriptPrinter::~PostscriptPrinter()
{
out.close();
}
bool PostscriptPrinter::saveToFile(const std::string& fileName)
{
this->fileName = fileName + ".ps";
out.open(this->fileName);
if (! out.is_open()) {
return false;
}
update();
return true;
}
void PostscriptPrinter::update()
{
if (plots == nullptr) {
return;
}
writeHeader();
for(auto i = plots->cbegin(); i != plots->cend(); i++) {
setCurrentGeometry(i->second->getGeometry(), i->second->xmin(), i->second->xmax(), i->second->ymin(), i->second->ymax());
Lines* l = dynamic_cast<Lines*>(i->second);
if (l != 0) {
setColor(l->getColor());
setLineWidth(l->getThickness());
draw(l->n(), l->x(), l->y(), l->getDataType());
continue;
}
Points* p = dynamic_cast<Points*>(i->second);
if (p != 0) {
setColor(p->getColor());
if (p->getSymbol() != Points::Dot) {
setLineWidth(p->getSymbolSize());
}
draw(p->n(), p->x(), p->y(), p->getDataType());
continue;
}
Contour* c = dynamic_cast<Contour*>(i->second);
if (c != 0 && c->getDataType() == Drawable::Type_Texture) {
setCurrentZLimits(c->getZmin(), c->getZmax());
Color* colors = c->getColors();
draw(c->n, c->x, c->y, colors);
delete[] colors;
continue;
}
Text* t = dynamic_cast<Text*>(i->second);
if (t != 0) {
//! @todo calculate fontsize properly
unsigned int fontSize = 10;
setFont(t->getFontName(), fontSize);
setColor(t->getColor());
writeTextCentered(t->x + 0.5 * t->width, t->y + 0.5 * t->height, t->text);
continue;
}
}
writeFooter();
}
void PostscriptPrinter::writeHeader()
{
out << "%!PS-Adobe-3.0" << std::endl;
out << "%%BoundingBox 0 0 " << (pixelX+2*pixelBoundary) << " " << (pixelY+2*pixelBoundary) << std::endl;
out << "%%PageOrientation: " << (orientation == Portrait ? "Portrait" : "Landscape") << std::endl;
out << "%%PageBoundingBox 0 0 " << (pixelX+2*pixelBoundary) << " " << (pixelY+2*pixelBoundary) << std::endl;
out << "%%EndPageSetup" << std::endl;
double s = 1.0 / sizefactor;
out << s << " " << s << " scale" << std::endl;
}
void PostscriptPrinter::writeFooter()
{
out << "showpage" << std::endl;
out << "%%EOF" << std::endl;
}
void PostscriptPrinter::setFont(std::string fontname, unsigned int size)
{
fontname[0] = toupper(fontname[0]);
out << "/" << fontname << " findfont" << std::endl;
out << size * sizefactor << " scalefont" << std::endl;
out << "setfont" << std::endl;
}
void PostscriptPrinter::setColor(const Color& color)
{
out << color.r << " " << color.g << " " << color.b << " setrgbcolor" << std::endl;
}
void PostscriptPrinter::setLineWidth(unsigned int width)
{
out << width << " setlinewidth" << std::endl;
}
void PostscriptPrinter::draw(int n, double const* x, double const* y, Drawable::Type type)
{
switch (type) {
case Drawable::Type_Lines:
for (int i = 0; i < n-1; i+=2) {
//! @todo this should actually be done in the Drawable derivates
if (isfinite(x[i], y[i]) && isfinite(x[i+1], y[i+1])) {
drawLine(x[i], y[i], x[i+1], y[i+1]);
}
}
break;
case Drawable::Type_LineStrips:
for (int i = 0; i < n-1; ++i) {
if (isfinite(x[i], y[i]) && isfinite(x[i+1], y[i+1])) {
drawLine(x[i], y[i], x[i+1], y[i+1]);
}
}
break;
case Drawable::Type_Points:
for (int i = 0; i < n; ++i) {
if (isfinite(x[i], y[i])) {
drawPoint(x[i], y[i]);
}
}
break;
case Drawable::Type_Texture:
break;
}
}
void PostscriptPrinter::draw(int n, double const* x, double const* y, Color const* colors)
{
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
setColor(colors[i*n+j]);
double dxp = 0.5 * (x[j] - (j == 0 ? currentXMin : x[j-1]));
double dyp = 0.5 * (y[i] - (i == 0 ? currentYMin : y[i-1]));
double dxn = 0.5 * ((j == n-1 ? currentXMax : x[j+1]) - x[j]);
double dyn = 0.5 * ((i == n-1 ? currentYMax : y[i+1]) - y[i]);
fillShape({x[j]-dxp, x[j]-dxp, x[j]+dxn, x[j]+dxn}, {y[i]-dyp, y[i]+dyn, y[i]+dyn, y[i]-dyp});
}
}
}
void PostscriptPrinter::drawLine(double x1, double y1, double x2, double y2)
{
Pixel p1 = transformCoordinates(x1, y1), p2 = transformCoordinates(x2, y2);
out << "newpath" << std::endl;
out << p1.first << " " << p1.second << " moveto" << std::endl;
out << p2.first << " " << p2.second << " lineto" << std::endl;
out << "stroke" << std::endl;
}
void PostscriptPrinter::drawPoint(double x, double y)
{
Pixel p = transformCoordinates(x, y);
out << "newpath" << std::endl;
out << p.first << " " << p.second << " moveto" << std::endl;
out << "gsave currentpoint lineto 1 setlinecap stroke grestore" << std::endl;
}
void PostscriptPrinter::fillShape(std::vector<double> x, std::vector<double> y)
{
if (x.size() == 0 || y.size() == 0) {
return;
}
out << "newpath" << std::endl;
Pixel p = transformCoordinates(x[0], y[0]);
out << p.first << " " << p.second << " moveto" << std::endl;
for (unsigned int i = 1; i < x.size() && i < y.size(); i++) {
p = transformCoordinates(x[i], y[i]);
out << p.first << " " << p.second << " lineto" << std::endl;
}
out << "closepath" << std::endl;
out << "gsave fill grestore" << std::endl;
}
void PostscriptPrinter::writeText(double x, double y, std::string const& text)
{
Pixel p = transformCoordinates(x, y);
out << p.first << " " << p.second << " moveto" << std::endl;
out << "(" << text << ") show" << std::endl;
}
void PostscriptPrinter::writeTextCentered(double x, double y, std::string const& text)
{
Pixel p = transformCoordinates(x, y);
out << p.first << " " << p.second << " moveto (" << text << ") dup true charpath pathbbox 3 -1 roll sub 2 div neg 3 1 roll sub 2 div exch "
<< p.first << " " << p.second << " moveto rmoveto show" << std::endl;
}
}
<commit_msg>Fixed bug in new positioning algorithm, works now. Only need to adjust font sizes appropriately now.<commit_after>#include "PostscriptPrinter.hpp"
namespace hpl
{
PostscriptPrinter::PostscriptPrinter(Orientation orientation) : AbstractPlotter(), PlotPrinter(orientation)
{
}
PostscriptPrinter::~PostscriptPrinter()
{
out.close();
}
bool PostscriptPrinter::saveToFile(const std::string& fileName)
{
this->fileName = fileName + ".ps";
out.open(this->fileName);
if (! out.is_open()) {
return false;
}
update();
return true;
}
void PostscriptPrinter::update()
{
if (plots == nullptr) {
return;
}
writeHeader();
for(auto i = plots->cbegin(); i != plots->cend(); i++) {
setCurrentGeometry(i->second->getGeometry(), i->second->xmin(), i->second->xmax(), i->second->ymin(), i->second->ymax());
Lines* l = dynamic_cast<Lines*>(i->second);
if (l != 0) {
setColor(l->getColor());
setLineWidth(l->getThickness());
draw(l->n(), l->x(), l->y(), l->getDataType());
continue;
}
Points* p = dynamic_cast<Points*>(i->second);
if (p != 0) {
setColor(p->getColor());
if (p->getSymbol() != Points::Dot) {
setLineWidth(p->getSymbolSize());
}
draw(p->n(), p->x(), p->y(), p->getDataType());
continue;
}
Contour* c = dynamic_cast<Contour*>(i->second);
if (c != 0 && c->getDataType() == Drawable::Type_Texture) {
setCurrentZLimits(c->getZmin(), c->getZmax());
Color* colors = c->getColors();
draw(c->n, c->x, c->y, colors);
delete[] colors;
continue;
}
Text* t = dynamic_cast<Text*>(i->second);
if (t != 0) {
//! @todo calculate fontsize properly
unsigned int fontSize = 10;
setFont(t->getFontName(), fontSize);
setColor(t->getColor());
writeTextCentered(t->x + 0.5 * t->width, t->y + 0.5 * t->height, t->text);
continue;
}
}
writeFooter();
}
void PostscriptPrinter::writeHeader()
{
out << "%!PS-Adobe-3.0" << std::endl;
out << "%%BoundingBox 0 0 " << (pixelX+2*pixelBoundary) << " " << (pixelY+2*pixelBoundary) << std::endl;
out << "%%PageOrientation: " << (orientation == Portrait ? "Portrait" : "Landscape") << std::endl;
out << "%%PageBoundingBox 0 0 " << (pixelX+2*pixelBoundary) << " " << (pixelY+2*pixelBoundary) << std::endl;
out << "%%EndPageSetup" << std::endl;
double s = 1.0 / sizefactor;
out << s << " " << s << " scale" << std::endl;
}
void PostscriptPrinter::writeFooter()
{
out << "showpage" << std::endl;
out << "%%EOF" << std::endl;
}
void PostscriptPrinter::setFont(std::string fontname, unsigned int size)
{
fontname[0] = toupper(fontname[0]);
out << "/" << fontname << " findfont" << std::endl;
out << size * sizefactor << " scalefont" << std::endl;
out << "setfont" << std::endl;
}
void PostscriptPrinter::setColor(const Color& color)
{
out << color.r << " " << color.g << " " << color.b << " setrgbcolor" << std::endl;
}
void PostscriptPrinter::setLineWidth(unsigned int width)
{
out << width << " setlinewidth" << std::endl;
}
void PostscriptPrinter::draw(int n, double const* x, double const* y, Drawable::Type type)
{
switch (type) {
case Drawable::Type_Lines:
for (int i = 0; i < n-1; i+=2) {
//! @todo this should actually be done in the Drawable derivates
if (isfinite(x[i], y[i]) && isfinite(x[i+1], y[i+1])) {
drawLine(x[i], y[i], x[i+1], y[i+1]);
}
}
break;
case Drawable::Type_LineStrips:
for (int i = 0; i < n-1; ++i) {
if (isfinite(x[i], y[i]) && isfinite(x[i+1], y[i+1])) {
drawLine(x[i], y[i], x[i+1], y[i+1]);
}
}
break;
case Drawable::Type_Points:
for (int i = 0; i < n; ++i) {
if (isfinite(x[i], y[i])) {
drawPoint(x[i], y[i]);
}
}
break;
case Drawable::Type_Texture:
break;
}
}
void PostscriptPrinter::draw(int n, double const* x, double const* y, Color const* colors)
{
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
setColor(colors[i*n+j]);
double dxp = 0.5 * (x[j] - (j == 0 ? currentXMin : x[j-1]));
double dyp = 0.5 * (y[i] - (i == 0 ? currentYMin : y[i-1]));
double dxn = 0.5 * ((j == n-1 ? currentXMax : x[j+1]) - x[j]);
double dyn = 0.5 * ((i == n-1 ? currentYMax : y[i+1]) - y[i]);
fillShape({x[j]-dxp, x[j]-dxp, x[j]+dxn, x[j]+dxn}, {y[i]-dyp, y[i]+dyn, y[i]+dyn, y[i]-dyp});
}
}
}
void PostscriptPrinter::drawLine(double x1, double y1, double x2, double y2)
{
Pixel p1 = transformCoordinates(x1, y1), p2 = transformCoordinates(x2, y2);
out << "newpath" << std::endl;
out << p1.first << " " << p1.second << " moveto" << std::endl;
out << p2.first << " " << p2.second << " lineto" << std::endl;
out << "stroke" << std::endl;
}
void PostscriptPrinter::drawPoint(double x, double y)
{
Pixel p = transformCoordinates(x, y);
out << "newpath" << std::endl;
out << p.first << " " << p.second << " moveto" << std::endl;
out << "gsave currentpoint lineto 1 setlinecap stroke grestore" << std::endl;
}
void PostscriptPrinter::fillShape(std::vector<double> x, std::vector<double> y)
{
if (x.size() == 0 || y.size() == 0) {
return;
}
out << "newpath" << std::endl;
Pixel p = transformCoordinates(x[0], y[0]);
out << p.first << " " << p.second << " moveto" << std::endl;
for (unsigned int i = 1; i < x.size() && i < y.size(); i++) {
p = transformCoordinates(x[i], y[i]);
out << p.first << " " << p.second << " lineto" << std::endl;
}
out << "closepath" << std::endl;
out << "gsave fill grestore" << std::endl;
}
void PostscriptPrinter::writeText(double x, double y, std::string const& text)
{
Pixel p = transformCoordinates(x, y);
out << p.first << " " << p.second << " moveto" << std::endl;
out << "(" << text << ") show" << std::endl;
}
void PostscriptPrinter::writeTextCentered(double x, double y, std::string const& text)
{
Pixel p = transformCoordinates(x, y);
out << "save " << p.first << " " << p.second << " moveto (" << text << ") dup true charpath pathbbox 3 -1 roll sub 2 div neg 3 1 roll sub 2 div exch "
<< p.first << " " << p.second << " moveto rmoveto show restore" << std::endl;
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cstdio>
#include "json_object.h"
#include "json_loader.h"
#include "regex.h"
#include "grammar.h"
#include "grammar_loader.h"
#include "scope.h"
#include "tokenizer.h"
using namespace std;
void error(const char* msg) {
cerr << msg << endl;
exit(-1);
}
int file_size(FILE* file) {
if (fseek(file, 0, SEEK_END) != 0) error("failed to seek");
int size = ftell(file);
if (size == -1) error("failed to tell size");
if (fseek(file, 0, SEEK_SET) != 0) error("failed to seek");
return size;
}
char* read_all(FILE* file, int& size) {
size = file_size(file);
char* buffer = new char[size];
if(buffer == nullptr) error("can't allocate memeory");
if(fread(buffer, size, 1, file) != 1) error("cannot read file");
return buffer;
}
string read_file(const string& path) {
FILE* file = fopen(path.c_str(), "rb");
if(file == nullptr) error("error open file");
char* buffer;
int size;
buffer = read_all(file, size);
fclose(file);
return string(buffer, buffer + size);
}
using namespace shl;
const Pattern& get_map(const map<string, Pattern> m, const char* key) {
return m.at(key);
}
const Pattern& get_v(const vector<Pattern> v, int i) {
return v.at(i);
}
int main() {
string syntax_data = read_file("test/c.json");
shl::GrammarLoader loader;
shl::Grammar g = loader.load(syntax_data);
string source = read_file("test/linker_md.c");
shl::Tokenizer tokenizer;
auto tokens = tokenizer.tokenize(g, source);
for (auto& pair : tokens) {
cout << "(" << pair.first.position << "," << pair.first.length << "," << pair.first.end() - 1 << ")" << pair.second.name() << endl;
cout << source.substr(pair.first.position, pair.first.length) << endl;
}
cout << tokens.size() << endl;
}
<commit_msg>add test for StructuredScope<commit_after>#include <iostream>
#include <cstdio>
#include "json_object.h"
#include "json_loader.h"
#include "regex.h"
#include "grammar.h"
#include "grammar_loader.h"
#include "scope.h"
#include "tokenizer.h"
#include "structured_scope.h"
using namespace std;
void error(const char* msg) {
cerr << msg << endl;
exit(-1);
}
int file_size(FILE* file) {
if (fseek(file, 0, SEEK_END) != 0) error("failed to seek");
int size = ftell(file);
if (size == -1) error("failed to tell size");
if (fseek(file, 0, SEEK_SET) != 0) error("failed to seek");
return size;
}
char* read_all(FILE* file, int& size) {
size = file_size(file);
char* buffer = new char[size];
if(buffer == nullptr) error("can't allocate memeory");
if(fread(buffer, size, 1, file) != 1) error("cannot read file");
return buffer;
}
string read_file(const string& path) {
FILE* file = fopen(path.c_str(), "rb");
if(file == nullptr) error("error open file");
char* buffer;
int size;
buffer = read_all(file, size);
fclose(file);
return string(buffer, buffer + size);
}
using namespace shl;
const Pattern& get_map(const map<string, Pattern> m, const char* key) {
return m.at(key);
}
const Pattern& get_v(const vector<Pattern> v, int i) {
return v.at(i);
}
int main() {
string syntax_data = read_file("test/c.json");
shl::GrammarLoader loader;
shl::Grammar g = loader.load(syntax_data);
string source = read_file("test/linker_md.c");
shl::Tokenizer tokenizer;
auto tokens = tokenizer.tokenize(g, source);
/*
for (auto& pair : tokens) {
cout << "(" << pair.first.position << "," << pair.first.length << "," << pair.first.end() - 1 << ")" << pair.second.name() << endl;
cout << source.substr(pair.first.position, pair.first.length) << endl;
}
*/
StructuredScope structure;
string markup = structure.to_markup(source, tokens);
cout << markup << endl;
}
<|endoftext|>
|
<commit_before>#include <ncurses.h>
#include "window.hh"
#include "buffer.hh"
#include "file.hh"
#include "regex_selector.hh"
#include "command_manager.hh"
#include "buffer_manager.hh"
#include <unordered_map>
#include <cassert>
using namespace Kakoune;
void draw_window(Window& window)
{
int max_x,max_y;
getmaxyx(stdscr, max_y, max_x);
max_y -= 1;
window.set_dimensions(WindowCoord(max_y, max_x));
window.update_display_buffer();
WindowCoord position;
for (const DisplayAtom& atom : window.display_buffer())
{
const std::string& content = atom.content;
if (atom.attribute & UNDERLINE)
attron(A_UNDERLINE);
else
attroff(A_UNDERLINE);
size_t pos = 0;
size_t end;
while (true)
{
move(position.line, position.column);
clrtoeol();
end = content.find_first_of('\n', pos);
std::string line = content.substr(pos, end - pos);
addstr(line.c_str());
if (end != std::string::npos)
{
position.line = position.line + 1;
position.column = 0;
pos = end + 1;
if (position.line >= max_y)
break;
}
else
{
position.column += line.length();
break;
}
}
if (position.line >= max_y)
break;
}
while (++position.line < max_y)
{
move(position.line, 0);
clrtoeol();
addch('~');
}
const WindowCoord& cursor_position = window.cursor_position();
move(cursor_position.line, cursor_position.column);
}
void init_ncurses()
{
initscr();
cbreak();
noecho();
nonl();
intrflush(stdscr, false);
keypad(stdscr, true);
curs_set(2);
}
void deinit_ncurses()
{
endwin();
}
struct prompt_aborted {};
std::string prompt(const std::string& text)
{
int max_x, max_y;
getmaxyx(stdscr, max_y, max_x);
move(max_y-1, 0);
addstr(text.c_str());
clrtoeol();
std::string result;
while(true)
{
char c = getch();
switch (c)
{
case '\r':
return result;
case 7:
if (not result.empty())
{
move(max_y - 1, text.length() + result.length() - 1);
addch(' ');
result.resize(result.length() - 1);
move(max_y - 1, text.length() + result.length());
refresh();
}
break;
case 27:
throw prompt_aborted();
default:
result += c;
addch(c);
refresh();
}
}
return result;
}
void print_status(const std::string& status)
{
int x,y;
getmaxyx(stdscr, y, x);
move(y-1, 0);
clrtoeol();
addstr(status.c_str());
}
void do_insert(Window& window)
{
print_status("-- INSERT --");
std::string inserted;
WindowCoord pos = window.cursor_position();
move(pos.line, pos.column);
refresh();
while(true)
{
char c = getch();
if (c == 27)
break;
window.insert(std::string() + c);
draw_window(window);
}
print_status("");
}
Window* current_window;
void edit(const CommandParameters& params)
{
if (params.size() != 1)
throw wrong_argument_count();
std::string filename = params[0];
Buffer* buffer = NULL;
try
{
buffer = create_buffer_from_file(filename);
}
catch (file_not_found& what)
{
print_status("new file " + filename);
buffer = new Buffer(filename);
}
current_window = buffer->get_or_create_window();
}
void write_buffer(const CommandParameters& params)
{
if (params.size() > 1)
throw wrong_argument_count();
Buffer& buffer = current_window->buffer();
std::string filename = params.empty() ? buffer.name() : params[0];
write_buffer_to_file(buffer, filename);
}
bool quit_requested = false;
void quit(const CommandParameters& params)
{
if (params.size() != 0)
throw wrong_argument_count();
quit_requested = true;
}
CommandManager command_manager;
void do_command()
{
try
{
command_manager.execute(prompt(":"));
}
catch (prompt_aborted&) {}
catch (std::runtime_error& err)
{
print_status(err.what());
}
}
bool is_blank(char c)
{
return c == ' ' or c == '\t' or c == '\n';
}
Selection select_to_next_word(const BufferIterator& cursor)
{
BufferIterator end = cursor;
while (not end.is_end() and not is_blank(*end))
++end;
while (not end.is_end() and is_blank(*end))
++end;
return Selection(cursor, end);
}
Selection select_to_next_word_end(const BufferIterator& cursor)
{
BufferIterator end = cursor;
while (not end.is_end() and is_blank(*end))
++end;
while (not end.is_end() and not is_blank(*end))
++end;
return Selection(cursor, end);
}
Selection select_line(const BufferIterator& cursor)
{
BufferIterator begin = cursor;
while (not begin.is_begin() and *(begin -1) != '\n')
--begin;
BufferIterator end = cursor;
while (not end.is_end() and *end != '\n')
++end;
return Selection(begin, end + 1);
}
void do_search(Window& window)
{
try
{
std::string ex = prompt("/");
window.select(false, RegexSelector(ex));
}
catch (boost::regex_error&) {}
catch (prompt_aborted&) {}
}
std::unordered_map<char, std::function<void (Window& window, int count)>> keymap =
{
{ 'h', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(WindowCoord(0, -count)); window.empty_selections(); } },
{ 'j', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(WindowCoord(count, 0)); window.empty_selections(); } },
{ 'k', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(WindowCoord(-count, 0)); window.empty_selections(); } },
{ 'l', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(WindowCoord(0, count)); window.empty_selections(); } },
{ 'd', [](Window& window, int count) { window.erase(); window.empty_selections(); } },
{ 'c', [](Window& window, int count) { window.erase(); do_insert(window); } },
{ 'i', [](Window& window, int count) { do_insert(window); } },
{ ':', [](Window& window, int count) { do_command(); } },
{ ' ', [](Window& window, int count) { window.empty_selections(); } },
{ 'w', [](Window& window, int count) { do { window.select(false, select_to_next_word); } while(--count > 0); } },
{ 'W', [](Window& window, int count) { do { window.select(true, select_to_next_word); } while(--count > 0); } },
{ 'e', [](Window& window, int count) { do { window.select(false, select_to_next_word_end); } while(--count > 0); } },
{ 'E', [](Window& window, int count) { do { window.select(true, select_to_next_word_end); } while(--count > 0); } },
{ '.', [](Window& window, int count) { do { window.select(false, select_line); } while(--count > 0); } },
{ '/', [](Window& window, int count) { do_search(window); } },
{ 'u', [](Window& window, int count) { do { if (not window.undo()) { print_status("nothing left to undo"); break; } } while(--count > 0); } },
{ 'U', [](Window& window, int count) { do { if (not window.redo()) { print_status("nothing left to redo"); break; } } while(--count > 0); } },
};
int main()
{
init_ncurses();
command_manager.register_command(std::vector<std::string>{ "e", "edit" }, edit);
command_manager.register_command(std::vector<std::string>{ "q", "quit" }, quit);
command_manager.register_command(std::vector<std::string>{ "w", "write" }, write_buffer);
try
{
auto buffer = new Buffer("<scratch>");
current_window = buffer->get_or_create_window();
draw_window(*current_window);
int count = 0;
while(not quit_requested)
{
char c = getch();
if (isdigit(c))
count = count * 10 + c - '0';
else
{
if (keymap.find(c) != keymap.end())
{
keymap[c](*current_window, count);
draw_window(*current_window);
}
count = 0;
}
}
deinit_ncurses();
}
catch (...)
{
deinit_ncurses();
throw;
}
return 0;
}
<commit_msg>Add a buffer command to switch between existing buffers<commit_after>#include <ncurses.h>
#include "window.hh"
#include "buffer.hh"
#include "file.hh"
#include "regex_selector.hh"
#include "command_manager.hh"
#include "buffer_manager.hh"
#include <unordered_map>
#include <cassert>
using namespace Kakoune;
void draw_window(Window& window)
{
int max_x,max_y;
getmaxyx(stdscr, max_y, max_x);
max_y -= 1;
window.set_dimensions(WindowCoord(max_y, max_x));
window.update_display_buffer();
WindowCoord position;
for (const DisplayAtom& atom : window.display_buffer())
{
const std::string& content = atom.content;
if (atom.attribute & UNDERLINE)
attron(A_UNDERLINE);
else
attroff(A_UNDERLINE);
size_t pos = 0;
size_t end;
while (true)
{
move(position.line, position.column);
clrtoeol();
end = content.find_first_of('\n', pos);
std::string line = content.substr(pos, end - pos);
addstr(line.c_str());
if (end != std::string::npos)
{
position.line = position.line + 1;
position.column = 0;
pos = end + 1;
if (position.line >= max_y)
break;
}
else
{
position.column += line.length();
break;
}
}
if (position.line >= max_y)
break;
}
while (++position.line < max_y)
{
move(position.line, 0);
clrtoeol();
addch('~');
}
const WindowCoord& cursor_position = window.cursor_position();
move(cursor_position.line, cursor_position.column);
}
void init_ncurses()
{
initscr();
cbreak();
noecho();
nonl();
intrflush(stdscr, false);
keypad(stdscr, true);
curs_set(2);
}
void deinit_ncurses()
{
endwin();
}
struct prompt_aborted {};
std::string prompt(const std::string& text)
{
int max_x, max_y;
getmaxyx(stdscr, max_y, max_x);
move(max_y-1, 0);
addstr(text.c_str());
clrtoeol();
std::string result;
while(true)
{
char c = getch();
switch (c)
{
case '\r':
return result;
case 7:
if (not result.empty())
{
move(max_y - 1, text.length() + result.length() - 1);
addch(' ');
result.resize(result.length() - 1);
move(max_y - 1, text.length() + result.length());
refresh();
}
break;
case 27:
throw prompt_aborted();
default:
result += c;
addch(c);
refresh();
}
}
return result;
}
void print_status(const std::string& status)
{
int x,y;
getmaxyx(stdscr, y, x);
move(y-1, 0);
clrtoeol();
addstr(status.c_str());
}
void do_insert(Window& window)
{
print_status("-- INSERT --");
std::string inserted;
WindowCoord pos = window.cursor_position();
move(pos.line, pos.column);
refresh();
while(true)
{
char c = getch();
if (c == 27)
break;
window.insert(std::string() + c);
draw_window(window);
}
print_status("");
}
Window* current_window;
void edit(const CommandParameters& params)
{
if (params.size() != 1)
throw wrong_argument_count();
std::string filename = params[0];
Buffer* buffer = NULL;
try
{
buffer = create_buffer_from_file(filename);
}
catch (file_not_found& what)
{
print_status("new file " + filename);
buffer = new Buffer(filename);
}
current_window = buffer->get_or_create_window();
}
void write_buffer(const CommandParameters& params)
{
if (params.size() > 1)
throw wrong_argument_count();
Buffer& buffer = current_window->buffer();
std::string filename = params.empty() ? buffer.name() : params[0];
write_buffer_to_file(buffer, filename);
}
bool quit_requested = false;
void quit(const CommandParameters& params)
{
if (params.size() != 0)
throw wrong_argument_count();
quit_requested = true;
}
void show_buffer(const CommandParameters& params)
{
if (params.size() != 1)
throw wrong_argument_count();
Buffer* buffer = BufferManager::instance().get_buffer(params[0]);
if (not buffer)
print_status("buffer " + params[0] + " does not exists");
else
current_window = buffer->get_or_create_window();
}
CommandManager command_manager;
void do_command()
{
try
{
command_manager.execute(prompt(":"));
}
catch (prompt_aborted&) {}
catch (std::runtime_error& err)
{
print_status(err.what());
}
}
bool is_blank(char c)
{
return c == ' ' or c == '\t' or c == '\n';
}
Selection select_to_next_word(const BufferIterator& cursor)
{
BufferIterator end = cursor;
while (not end.is_end() and not is_blank(*end))
++end;
while (not end.is_end() and is_blank(*end))
++end;
return Selection(cursor, end);
}
Selection select_to_next_word_end(const BufferIterator& cursor)
{
BufferIterator end = cursor;
while (not end.is_end() and is_blank(*end))
++end;
while (not end.is_end() and not is_blank(*end))
++end;
return Selection(cursor, end);
}
Selection select_line(const BufferIterator& cursor)
{
BufferIterator begin = cursor;
while (not begin.is_begin() and *(begin -1) != '\n')
--begin;
BufferIterator end = cursor;
while (not end.is_end() and *end != '\n')
++end;
return Selection(begin, end + 1);
}
void do_search(Window& window)
{
try
{
std::string ex = prompt("/");
window.select(false, RegexSelector(ex));
}
catch (boost::regex_error&) {}
catch (prompt_aborted&) {}
}
std::unordered_map<char, std::function<void (Window& window, int count)>> keymap =
{
{ 'h', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(WindowCoord(0, -count)); window.empty_selections(); } },
{ 'j', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(WindowCoord(count, 0)); window.empty_selections(); } },
{ 'k', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(WindowCoord(-count, 0)); window.empty_selections(); } },
{ 'l', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(WindowCoord(0, count)); window.empty_selections(); } },
{ 'd', [](Window& window, int count) { window.erase(); window.empty_selections(); } },
{ 'c', [](Window& window, int count) { window.erase(); do_insert(window); } },
{ 'i', [](Window& window, int count) { do_insert(window); } },
{ ':', [](Window& window, int count) { do_command(); } },
{ ' ', [](Window& window, int count) { window.empty_selections(); } },
{ 'w', [](Window& window, int count) { do { window.select(false, select_to_next_word); } while(--count > 0); } },
{ 'W', [](Window& window, int count) { do { window.select(true, select_to_next_word); } while(--count > 0); } },
{ 'e', [](Window& window, int count) { do { window.select(false, select_to_next_word_end); } while(--count > 0); } },
{ 'E', [](Window& window, int count) { do { window.select(true, select_to_next_word_end); } while(--count > 0); } },
{ '.', [](Window& window, int count) { do { window.select(false, select_line); } while(--count > 0); } },
{ '/', [](Window& window, int count) { do_search(window); } },
{ 'u', [](Window& window, int count) { do { if (not window.undo()) { print_status("nothing left to undo"); break; } } while(--count > 0); } },
{ 'U', [](Window& window, int count) { do { if (not window.redo()) { print_status("nothing left to redo"); break; } } while(--count > 0); } },
};
int main()
{
init_ncurses();
command_manager.register_command(std::vector<std::string>{ "e", "edit" }, edit);
command_manager.register_command(std::vector<std::string>{ "q", "quit" }, quit);
command_manager.register_command(std::vector<std::string>{ "w", "write" }, write_buffer);
command_manager.register_command(std::vector<std::string>{ "b", "buffer" }, show_buffer);
try
{
auto buffer = new Buffer("<scratch>");
current_window = buffer->get_or_create_window();
draw_window(*current_window);
int count = 0;
while(not quit_requested)
{
char c = getch();
if (isdigit(c))
count = count * 10 + c - '0';
else
{
if (keymap.find(c) != keymap.end())
{
keymap[c](*current_window, count);
draw_window(*current_window);
}
count = 0;
}
}
deinit_ncurses();
}
catch (...)
{
deinit_ncurses();
throw;
}
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef REFERENCERESOLVER_CPP_
#define REFERENCERESOLVER_CPP_
#include <OthUtil.h>
#include <Keywords.h>
#include <Datatypes.h>
#include <ParsedCall.h>
#include <Function.h>
#include <OthFile.h>
#include <ConfigurationNode.h>
#include <Call.h>
#include <string>
#include <stack>
#include <vector>
#include <iostream>
using namespace std;
inline void resolveFunctionReferences(OthFile &file, Function &function);
inline void parseCallList(OthFile &file, Function &function, vector<ParsedCall> &callList, vector<Call> &newCallList, stack<vector<Call>*> &blockStack);
static stack<Function*> callStack_res;
static void pairAndEliminateBasicConflicts(vector<pair<OthFile*,Function*>> &newList, uint32_t lineN, OthFile &local,
ParsedCall &call, Call &newCall, vector<OthFile *> &resolvedFiles, vector<uint32_t> &resolvedIndices) {
bool isCastable = false;
Function *castf = NULL;
for (unsigned int i = 0; i < resolvedFiles.size(); i++) {
Function *f = &(resolvedFiles[i]->functionList[resolvedIndices[i]]);
if (f->nInputs == call.inParams.size() &&
f->nOutputs == call.outParams.size() &&
f->confNodes.size() == call.confNodes.size()) { // Verify arg lengths
// -->-->--> Resolve the potential match **important important** this is the recursive call <--<--<--
resolveFunctionReferences(*resolvedFiles[i], *f);
// *******
bool valid = true;
bool hasIncompat = false;
for (unsigned int inp = 0; inp < call.inParams.size(); inp++) {
uint8_t cv = f->r_inputs[inp].getCompatibilityValue(newCall.inputs[inp].datatype());
if (cv <= DT_CASTABLE) {
valid = false;
if (cv == DT_INCOMPATIBLE) hasIncompat = true;
}
}
if (!hasIncompat) {
isCastable = true;
castf = f;
}
if (valid) newList.push_back(make_pair(resolvedFiles[i], f));
}
}
parse_validate(!newList.empty(), lineN, isCastable ?
"Reference could not be resolved: " + call.callName + " (function '" + castf->toString() + "' is a close match but some parameters must be cast)" :
"Reference could not be resolved: " + call.callName + "; inputs/outputs/configuration nodes don't match any known functions");
}
static void findPotentialMatches(string name, uint32_t lineN, OthFile &local,
vector<OthFile *> &resolvedFiles, vector<uint32_t> &resolvedIndices) {
for (pair<string, pair<OthFile*,vector<uint32_t>>> p : local.function_imports) {
if (name == p.first) {
resolvedFiles.push_back(p.second.first);
resolvedIndices = p.second.second;
}
}
for (uint32_t i = 0; i < local.functionList.size(); i++) { // Load all local functions
Function f = local.functionList[i];
if (name == f.functionName) {
resolvedFiles.push_back(&local);
resolvedIndices.push_back(i);
}
}
parse_validate(!resolvedFiles.empty(), lineN, "Reference could not be resolved: " + name);
}
static VarReference resolveVarReference(bool isInput, string name, uint32_t lineN, OthFile &file, Function &function, Call &self, stack<vector<Call>*> blockStack) {
if (name == "?" || name == "^") return VarReference(); // Garbage/? pipe
// Constants (inputs only)
if (file.constant_imports.find(name) == file.constant_imports.end() ) { // Search local constants
for (unsigned int i = 0; i < file.constants.size(); i++) {
if (name == file.constants[i]) {
parse_validate(isInput, lineN, "Cannot output to a constant");
return VarReference(name, true, &file, i);
}
}
} else { // Search imports
pair<OthFile*,uint32_t> p = file.constant_imports[name];
parse_validate(isInput, lineN, "Cannot output to a constant");
return VarReference(name, true, p.first, p.second);
}
// Variables
if (file.variable_imports.find(name) == file.variable_imports.end() ) { // Search local variables
for (unsigned int i = 0; i < file.variables.size(); i++) {
if (name == file.variables[i]) {
return VarReference(name, true, &file, i);
}
}
} else { // Search imports
pair<OthFile*,uint32_t> p = file.variable_imports[name];
return VarReference(name, true, p.first, p.second);
}
// Function in/out/aux
for (unsigned int i = 0; i < function.variables.size(); i++) {
if (function.variables[i] == name) {
return VarReference(name, &file, &function, i);
}
}
// Self-reference (outputs only)
if (!isInput) {
for (unsigned int i = 0; i < self.inputs.size(); i++) {
if (self.inputs[i].name == name) return VarReference(name, &file, &function, &self, i, self.inputs[i].datatype(), true);
}
} else { // Pipes (inputs only)
while (true) {
parse_validate(!blockStack.empty(), lineN, "Variable or pipe reference could not be resolved: " + name);
vector<Call> * callScope = blockStack.top(); blockStack.pop();
for (int i = callScope->size() - 1; i >= 0; i--) {
Call * currentCall = &(callScope->at(i));
for (uint32_t j = 0; j < currentCall->outputs.size(); j++) {
VarReference v = currentCall->outputs[j];
if (v.name == name) {
return VarReference(name, &file, &function, currentCall, j, v.datatype(), false);
}
}
}
}
}
parse_validate(false, lineN, "Variable or pipe reference could not be resolved: " + name);
return VarReference();
}
static void setCallInputs(OthFile &file, Function &function, stack<vector<Call>*> &blockStack, Call &call, ParsedCall &oldCall) {
for (unsigned int i = 0; i < oldCall.inParams.size(); i++) {
VarReference v = resolveVarReference(true, oldCall.inParams[i], oldCall.lineN, file, function, call, blockStack);
call.inputs.push_back(v);
parse_validate(!(v.isOptional() && function.variable_defaults[i].empty()), call.lineN,
"Optional input specified for non-optional parameter");
}
}
static void defineConfNodes(OthFile &file, Function &function, stack<vector<Call>*> &blockStack, Call &call, ParsedCall &oldCall) {
for (unsigned int i = 0; i < oldCall.confNodes.size(); i++) {
vector<ParsedCall> node = oldCall.confNodes[i];
vector<Call> newCallList;
string word = "";
bool isOneWord = node.size() == 1 && qualifiesAsKeyword_strict(node[0]);
if (isOneWord) word = node[0].callName;
uint8_t declaredMode = call.callReference->confNode_types[i];
bool isReference = false;
uint32_t refIndex;
for (refIndex = 0; refIndex < function.confNodes.size(); refIndex++) {
if (word == function.confNodes[i]) {
parse_validate(function.confNode_types[i] == declaredMode, call.lineN, "ConfNode reference doesn't match declared type: " + word);
isReference = true;
break;
}
}
if (!isReference) {
if (declaredMode == CHAIN || declaredMode == SOUT_CHAIN) {
parseCallList(file, function, node, newCallList, blockStack);
} else {
parse_validate(isOneWord, call.lineN, "Configuration node is not a valid " + string(cn_kw(declaredMode)) + " expression");
}
}
ConfNode cn = ConfNode(isReference, declaredMode, newCallList);
if (isReference) {
cn.reference = VarReference(&file, &function, refIndex);
} else if (call.callReference->confNode_types[i] == SOUT_CHAIN) {
Call lastCall = newCallList[newCallList.size() - 1];
parse_validate(lastCall.outputs.size() == 1, lastCall.lineN, "Last call in an SOUT_CHAIN must have one output");
cn.type = lastCall.outputs[0].datatype(); // TODO this might be problematic (datatype, not satisfied datatype)
} else if (declaredMode == DATATYPE) {
cn.type = evaluateDatatypeWithoutAbstracts(word, call.lineN, "Invalid DATATYPE node: " + word);
} else if (declaredMode == CONSTANT) {
cn.reference = resolveVarReference(false, word, call.lineN, file, function, call, blockStack);
parse_validate(cn.reference.isConstant(), call.lineN, "CONSTANT " + word + " does not reference a constant");
}
call.confNodes.push_back(cn);
}
}
inline void parseCallList(OthFile &file, Function &function, vector<ParsedCall> &callList, vector<Call> &newCallList, stack<vector<Call>*> &blockStack) {
for (ParsedCall &call : callList) {// TODO add built-in functions
string name = call.callName;
vector<OthFile *> resolvedFiles;
vector<uint32_t> resolvedIndices;
Call newCall;
newCall.lineN = call.lineN;
newCall.isBlockStart = call.isBlockStart; //TODO and we need to process a special case!!
newCall.isBlockEnd = call.isBlockEnd; //TODO and we need to process another special case!!
setCallInputs(file, function, blockStack, newCall, call);
findPotentialMatches(name, call.lineN, file, resolvedFiles, resolvedIndices);
vector<pair<OthFile*,Function*>> resolved;
pairAndEliminateBasicConflicts(resolved, call.lineN, file, call, newCall, resolvedFiles, resolvedIndices);
parse_validate(resolved.size() == 1, call.lineN, "Ambiguous reference (multiple matches) for call " + call.callName);
newCall.callReference = resolved[0].second;
defineConfNodes(file, function, blockStack, newCall, call);
blockStack.top()->push_back(newCall);
}
}
inline void resolveFunctionReferences(OthFile &file, Function &function) {
if (function.resolved) return; // TODO also check if it's already in the call stack (recursion) and kill static recursion
// Split up variables
for (unsigned int i = 0; i < function.variables.size(); i++) {
if (i < function.nInputs) {
function.r_inputs.push_back(function.variable_types[i]);
} else if (i < function.nInputs + function.nOutputs) {
function.r_outputs.push_back(function.variable_types[i]);
} else {
function.r_aux.push_back(function.variable_types[i]);
}
}
callStack_res.push(&function);
vector<Call> newCallList;
stack<vector<Call>*> blockStack;
blockStack.push(&newCallList);
parseCallList(file, function, function.callList, newCallList, blockStack);
callStack_res.pop();
function.resolved = true;
}
#endif
<commit_msg>Forgot to set type for CONSTANT node Add setCallOutputs<commit_after>#ifndef REFERENCERESOLVER_CPP_
#define REFERENCERESOLVER_CPP_
#include <OthUtil.h>
#include <Keywords.h>
#include <Datatypes.h>
#include <ParsedCall.h>
#include <Function.h>
#include <OthFile.h>
#include <ConfigurationNode.h>
#include <Call.h>
#include <string>
#include <stack>
#include <vector>
#include <iostream>
using namespace std;
inline void resolveFunctionReferences(OthFile &file, Function &function);
inline void parseCallList(OthFile &file, Function &function, vector<ParsedCall> &callList, vector<Call> &newCallList, stack<vector<Call>*> &blockStack);
static stack<Function*> callStack_res;
static void pairAndEliminateBasicConflicts(vector<pair<OthFile*,Function*>> &newList, uint32_t lineN, OthFile &local,
ParsedCall &call, Call &newCall, vector<OthFile *> &resolvedFiles, vector<uint32_t> &resolvedIndices) {
bool isCastable = false;
Function *castf = NULL;
for (unsigned int i = 0; i < resolvedFiles.size(); i++) {
Function *f = &(resolvedFiles[i]->functionList[resolvedIndices[i]]);
if (f->nInputs == call.inParams.size() &&
f->nOutputs == call.outParams.size() &&
f->confNodes.size() == call.confNodes.size()) { // Verify arg lengths
// -->-->--> Resolve the potential match **important important** this is the recursive call <--<--<--
resolveFunctionReferences(*resolvedFiles[i], *f);
// *******
bool valid = true;
bool hasIncompat = false;
for (unsigned int inp = 0; inp < call.inParams.size(); inp++) {
uint8_t cv = f->r_inputs[inp].getCompatibilityValue(newCall.inputs[inp].datatype());
if (cv <= DT_CASTABLE) {
valid = false;
if (cv == DT_INCOMPATIBLE) hasIncompat = true;
}
}
if (!hasIncompat) {
isCastable = true;
castf = f;
}
if (valid) newList.push_back(make_pair(resolvedFiles[i], f));
}
}
parse_validate(!newList.empty(), lineN, isCastable ?
"Reference could not be resolved: " + call.callName + " (function '" + castf->toString() + "' is a close match but some parameters must be cast)" :
"Reference could not be resolved: " + call.callName + "; inputs/outputs/configuration nodes don't match any known functions");
}
static void findPotentialMatches(string name, uint32_t lineN, OthFile &local,
vector<OthFile *> &resolvedFiles, vector<uint32_t> &resolvedIndices) {
for (pair<string, pair<OthFile*,vector<uint32_t>>> p : local.function_imports) {
if (name == p.first) {
resolvedFiles.push_back(p.second.first);
resolvedIndices = p.second.second;
}
}
for (uint32_t i = 0; i < local.functionList.size(); i++) { // Load all local functions
Function f = local.functionList[i];
if (name == f.functionName) {
resolvedFiles.push_back(&local);
resolvedIndices.push_back(i);
}
}
parse_validate(!resolvedFiles.empty(), lineN, "Reference could not be resolved: " + name);
}
static VarReference resolveVarReference(bool isInput, string name, uint32_t lineN, OthFile &file, Function &function, Call &self, stack<vector<Call>*> blockStack) {
if (name == "?" || name == "^") return VarReference(); // Garbage/? pipe
// Constants (inputs only)
if (file.constant_imports.find(name) == file.constant_imports.end() ) { // Search local constants
for (unsigned int i = 0; i < file.constants.size(); i++) {
if (name == file.constants[i]) {
parse_validate(isInput, lineN, "Cannot output to a constant");
return VarReference(name, true, &file, i);
}
}
} else { // Search imports
pair<OthFile*,uint32_t> p = file.constant_imports[name];
parse_validate(isInput, lineN, "Cannot output to a constant");
return VarReference(name, true, p.first, p.second);
}
// Variables
if (file.variable_imports.find(name) == file.variable_imports.end() ) { // Search local variables
for (unsigned int i = 0; i < file.variables.size(); i++) {
if (name == file.variables[i]) {
return VarReference(name, true, &file, i);
}
}
} else { // Search imports
pair<OthFile*,uint32_t> p = file.variable_imports[name];
return VarReference(name, true, p.first, p.second);
}
// Function in/out/aux
for (unsigned int i = 0; i < function.variables.size(); i++) {
if (function.variables[i] == name) {
return VarReference(name, &file, &function, i);
}
}
// Self-reference (outputs only)
if (!isInput) {
for (unsigned int i = 0; i < self.inputs.size(); i++) {
if (self.inputs[i].name == name) return VarReference(name, &file, &function, &self, i, self.inputs[i].datatype(), true);
}
} else { // Pipes (inputs only)
while (true) {
parse_validate(!blockStack.empty(), lineN, "Variable or pipe reference could not be resolved: " + name);
vector<Call> * callScope = blockStack.top(); blockStack.pop();
for (int i = callScope->size() - 1; i >= 0; i--) {
Call * currentCall = &(callScope->at(i));
for (uint32_t j = 0; j < currentCall->outputs.size(); j++) {
VarReference v = currentCall->outputs[j];
if (v.name == name) {
return VarReference(name, &file, &function, currentCall, j, v.datatype(), false);
}
}
}
}
}
parse_validate(false, lineN, "Variable or pipe reference could not be resolved: " + name);
return VarReference();
}
static void setCallOutputs(OthFile &file, Function &function, stack<vector<Call>*> &blockStack, Call &call, ParsedCall &oldCall) {
for (unsigned int i = 0; i < oldCall.outParams.size(); i++) {
}
}
static void setCallInputs(OthFile &file, Function &function, stack<vector<Call>*> &blockStack, Call &call, ParsedCall &oldCall) {
for (unsigned int i = 0; i < oldCall.inParams.size(); i++) {
VarReference v = resolveVarReference(true, oldCall.inParams[i], oldCall.lineN, file, function, call, blockStack);
call.inputs.push_back(v);
parse_validate(!(v.isOptional() && function.variable_defaults[i].empty()), call.lineN,
"Optional input specified for non-optional parameter");
}
}
static void defineConfNodes(OthFile &file, Function &function, stack<vector<Call>*> &blockStack, Call &call, ParsedCall &oldCall) {
for (unsigned int i = 0; i < oldCall.confNodes.size(); i++) {
vector<ParsedCall> node = oldCall.confNodes[i];
vector<Call> newCallList;
string word = "";
bool isOneWord = node.size() == 1 && qualifiesAsKeyword_strict(node[0]);
if (isOneWord) word = node[0].callName;
uint8_t declaredMode = call.callReference->confNode_types[i];
bool isReference = false;
uint32_t refIndex;
for (refIndex = 0; refIndex < function.confNodes.size(); refIndex++) {
if (word == function.confNodes[i]) {
parse_validate(function.confNode_types[i] == declaredMode, call.lineN, "ConfNode reference doesn't match declared type: " + word);
isReference = true;
break;
}
}
if (!isReference) {
if (declaredMode == CHAIN || declaredMode == SOUT_CHAIN) {
parseCallList(file, function, node, newCallList, blockStack);
} else {
parse_validate(isOneWord, call.lineN, "Configuration node is not a valid " + string(cn_kw(declaredMode)) + " expression");
}
}
ConfNode cn = ConfNode(isReference, declaredMode, newCallList);
if (isReference) {
cn.reference = VarReference(&file, &function, refIndex);
} else if (call.callReference->confNode_types[i] == SOUT_CHAIN) {
Call lastCall = newCallList[newCallList.size() - 1];
parse_validate(lastCall.outputs.size() == 1, lastCall.lineN, "Last call in an SOUT_CHAIN must have one output");
cn.type = lastCall.outputs[0].datatype(); // TODO this might be problematic (datatype, not satisfied datatype)
} else if (declaredMode == DATATYPE) {
cn.type = evaluateDatatypeWithoutAbstracts(word, call.lineN, "Invalid DATATYPE node: " + word);
} else if (declaredMode == CONSTANT) {
cn.reference = resolveVarReference(false, word, call.lineN, file, function, call, blockStack);
cn.type = cn.reference.datatype();
parse_validate(cn.reference.isConstant(), call.lineN, "CONSTANT " + word + " does not reference a constant");
}
call.confNodes.push_back(cn);
}
}
inline void parseCallList(OthFile &file, Function &function, vector<ParsedCall> &callList, vector<Call> &newCallList, stack<vector<Call>*> &blockStack) {
for (ParsedCall &call : callList) {// TODO add built-in functions
string name = call.callName;
vector<OthFile *> resolvedFiles;
vector<uint32_t> resolvedIndices;
Call newCall;
newCall.lineN = call.lineN;
newCall.isBlockStart = call.isBlockStart; //TODO and we need to process a special case!!
newCall.isBlockEnd = call.isBlockEnd; //TODO and we need to process another special case!!
setCallInputs(file, function, blockStack, newCall, call);
findPotentialMatches(name, call.lineN, file, resolvedFiles, resolvedIndices);
vector<pair<OthFile*,Function*>> resolved;
pairAndEliminateBasicConflicts(resolved, call.lineN, file, call, newCall, resolvedFiles, resolvedIndices);
parse_validate(resolved.size() == 1, call.lineN, "Ambiguous reference (multiple matches) for call " + call.callName);
newCall.callReference = resolved[0].second;
defineConfNodes(file, function, blockStack, newCall, call);
setCallOutputs(file, function, blockStack, newCall, call);
blockStack.top()->push_back(newCall);
}
}
inline void resolveFunctionReferences(OthFile &file, Function &function) {
if (function.resolved) return; // TODO also check if it's already in the call stack (recursion) and kill static recursion
// Split up variables
for (unsigned int i = 0; i < function.variables.size(); i++) {
if (i < function.nInputs) {
function.r_inputs.push_back(function.variable_types[i]);
} else if (i < function.nInputs + function.nOutputs) {
function.r_outputs.push_back(function.variable_types[i]);
} else {
function.r_aux.push_back(function.variable_types[i]);
}
}
callStack_res.push(&function);
vector<Call> newCallList;
stack<vector<Call>*> blockStack;
blockStack.push(&newCallList);
parseCallList(file, function, function.callList, newCallList, blockStack);
callStack_res.pop();
function.resolved = true;
}
#endif
<|endoftext|>
|
<commit_before>
#ifdef __MINGW32__
#define SDL_MAIN_HANDLED 1
#endif
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <deque>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
using namespace std;
const int w = 480;
const int h = 640;
const int fsize = 32;
const int cgap0 = 15;
const int cgap1 = cgap0 + 180;
const int cgap2 = cgap1 + 160;
const int rgap0 = 10;
const int rgap1 = rgap0 + 50;
const int rgap = 50;
const int hposx = 40;
const int hposy = 520;
const int hh = 5;
const int hrpoy = 590;
const int maxhist = 40*1000;
const int nintevals = 7;
int intervals[nintevals] = { 1000, 2000, 3000, 5000, 10000, 20000, 30000 };
const char* fontfile = "OpenSans-Semibold.ttf";
void rendersurface(SDL_Renderer* renderer, SDL_Surface* s, int x, int y) {
SDL_Rect dest;
dest.x = x;
dest.y = y;
SDL_Texture* t = SDL_CreateTextureFromSurface(renderer, s);
SDL_QueryTexture(t, NULL, NULL, &dest.w, &dest.h);
SDL_RenderCopy(renderer, t, NULL, &dest);
SDL_DestroyTexture(t);
}
void drawtext(SDL_Renderer* renderer, TTF_Font* font,
const char* text, int x, int y) {
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_Surface* s = TTF_RenderText_Blended(font, text, { 255, 255, 255, 0 });
rendersurface(renderer, s, x, y);
SDL_FreeSurface(s);
}
void drawsep(SDL_Renderer* renderer, SDL_Rect* r) {
SDL_SetRenderDrawColor(renderer, 100, 100, 100, 255);
SDL_RenderFillRect(renderer, r);
}
void updatedata(Uint32 tick, deque<Uint32>& data) {
while(data.size() > 0 && data.back() + maxhist < tick) {
data.pop_back();
}
}
int count(deque<Uint32>& data, Uint32 tick, int offset) {
int c = 0;
Uint32 t;
for(; c < data.size(); c++) {
t = data[c];
if(t + offset < tick) break;
}
return c;
}
int updateresults(Uint32 tick, deque<Uint32>& data,
double *currentscores, double *topscores,
bool onlytop = true) {
int times;
double rate;
for(int i = 0; i < nintevals; i++) {
times = count(data, tick, intervals[i]);
rate = times/(double)(intervals[i]) * 1000.0;
if(rate > topscores[i]) {
topscores[i] = rate;
}
if(!onlytop) {
currentscores[i] = rate;
}
}
}
void drawhist(SDL_Renderer* renderer, TTF_Font* font,
deque<Uint32>& data, Uint32 tick) {
const int linew = 4;
const int histw = 400;
const int histt = 1000;
int t, d;
SDL_Rect r = { hposx, hposy, linew, hh };
SDL_SetRenderDrawColor(renderer, 150, 255, 150, 255);
for(int i = 0; i < data.size(); i++) {
d = tick - data[i];
t = max(0, d);
if( t >= histt ) break;
r.x = hposx + t * histw / histt;
SDL_RenderFillRect(renderer, &r);
}
}
void drawdata(SDL_Renderer* renderer, TTF_Font* font,
double *currentscores, double *topscores,
int time) {
const int seph = 2;
const int bsz = 1024;
static char buffer[bsz];
int posy, i;
SDL_Rect r;
r.x = 0;
r.w = w;
r.h = seph;
r.y = rgap1;
drawsep(renderer, &r);
drawtext(renderer, font, "Interval", cgap0, rgap0);
drawtext(renderer, font, "Rate", cgap1, rgap0);
drawtext(renderer, font, "Max", cgap2, rgap0);
for(i = 0; i < nintevals; i++) {
posy = i*rgap + rgap1;
snprintf(buffer, bsz, "%d", intervals[i]/1000);
drawtext(renderer, font, buffer, cgap0, posy);
snprintf(buffer, bsz, "%3.2lf", currentscores[i]);
drawtext(renderer, font, buffer, cgap1, posy);
snprintf(buffer, bsz, "%3.2lf", topscores[i]);
drawtext(renderer, font, buffer, cgap2, posy);
r.y = posy + rgap - seph;
drawsep(renderer, &r);
}
posy = i*rgap + rgap1;
int m = time / 60000;
int sec = (time / 1000) % 60;
int msec = time % 1000;
snprintf(buffer, bsz, "%02d:%02d.%02d", m, sec, msec/10);
drawtext(renderer, font, buffer, cgap0, posy);
snprintf(buffer, bsz, "%d", (int)currentscores[0]);
drawtext(renderer, font, buffer, cgap0, hrpoy);
}
void draw(SDL_Renderer* renderer, TTF_Font* font,
deque<Uint32>& data, Uint32 tick,
double *currentscores, double *topscores,
int time) {
SDL_RenderClear(renderer);
drawdata(renderer, font, currentscores, topscores, time);
drawhist(renderer, font, data, tick);
SDL_RenderPresent(renderer);
}
void drawpaderror(SDL_Renderer* renderer, TTF_Font* font) {
SDL_RenderClear(renderer);
drawtext(renderer, font, "No gamepad found :(", cgap0, rgap0);
SDL_RenderPresent(renderer);
}
void drawselbtn(SDL_Renderer* renderer, TTF_Font* font) {
SDL_RenderClear(renderer);
drawtext(renderer, font, "Press a button to mash...", cgap0, rgap0);
SDL_RenderPresent(renderer);
}
void getpad(int padnum, SDL_Joystick* &joystick, SDL_JoystickID& instanceid) {
int npads = SDL_NumJoysticks();
if(npads <= 0) return;
joystick = SDL_JoystickOpen(padnum);
if(joystick) {
instanceid = SDL_JoystickInstanceID(joystick);
}
}
void resetpad(SDL_Joystick* &joystick, SDL_JoystickID& instanceid) {
SDL_JoystickClose(joystick);
joystick = NULL;
instanceid = -1;
}
int main(int argc, char* argv[]) {
const int padnum = 0;
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK)) {
cerr << "SDL_Init failed: " << SDL_GetError() << endl;
exit(-1);
}
TTF_Init();
TTF_Font* font = TTF_OpenFont(fontfile, fsize);
if(!font) {
cerr << "TTF_OpenFont failed: " << SDL_GetError() << endl;
exit(-1);
}
SDL_JoystickID instanceid = -1;
SDL_Joystick *joystick = NULL;
getpad(padnum, joystick, instanceid);
SDL_Window *window;
window = SDL_CreateWindow("Button mashing v1.1 by qety1",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
w, h, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1,
SDL_RENDERER_ACCELERATED |
SDL_RENDERER_PRESENTVSYNC);
const int updaterate = 100;
const Uint32 nullbutton = 255;
bool running = true;
bool hidden = true;
SDL_Event event;
Uint8 button = nullbutton;
Uint32 tick, ticksaved, tickfirst;
deque<Uint32> data;
double topscores[nintevals] = { 0, 0, 0, 0, 0, 0, 0 };
double currentscores[nintevals] = { 0, 0, 0, 0, 0, 0, 0 };
tickfirst = SDL_GetTicks();
ticksaved = 0;
while(running) {
while(SDL_PollEvent(&event) > 0) {
switch(event.type) {
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_SHOWN:
hidden = false;
break;
case SDL_WINDOWEVENT_HIDDEN:
hidden = true;
break;
}
break;
case SDL_JOYBUTTONDOWN:
if(button == nullbutton) {
button = event.jbutton.button;
} else if(button == event.jbutton.button) {
data.push_front(event.jbutton.timestamp);
}
break;
case SDL_JOYDEVICEADDED:
if(!joystick) {
getpad(padnum, joystick, instanceid);
}
break;
case SDL_JOYDEVICEREMOVED:
if(joystick && event.jdevice.which == instanceid) {
resetpad(joystick, instanceid);
button = nullbutton;
}
break;
case SDL_QUIT:
running = false;
break;
}
}
tick = SDL_GetTicks();
if(tick > ticksaved + updaterate) {
updateresults(tick, data, currentscores, topscores, false);
ticksaved = tick;
} else {
updateresults(tick, data, currentscores, topscores);
}
if(!hidden) {
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
if(button == nullbutton && joystick) {
drawselbtn(renderer, font);
} else if(joystick) {
draw(renderer, font, data, tick,
currentscores, topscores, tick-tickfirst);
} else {
drawpaderror(renderer, font);
}
}
}
resetpad(joystick, instanceid);
TTF_CloseFont(font);
TTF_Quit();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
<commit_msg>Minimized delay.<commit_after>
#ifdef __MINGW32__
#define SDL_MAIN_HANDLED 1
#endif
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <deque>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
using namespace std;
const int w = 480;
const int h = 640;
const int fsize = 32;
const int cgap0 = 15;
const int cgap1 = cgap0 + 180;
const int cgap2 = cgap1 + 160;
const int rgap0 = 10;
const int rgap1 = rgap0 + 50;
const int rgap = 50;
const int hposx = 40;
const int hposy = 520;
const int hh = 5;
const int hrpoy = 590;
const int maxhist = 40*1000;
const int nintevals = 7;
int intervals[nintevals] = { 1000, 2000, 3000, 5000, 10000, 20000, 30000 };
const char* fontfile = "OpenSans-Semibold.ttf";
void rendersurface(SDL_Renderer* renderer, SDL_Surface* s, int x, int y) {
SDL_Rect dest;
dest.x = x;
dest.y = y;
SDL_Texture* t = SDL_CreateTextureFromSurface(renderer, s);
SDL_QueryTexture(t, NULL, NULL, &dest.w, &dest.h);
SDL_RenderCopy(renderer, t, NULL, &dest);
SDL_DestroyTexture(t);
}
void drawtext(SDL_Renderer* renderer, TTF_Font* font,
const char* text, int x, int y) {
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_Surface* s = TTF_RenderText_Blended(font, text, { 255, 255, 255, 0 });
rendersurface(renderer, s, x, y);
SDL_FreeSurface(s);
}
void drawsep(SDL_Renderer* renderer, SDL_Rect* r) {
SDL_SetRenderDrawColor(renderer, 100, 100, 100, 255);
SDL_RenderFillRect(renderer, r);
}
void updatedata(Uint32 tick, deque<Uint32>& data) {
while(data.size() > 0 && data.back() + maxhist < tick) {
data.pop_back();
}
}
int count(deque<Uint32>& data, Uint32 tick, int offset) {
int c = 0;
Uint32 t;
for(; c < data.size(); c++) {
t = data[c];
if(t + offset < tick) break;
}
return c;
}
int updateresults(Uint32 tick, deque<Uint32>& data,
double *currentscores, double *topscores,
bool onlytop = true) {
int times;
double rate;
for(int i = 0; i < nintevals; i++) {
times = count(data, tick, intervals[i]);
rate = times/(double)(intervals[i]) * 1000.0;
if(rate > topscores[i]) {
topscores[i] = rate;
}
if(!onlytop) {
currentscores[i] = rate;
}
}
}
void drawhist(SDL_Renderer* renderer, TTF_Font* font,
deque<Uint32>& data, Uint32 tick) {
const int linew = 4;
const int histw = 400;
const int histt = 1000;
int t, d;
SDL_Rect r = { hposx, hposy, linew, hh };
SDL_SetRenderDrawColor(renderer, 150, 255, 150, 255);
for(int i = 0; i < data.size(); i++) {
d = tick - data[i];
t = max(0, d);
if( t >= histt ) break;
r.x = hposx + t * histw / histt;
SDL_RenderFillRect(renderer, &r);
}
}
void drawdata(SDL_Renderer* renderer, TTF_Font* font,
double *currentscores, double *topscores,
int time) {
const int seph = 2;
const int bsz = 1024;
static char buffer[bsz];
int posy, i;
SDL_Rect r;
r.x = 0;
r.w = w;
r.h = seph;
r.y = rgap1;
drawsep(renderer, &r);
drawtext(renderer, font, "Interval", cgap0, rgap0);
drawtext(renderer, font, "Rate", cgap1, rgap0);
drawtext(renderer, font, "Max", cgap2, rgap0);
for(i = 0; i < nintevals; i++) {
posy = i*rgap + rgap1;
snprintf(buffer, bsz, "%d", intervals[i]/1000);
drawtext(renderer, font, buffer, cgap0, posy);
snprintf(buffer, bsz, "%3.2lf", currentscores[i]);
drawtext(renderer, font, buffer, cgap1, posy);
snprintf(buffer, bsz, "%3.2lf", topscores[i]);
drawtext(renderer, font, buffer, cgap2, posy);
r.y = posy + rgap - seph;
drawsep(renderer, &r);
}
posy = i*rgap + rgap1;
int m = time / 60000;
int sec = (time / 1000) % 60;
int msec = time % 1000;
snprintf(buffer, bsz, "%02d:%02d.%02d", m, sec, msec/10);
drawtext(renderer, font, buffer, cgap0, posy);
snprintf(buffer, bsz, "%d", (int)currentscores[0]);
drawtext(renderer, font, buffer, cgap0, hrpoy);
}
void draw(SDL_Renderer* renderer, TTF_Font* font,
deque<Uint32>& data, Uint32 tick,
double *currentscores, double *topscores,
int time) {
SDL_RenderClear(renderer);
drawdata(renderer, font, currentscores, topscores, time);
drawhist(renderer, font, data, tick);
SDL_RenderPresent(renderer);
}
void drawpaderror(SDL_Renderer* renderer, TTF_Font* font) {
SDL_RenderClear(renderer);
drawtext(renderer, font, "No gamepad found :(", cgap0, rgap0);
SDL_RenderPresent(renderer);
}
void drawselbtn(SDL_Renderer* renderer, TTF_Font* font) {
SDL_RenderClear(renderer);
drawtext(renderer, font, "Press a button to mash...", cgap0, rgap0);
SDL_RenderPresent(renderer);
}
void getpad(int padnum, SDL_Joystick* &joystick, SDL_JoystickID& instanceid) {
int npads = SDL_NumJoysticks();
if(npads <= 0) return;
joystick = SDL_JoystickOpen(padnum);
if(joystick) {
instanceid = SDL_JoystickInstanceID(joystick);
}
}
void resetpad(SDL_Joystick* &joystick, SDL_JoystickID& instanceid) {
SDL_JoystickClose(joystick);
joystick = NULL;
instanceid = -1;
}
int main(int argc, char* argv[]) {
const int padnum = 0;
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK)) {
cerr << "SDL_Init failed: " << SDL_GetError() << endl;
exit(-1);
}
TTF_Init();
TTF_Font* font = TTF_OpenFont(fontfile, fsize);
if(!font) {
cerr << "TTF_OpenFont failed: " << SDL_GetError() << endl;
exit(-1);
}
SDL_JoystickID instanceid = -1;
SDL_Joystick *joystick = NULL;
getpad(padnum, joystick, instanceid);
SDL_Window *window;
window = SDL_CreateWindow("Button mashing v1.1 by qety1",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
w, h, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1,
SDL_RENDERER_ACCELERATED |
SDL_RENDERER_PRESENTVSYNC);
const int updaterate = 100;
const Uint32 nullbutton = 255;
bool running = true;
bool hidden = true;
SDL_Event event;
Uint8 button = nullbutton;
Uint32 tick, ticksaved, tickfirst;
deque<Uint32> data;
double topscores[nintevals] = { 0, 0, 0, 0, 0, 0, 0 };
double currentscores[nintevals] = { 0, 0, 0, 0, 0, 0, 0 };
tickfirst = SDL_GetTicks();
ticksaved = 0;
while(running) {
while(SDL_PollEvent(&event) > 0) {
switch(event.type) {
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_SHOWN:
hidden = false;
break;
case SDL_WINDOWEVENT_HIDDEN:
hidden = true;
break;
}
break;
case SDL_JOYBUTTONDOWN:
if(button == nullbutton) {
button = event.jbutton.button;
} else if(button == event.jbutton.button) {
data.push_front(event.jbutton.timestamp);
}
break;
case SDL_JOYDEVICEADDED:
if(!joystick) {
getpad(padnum, joystick, instanceid);
}
break;
case SDL_JOYDEVICEREMOVED:
if(joystick && event.jdevice.which == instanceid) {
resetpad(joystick, instanceid);
button = nullbutton;
}
break;
case SDL_QUIT:
running = false;
break;
}
}
tick = SDL_GetTicks();
if(tick > ticksaved + updaterate) {
updateresults(tick, data, currentscores, topscores, false);
ticksaved = tick;
} else {
updateresults(tick, data, currentscores, topscores);
}
if(!hidden) {
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
if(button == nullbutton && joystick) {
drawselbtn(renderer, font);
} else if(joystick) {
draw(renderer, font, data, tick,
currentscores, topscores, tick-tickfirst);
} else {
drawpaderror(renderer, font);
}
} else {
SDL_Delay(updaterate);
}
}
resetpad(joystick, instanceid);
TTF_CloseFont(font);
TTF_Quit();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
<|endoftext|>
|
<commit_before>#include "BiLM_NPLM.h"
#include "neuralLM.h"
#include "vocabulary.h"
namespace Moses {
BilingualLM_NPLM::BilingualLM_NPLM(const std::string &line)
: BilingualLM(line),
premultiply(true),
factored(false),
neuralLM_cache(1000000) {
if (!NULL_overwrite) {
NULL_string = "<null>"; //Default null value for nplm
}
FactorCollection& factorFactory = FactorCollection::Instance(); // To add null word.
const Factor* NULL_factor = factorFactory.AddFactor(NULL_string);
NULL_word.SetFactor(0, NULL_factor);
}
float BilingualLM_NPLM::Score(std::vector<int>& source_words, std::vector<int>& target_words) const {
source_words.reserve(source_ngrams+target_ngrams+1);
source_words.insert( source_words.end(), target_words.begin(), target_words.end() );
return m_neuralLM->lookup_ngram(source_words);
}
const Word& BilingualLM_NPLM::getNullWord() const {
return NULL_word;
}
int BilingualLM_NPLM::getNeuralLMId(const Word& word, bool is_source_word) const {
initSharedPointer();
boost::unordered_map<const Factor*, int>::iterator it;
const Factor* factor = word.GetFactor(word_factortype);
it = neuralLMids.find(factor);
//If we know the word return immediately
if (it != neuralLMids.end()){
return it->second;
}
//If we don't know the word and we aren't factored, return the word.
if (!factored) {
return unknown_word_id;
}
//Else try to get a pos_factor
const Factor* pos_factor = word.GetFactor(pos_factortype);
it = neuralLMids.find(pos_factor);
if (it != neuralLMids.end()){
return it->second;
} else {
return unknown_word_id;
}
}
void BilingualLM_NPLM::initSharedPointer() const {
if (!m_neuralLM.get()) {
m_neuralLM.reset(new nplm::neuralLM(*m_neuralLM_shared));
}
}
void BilingualLM_NPLM::SetParameter(const std::string& key, const std::string& value) {
if (key == "target_ngrams") {
target_ngrams = Scan<int>(value);
} else if (key == "source_ngrams") {
source_ngrams = Scan<int>(value);
} else if (key == "factored") {
factored = Scan<bool>(value);
} else if (key == "pos_factor") {
pos_factortype = Scan<FactorType>(value);
} else if (key == "cache_size") {
neuralLM_cache = atoi(value.c_str());
} else if (key == "premultiply") {
premultiply = Scan<bool>(value);
} else if (key == "null_word") {
NULL_string = value;
NULL_overwrite = true;
} else {
BilingualLM::SetParameter(key, value);
}
}
void BilingualLM_NPLM::loadModel() {
m_neuralLM_shared = new nplm::neuralLM(m_filePath, premultiply); //Default premultiply= true
int ngram_order = target_ngrams + source_ngrams + 1;
UTIL_THROW_IF2(
ngram_order != m_neuralLM_shared->get_order(),
"Wrong order of neuralLM: LM has " << m_neuralLM_shared->get_order() <<
", but Moses expects " << ngram_order);
m_neuralLM_shared->set_cache(neuralLM_cache); //Default 1000000
unknown_word_id = m_neuralLM_shared->lookup_word("<unk>");
//Setup factor -> NeuralLMId cache
FactorCollection& factorFactory = FactorCollection::Instance(); //To do the conversion from string to vocabID
const nplm::vocabulary& vocab = m_neuralLM_shared->get_vocabulary();
const boost::unordered_map<std::string, int>& neuraLMvocabmap = vocab.get_idmap();
boost::unordered_map<std::string, int>::const_iterator it;
for (it = neuraLMvocabmap.cbegin(); it != neuraLMvocabmap.cend(); it++) {
std::string raw_word = it->first;
int neuralLMid = it->second;
const Factor * factor = factorFactory.AddFactor(raw_word);
neuralLMids.insert(std::make_pair(factor, neuralLMid));
}
}
} // namespace Moses
<commit_msg>floor score of bilingualNPLM<commit_after>#include "BiLM_NPLM.h"
#include "neuralLM.h"
#include "vocabulary.h"
namespace Moses {
BilingualLM_NPLM::BilingualLM_NPLM(const std::string &line)
: BilingualLM(line),
premultiply(true),
factored(false),
neuralLM_cache(1000000) {
if (!NULL_overwrite) {
NULL_string = "<null>"; //Default null value for nplm
}
FactorCollection& factorFactory = FactorCollection::Instance(); // To add null word.
const Factor* NULL_factor = factorFactory.AddFactor(NULL_string);
NULL_word.SetFactor(0, NULL_factor);
}
float BilingualLM_NPLM::Score(std::vector<int>& source_words, std::vector<int>& target_words) const {
source_words.reserve(source_ngrams+target_ngrams+1);
source_words.insert( source_words.end(), target_words.begin(), target_words.end() );
return FloorScore(m_neuralLM->lookup_ngram(source_words));
}
const Word& BilingualLM_NPLM::getNullWord() const {
return NULL_word;
}
int BilingualLM_NPLM::getNeuralLMId(const Word& word, bool is_source_word) const {
initSharedPointer();
boost::unordered_map<const Factor*, int>::iterator it;
const Factor* factor = word.GetFactor(word_factortype);
it = neuralLMids.find(factor);
//If we know the word return immediately
if (it != neuralLMids.end()){
return it->second;
}
//If we don't know the word and we aren't factored, return the word.
if (!factored) {
return unknown_word_id;
}
//Else try to get a pos_factor
const Factor* pos_factor = word.GetFactor(pos_factortype);
it = neuralLMids.find(pos_factor);
if (it != neuralLMids.end()){
return it->second;
} else {
return unknown_word_id;
}
}
void BilingualLM_NPLM::initSharedPointer() const {
if (!m_neuralLM.get()) {
m_neuralLM.reset(new nplm::neuralLM(*m_neuralLM_shared));
}
}
void BilingualLM_NPLM::SetParameter(const std::string& key, const std::string& value) {
if (key == "target_ngrams") {
target_ngrams = Scan<int>(value);
} else if (key == "source_ngrams") {
source_ngrams = Scan<int>(value);
} else if (key == "factored") {
factored = Scan<bool>(value);
} else if (key == "pos_factor") {
pos_factortype = Scan<FactorType>(value);
} else if (key == "cache_size") {
neuralLM_cache = atoi(value.c_str());
} else if (key == "premultiply") {
premultiply = Scan<bool>(value);
} else if (key == "null_word") {
NULL_string = value;
NULL_overwrite = true;
} else {
BilingualLM::SetParameter(key, value);
}
}
void BilingualLM_NPLM::loadModel() {
m_neuralLM_shared = new nplm::neuralLM(m_filePath, premultiply); //Default premultiply= true
int ngram_order = target_ngrams + source_ngrams + 1;
UTIL_THROW_IF2(
ngram_order != m_neuralLM_shared->get_order(),
"Wrong order of neuralLM: LM has " << m_neuralLM_shared->get_order() <<
", but Moses expects " << ngram_order);
m_neuralLM_shared->set_cache(neuralLM_cache); //Default 1000000
unknown_word_id = m_neuralLM_shared->lookup_word("<unk>");
//Setup factor -> NeuralLMId cache
FactorCollection& factorFactory = FactorCollection::Instance(); //To do the conversion from string to vocabID
const nplm::vocabulary& vocab = m_neuralLM_shared->get_vocabulary();
const boost::unordered_map<std::string, int>& neuraLMvocabmap = vocab.get_idmap();
boost::unordered_map<std::string, int>::const_iterator it;
for (it = neuraLMvocabmap.cbegin(); it != neuraLMvocabmap.cend(); it++) {
std::string raw_word = it->first;
int neuralLMid = it->second;
const Factor * factor = factorFactory.AddFactor(raw_word);
neuralLMids.insert(std::make_pair(factor, neuralLMid));
}
}
} // namespace Moses
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: frmhtmlw.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: ihi $ $Date: 2007-07-11 13:10:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#ifndef _INETDEF_HXX
#include <svtools/inetdef.hxx>
#endif
#include "svtools/htmlkywd.hxx"
//!(dv) #include <chaos2/cntapi.hxx>
#ifndef GCC
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#include <unotools/configmgr.hxx>
#include "svtools/urihelper.hxx"
#include <sfx2/docinf.hxx>
#include <sfx2/frmhtmlw.hxx>
#include <sfx2/evntconf.hxx>
#include <sfx2/frame.hxx>
#include <sfx2/app.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/docfile.hxx>
#include "sfxresid.hxx"
#include <sfx2/objsh.hxx>
#include <sfx2/sfx.hrc>
#include "bastyp.hrc"
// -----------------------------------------------------------------------
using namespace com::sun::star;
static sal_Char __READONLY_DATA sHTML_SC_yes[] = "YES";
static sal_Char __READONLY_DATA sHTML_SC_no[] = "NO";
static sal_Char __READONLY_DATA sHTML_SC_auto[] = "AUTO";
static sal_Char __READONLY_DATA sHTML_MIME_text_html[] = "text/html; charset=";
/* not used anymore?
static HTMLOutEvent __FAR_DATA aFrameSetEventTable[] =
{
{ sHTML_O_SDonload, sHTML_O_onload, SFX_EVENT_OPENDOC },
{ sHTML_O_SDonunload, sHTML_O_onunload, SFX_EVENT_PREPARECLOSEDOC },
{ sHTML_O_SDonfocus, sHTML_O_onfocus, SFX_EVENT_ACTIVATEDOC },
{ sHTML_O_SDonblur, sHTML_O_onblur, SFX_EVENT_DEACTIVATEDOC },
{ 0, 0, 0 }
};
*/
#if defined(UNX)
const sal_Char SfxFrameHTMLWriter::sNewLine[] = "\012";
#else
const sal_Char __FAR_DATA SfxFrameHTMLWriter::sNewLine[] = "\015\012";
#endif
void SfxFrameHTMLWriter::OutMeta( SvStream& rStrm,
const sal_Char *pIndent,
const String& rName,
const String& rContent, BOOL bHTTPEquiv,
rtl_TextEncoding eDestEnc,
String *pNonConvertableChars )
{
rStrm << sNewLine;
if( pIndent )
rStrm << pIndent;
ByteString sOut( '<' );
(((sOut += sHTML_meta) += ' ')
+= (bHTTPEquiv ? sHTML_O_httpequiv : sHTML_O_name)) += "=\"";
rStrm << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rStrm, rName, eDestEnc, pNonConvertableChars );
((sOut = "\" ") += sHTML_O_content) += "=\"";
rStrm << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rStrm, rContent, eDestEnc, pNonConvertableChars ) << "\">";
}
void SfxFrameHTMLWriter::Out_DocInfo( SvStream& rStrm, const String& rBaseURL,
const SfxDocumentInfo* pInfo,
const sal_Char *pIndent,
rtl_TextEncoding eDestEnc,
String *pNonConvertableChars )
{
const sal_Char *pCharSet =
rtl_getBestMimeCharsetFromTextEncoding( eDestEnc );
if( pCharSet )
{
String aContentType = String::CreateFromAscii( sHTML_MIME_text_html );
aContentType.AppendAscii( pCharSet );
OutMeta( rStrm, pIndent, sHTML_META_content_type, aContentType, TRUE,
eDestEnc, pNonConvertableChars );
}
// Titel (auch wenn er leer ist)
rStrm << sNewLine;
if( pIndent )
rStrm << pIndent;
HTMLOutFuncs::Out_AsciiTag( rStrm, sHTML_title );
if( pInfo )
{
const String& rTitle = pInfo->GetTitle();
if( rTitle.Len() )
HTMLOutFuncs::Out_String( rStrm, rTitle, eDestEnc, pNonConvertableChars );
}
HTMLOutFuncs::Out_AsciiTag( rStrm, sHTML_title, FALSE );
// Target-Frame
if( pInfo )
{
const String& rTarget = pInfo->GetDefaultTarget();
if( rTarget.Len() )
{
rStrm << sNewLine;
if( pIndent )
rStrm << pIndent;
ByteString sOut( '<' );
(((sOut += sHTML_base) += ' ') += sHTML_O_target) += "=\"";
rStrm << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rStrm, rTarget, eDestEnc, pNonConvertableChars )
<< "\">";
}
}
// Who we are
String sGenerator( SfxResId( STR_HTML_GENERATOR ) );
sGenerator.SearchAndReplaceAscii( "%1", String( DEFINE_CONST_UNICODE( TOOLS_INETDEF_OS ) ) );
OutMeta( rStrm, pIndent, sHTML_META_generator, sGenerator, FALSE, eDestEnc, pNonConvertableChars );
if( pInfo )
{
// Reload
if( pInfo->IsReloadEnabled() )
{
String sContent = String::CreateFromInt32(
(sal_Int32)pInfo->GetReloadDelay() );
const String &rReloadURL = pInfo->GetReloadURL();
if( rReloadURL.Len() )
{
sContent.AppendAscii( ";URL=" );
sContent += String(
URIHelper::simpleNormalizedMakeRelative(
rBaseURL, rReloadURL));
}
OutMeta( rStrm, pIndent, sHTML_META_refresh, sContent, TRUE,
eDestEnc, pNonConvertableChars );
}
// Author
const SfxStamp& rCreated = pInfo->GetCreated();
const String& rAuthor = rCreated.GetName();
if( rAuthor.Len() )
OutMeta( rStrm, pIndent, sHTML_META_author, rAuthor, FALSE,
eDestEnc, pNonConvertableChars );
// created
const DateTime& rCreatedDT = rCreated.GetTime();
String sOut(
String::CreateFromInt32( (sal_Int32)rCreatedDT.GetDate() ) );
(sOut += ';') +=
String::CreateFromInt32( (sal_Int32)rCreatedDT.GetTime() );
OutMeta( rStrm, pIndent, sHTML_META_created, sOut, FALSE, eDestEnc, pNonConvertableChars );
// changedby
const SfxStamp& rChanged = pInfo->GetChanged();
const String& rChangedBy = rChanged.GetName();
if( rChangedBy.Len() )
OutMeta( rStrm, pIndent, sHTML_META_changedby, rChangedBy, FALSE,
eDestEnc, pNonConvertableChars );
// changed
const DateTime& rChangedDT = rChanged.GetTime();
sOut = String::CreateFromInt32( (sal_Int32)rChangedDT.GetDate() );
(sOut += ';') +=
String::CreateFromInt32( (sal_Int32)rChangedDT.GetTime() );
OutMeta( rStrm, pIndent, sHTML_META_changed, sOut, FALSE, eDestEnc, pNonConvertableChars );
// Thema
const String& rTheme = pInfo->GetTheme();
if( rTheme.Len() )
OutMeta( rStrm, pIndent, sHTML_META_classification, rTheme, FALSE,
eDestEnc, pNonConvertableChars );
// Beschreibung
const String& rComment = pInfo->GetComment();
if( rComment.Len() )
OutMeta( rStrm, pIndent, sHTML_META_description, rComment, FALSE,
eDestEnc, pNonConvertableChars);
// Keywords
const String& rKeywords = pInfo->GetKeywords();
if( rKeywords.Len() )
OutMeta( rStrm, pIndent, sHTML_META_keywords, rKeywords, FALSE,
eDestEnc, pNonConvertableChars);
// die Benutzer-Eintraege
USHORT nKeys = pInfo->GetUserKeyCount();
// Leere Eintraege am Ende werden nicht ausgegeben
while( nKeys && !pInfo->GetUserKey(nKeys-1).GetWord().Len() )
nKeys--;
for( USHORT i=0; i< nKeys; i++ )
{
const SfxDocUserKey& rUserKey = pInfo->GetUserKey(i);
String aWord( rUserKey.GetWord() );
aWord.EraseTrailingChars();
if( rUserKey.GetTitle().Len() )
OutMeta( rStrm, pIndent, rUserKey.GetTitle(), aWord, FALSE,
eDestEnc, pNonConvertableChars );
}
}
}
/*
void SfxFrameHTMLWriter::OutHeader( rtl_TextEncoding eDestEnc )
{
// <HTML>
// <HEAD>
// <TITLE>Titel</TITLE>
// </HEAD>
HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_html ) << sNewLine;
HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_head );
Out_DocInfo( Strm(), &pDoc->GetDocInfo(), "\t", eDestEnc );
Strm() << sNewLine;
HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_head, FALSE ) << sNewLine;
//! OutScript(); // Hier fehlen noch die Scripten im Header
}
*/
void SfxFrameHTMLWriter::Out_FrameDescriptor(
SvStream& rOut, const String& rBaseURL, const uno::Reference < beans::XPropertySet >& xSet,
rtl_TextEncoding eDestEnc, String *pNonConvertableChars )
{
try
{
ByteString sOut;
::rtl::OUString aStr;
uno::Any aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameURL") );
if ( (aAny >>= aStr) && aStr.getLength() )
{
String aURL = INetURLObject( aStr ).GetMainURL( INetURLObject::DECODE_TO_IURI );
if( aURL.Len() )
{
aURL = URIHelper::simpleNormalizedMakeRelative(
rBaseURL, aURL );
((sOut += ' ') += sHTML_O_src) += "=\"";
rOut << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rOut, aURL, eDestEnc, pNonConvertableChars );
sOut = '\"';
}
}
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameName") );
if ( (aAny >>= aStr) && aStr.getLength() )
{
((sOut += ' ') += sHTML_O_name) += "=\"";
rOut << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rOut, aStr, eDestEnc, pNonConvertableChars );
sOut = '\"';
}
sal_Int32 nVal = SIZE_NOT_SET;
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameMarginWidth") );
if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET )
(((sOut += ' ') += sHTML_O_marginwidth) += '=') += ByteString::CreateFromInt32( nVal );
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameMarginHeight") );
if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET )
(((sOut += ' ') += sHTML_O_marginheight) += '=') += ByteString::CreateFromInt32( nVal );
sal_Bool bVal = sal_True;
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsAutoScroll") );
if ( (aAny >>= bVal) && !bVal )
{
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsScrollingMode") );
if ( aAny >>= bVal )
{
const sal_Char *pStr = bVal ? sHTML_SC_yes : sHTML_SC_no;
(((sOut += ' ') += sHTML_O_scrolling) += '=') += pStr;
}
}
// frame border (MS+Netscape-Erweiterung)
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsAutoBorder") );
if ( (aAny >>= bVal) && !bVal )
{
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsBorder") );
if ( aAny >>= bVal )
{
const char* pStr = bVal ? sHTML_SC_yes : sHTML_SC_no;
(((sOut += ' ') += sHTML_O_frameborder) += '=') += pStr;
}
}
// TODO/LATER: currently not supported attributes
// resize
//if( !pFrame->IsResizable() )
// (sOut += ' ') += sHTML_O_noresize;
//
//if ( pFrame->GetWallpaper() )
//{
// ((sOut += ' ') += sHTML_O_bordercolor) += '=';
// rOut << sOut.GetBuffer();
// HTMLOutFuncs::Out_Color( rOut, pFrame->GetWallpaper()->GetColor(), eDestEnc );
//}
//else
rOut << sOut.GetBuffer();
}
catch ( uno::Exception& )
{
}
}
String SfxFrameHTMLWriter::CreateURL( SfxFrame* pFrame )
{
String aRet;
SfxObjectShell* pShell = pFrame->GetCurrentDocument();
if( !aRet.Len() && pShell )
{
aRet = pShell->GetMedium()->GetName();
//!(dv) CntAnchor::ToPresentationURL( aRet );
}
return aRet;
}
<commit_msg>INTEGRATION: CWS basemodelrefactoring (1.14.144); FILE MERGED 2007/04/06 18:46:04 mba 1.14.144.2: #i75677#: classes SfxStamp and TimeStamp removed 2007/03/24 19:22:01 mba 1.14.144.1: #i75677#: separation of DocInfo and DocumentInfoObject<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: frmhtmlw.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: obo $ $Date: 2007-07-17 13:41:19 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#ifndef _INETDEF_HXX
#include <svtools/inetdef.hxx>
#endif
#include "svtools/htmlkywd.hxx"
//!(dv) #include <chaos2/cntapi.hxx>
#ifndef GCC
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#include <unotools/configmgr.hxx>
#include "svtools/urihelper.hxx"
#include <sfx2/docinf.hxx>
#include <sfx2/frmhtmlw.hxx>
#include <sfx2/evntconf.hxx>
#include <sfx2/frame.hxx>
#include <sfx2/app.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/docfile.hxx>
#include "sfxresid.hxx"
#include <sfx2/objsh.hxx>
#include <sfx2/sfx.hrc>
#include "bastyp.hrc"
// -----------------------------------------------------------------------
using namespace com::sun::star;
static sal_Char __READONLY_DATA sHTML_SC_yes[] = "YES";
static sal_Char __READONLY_DATA sHTML_SC_no[] = "NO";
static sal_Char __READONLY_DATA sHTML_SC_auto[] = "AUTO";
static sal_Char __READONLY_DATA sHTML_MIME_text_html[] = "text/html; charset=";
/* not used anymore?
static HTMLOutEvent __FAR_DATA aFrameSetEventTable[] =
{
{ sHTML_O_SDonload, sHTML_O_onload, SFX_EVENT_OPENDOC },
{ sHTML_O_SDonunload, sHTML_O_onunload, SFX_EVENT_PREPARECLOSEDOC },
{ sHTML_O_SDonfocus, sHTML_O_onfocus, SFX_EVENT_ACTIVATEDOC },
{ sHTML_O_SDonblur, sHTML_O_onblur, SFX_EVENT_DEACTIVATEDOC },
{ 0, 0, 0 }
};
*/
#if defined(UNX)
const sal_Char SfxFrameHTMLWriter::sNewLine[] = "\012";
#else
const sal_Char __FAR_DATA SfxFrameHTMLWriter::sNewLine[] = "\015\012";
#endif
void SfxFrameHTMLWriter::OutMeta( SvStream& rStrm,
const sal_Char *pIndent,
const String& rName,
const String& rContent, BOOL bHTTPEquiv,
rtl_TextEncoding eDestEnc,
String *pNonConvertableChars )
{
rStrm << sNewLine;
if( pIndent )
rStrm << pIndent;
ByteString sOut( '<' );
(((sOut += sHTML_meta) += ' ')
+= (bHTTPEquiv ? sHTML_O_httpequiv : sHTML_O_name)) += "=\"";
rStrm << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rStrm, rName, eDestEnc, pNonConvertableChars );
((sOut = "\" ") += sHTML_O_content) += "=\"";
rStrm << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rStrm, rContent, eDestEnc, pNonConvertableChars ) << "\">";
}
void SfxFrameHTMLWriter::Out_DocInfo( SvStream& rStrm, const String& rBaseURL,
const SfxDocumentInfo* pInfo,
const sal_Char *pIndent,
rtl_TextEncoding eDestEnc,
String *pNonConvertableChars )
{
const sal_Char *pCharSet =
rtl_getBestMimeCharsetFromTextEncoding( eDestEnc );
if( pCharSet )
{
String aContentType = String::CreateFromAscii( sHTML_MIME_text_html );
aContentType.AppendAscii( pCharSet );
OutMeta( rStrm, pIndent, sHTML_META_content_type, aContentType, TRUE,
eDestEnc, pNonConvertableChars );
}
// Titel (auch wenn er leer ist)
rStrm << sNewLine;
if( pIndent )
rStrm << pIndent;
HTMLOutFuncs::Out_AsciiTag( rStrm, sHTML_title );
if( pInfo )
{
const String& rTitle = pInfo->GetTitle();
if( rTitle.Len() )
HTMLOutFuncs::Out_String( rStrm, rTitle, eDestEnc, pNonConvertableChars );
}
HTMLOutFuncs::Out_AsciiTag( rStrm, sHTML_title, FALSE );
// Target-Frame
if( pInfo )
{
const String& rTarget = pInfo->GetDefaultTarget();
if( rTarget.Len() )
{
rStrm << sNewLine;
if( pIndent )
rStrm << pIndent;
ByteString sOut( '<' );
(((sOut += sHTML_base) += ' ') += sHTML_O_target) += "=\"";
rStrm << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rStrm, rTarget, eDestEnc, pNonConvertableChars )
<< "\">";
}
}
// Who we are
String sGenerator( SfxResId( STR_HTML_GENERATOR ) );
sGenerator.SearchAndReplaceAscii( "%1", String( DEFINE_CONST_UNICODE( TOOLS_INETDEF_OS ) ) );
OutMeta( rStrm, pIndent, sHTML_META_generator, sGenerator, FALSE, eDestEnc, pNonConvertableChars );
if( pInfo )
{
// Reload
if( pInfo->IsReloadEnabled() )
{
String sContent = String::CreateFromInt32(
(sal_Int32)pInfo->GetReloadDelay() );
const String &rReloadURL = pInfo->GetReloadURL();
if( rReloadURL.Len() )
{
sContent.AppendAscii( ";URL=" );
sContent += String(
URIHelper::simpleNormalizedMakeRelative(
rBaseURL, rReloadURL));
}
OutMeta( rStrm, pIndent, sHTML_META_refresh, sContent, TRUE,
eDestEnc, pNonConvertableChars );
}
// Author
const String& rAuthor = pInfo->GetAuthor();
if( rAuthor.Len() )
OutMeta( rStrm, pIndent, sHTML_META_author, rAuthor, FALSE,
eDestEnc, pNonConvertableChars );
// created
const DateTime& rCreatedDT = pInfo->GetCreationDate();
String sOut(
String::CreateFromInt32( (sal_Int32)rCreatedDT.GetDate() ) );
(sOut += ';') +=
String::CreateFromInt32( (sal_Int32)rCreatedDT.GetTime() );
OutMeta( rStrm, pIndent, sHTML_META_created, sOut, FALSE, eDestEnc, pNonConvertableChars );
// changedby
const String& rChangedBy = pInfo->GetModificationAuthor();
if( rChangedBy.Len() )
OutMeta( rStrm, pIndent, sHTML_META_changedby, rChangedBy, FALSE,
eDestEnc, pNonConvertableChars );
// changed
const DateTime& rChangedDT = pInfo->GetModificationDate();
sOut = String::CreateFromInt32( (sal_Int32)rChangedDT.GetDate() );
(sOut += ';') +=
String::CreateFromInt32( (sal_Int32)rChangedDT.GetTime() );
OutMeta( rStrm, pIndent, sHTML_META_changed, sOut, FALSE, eDestEnc, pNonConvertableChars );
// Thema
const String& rTheme = pInfo->GetTheme();
if( rTheme.Len() )
OutMeta( rStrm, pIndent, sHTML_META_classification, rTheme, FALSE,
eDestEnc, pNonConvertableChars );
// Beschreibung
const String& rComment = pInfo->GetComment();
if( rComment.Len() )
OutMeta( rStrm, pIndent, sHTML_META_description, rComment, FALSE,
eDestEnc, pNonConvertableChars);
// Keywords
const String& rKeywords = pInfo->GetKeywords();
if( rKeywords.Len() )
OutMeta( rStrm, pIndent, sHTML_META_keywords, rKeywords, FALSE,
eDestEnc, pNonConvertableChars);
// die Benutzer-Eintraege
USHORT nKeys = pInfo->GetUserKeyCount();
// Leere Eintraege am Ende werden nicht ausgegeben
while( nKeys && !pInfo->GetUserKeyWord(nKeys-1).Len() )
nKeys--;
for( USHORT i=0; i< nKeys; i++ )
{
String aWord( pInfo->GetUserKeyWord(i) );
String aTitle( pInfo->GetUserKeyTitle(i) );
aWord.EraseTrailingChars();
if( aTitle.Len() )
OutMeta( rStrm, pIndent, aTitle, aWord, FALSE,
eDestEnc, pNonConvertableChars );
}
}
}
/*
void SfxFrameHTMLWriter::OutHeader( rtl_TextEncoding eDestEnc )
{
// <HTML>
// <HEAD>
// <TITLE>Titel</TITLE>
// </HEAD>
HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_html ) << sNewLine;
HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_head );
Out_DocInfo( Strm(), &pDoc->GetDocInfo(), "\t", eDestEnc );
Strm() << sNewLine;
HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_head, FALSE ) << sNewLine;
//! OutScript(); // Hier fehlen noch die Scripten im Header
}
*/
void SfxFrameHTMLWriter::Out_FrameDescriptor(
SvStream& rOut, const String& rBaseURL, const uno::Reference < beans::XPropertySet >& xSet,
rtl_TextEncoding eDestEnc, String *pNonConvertableChars )
{
try
{
ByteString sOut;
::rtl::OUString aStr;
uno::Any aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameURL") );
if ( (aAny >>= aStr) && aStr.getLength() )
{
String aURL = INetURLObject( aStr ).GetMainURL( INetURLObject::DECODE_TO_IURI );
if( aURL.Len() )
{
aURL = URIHelper::simpleNormalizedMakeRelative(
rBaseURL, aURL );
((sOut += ' ') += sHTML_O_src) += "=\"";
rOut << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rOut, aURL, eDestEnc, pNonConvertableChars );
sOut = '\"';
}
}
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameName") );
if ( (aAny >>= aStr) && aStr.getLength() )
{
((sOut += ' ') += sHTML_O_name) += "=\"";
rOut << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rOut, aStr, eDestEnc, pNonConvertableChars );
sOut = '\"';
}
sal_Int32 nVal = SIZE_NOT_SET;
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameMarginWidth") );
if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET )
(((sOut += ' ') += sHTML_O_marginwidth) += '=') += ByteString::CreateFromInt32( nVal );
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameMarginHeight") );
if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET )
(((sOut += ' ') += sHTML_O_marginheight) += '=') += ByteString::CreateFromInt32( nVal );
sal_Bool bVal = sal_True;
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsAutoScroll") );
if ( (aAny >>= bVal) && !bVal )
{
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsScrollingMode") );
if ( aAny >>= bVal )
{
const sal_Char *pStr = bVal ? sHTML_SC_yes : sHTML_SC_no;
(((sOut += ' ') += sHTML_O_scrolling) += '=') += pStr;
}
}
// frame border (MS+Netscape-Erweiterung)
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsAutoBorder") );
if ( (aAny >>= bVal) && !bVal )
{
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsBorder") );
if ( aAny >>= bVal )
{
const char* pStr = bVal ? sHTML_SC_yes : sHTML_SC_no;
(((sOut += ' ') += sHTML_O_frameborder) += '=') += pStr;
}
}
// TODO/LATER: currently not supported attributes
// resize
//if( !pFrame->IsResizable() )
// (sOut += ' ') += sHTML_O_noresize;
//
//if ( pFrame->GetWallpaper() )
//{
// ((sOut += ' ') += sHTML_O_bordercolor) += '=';
// rOut << sOut.GetBuffer();
// HTMLOutFuncs::Out_Color( rOut, pFrame->GetWallpaper()->GetColor(), eDestEnc );
//}
//else
rOut << sOut.GetBuffer();
}
catch ( uno::Exception& )
{
}
}
String SfxFrameHTMLWriter::CreateURL( SfxFrame* pFrame )
{
String aRet;
SfxObjectShell* pShell = pFrame->GetCurrentDocument();
if( !aRet.Len() && pShell )
{
aRet = pShell->GetMedium()->GetName();
//!(dv) CntAnchor::ToPresentationURL( aRet );
}
return aRet;
}
<|endoftext|>
|
<commit_before>
#include <gtest/gtest.h>
#include <sm/logging.hpp>
#include <sm/logging/StdOutLogger.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
/// \brief Helper logger to catch console output
class TestLogger : public sm::logging::StdOutLogger {
public:
TestLogger() : sm::logging::StdOutLogger() {
formatter.doColor_ = false;
}
virtual ~TestLogger() { }
std::string string() { std::string str = _str; _str.clear(); return str; }
protected:
virtual void logImplementation(const sm::logging::LoggingEvent & event) override {
std::ostringstream os;
os << std::setprecision(6);
formatter.print(event, os);
_str = os.str();
}
virtual Time currentTimeImplementation() const {
return Time();
}
private:
std::string _str;
};
TEST(LoggingTestSuite, testBasic) {
try {
sm::logging::setLevel(sm::logging::Level::All);
boost::shared_ptr<TestLogger> logger(new TestLogger());
sm::logging::setLogger(logger);
int x = 1;
std::ostringstream os;
os << " [0.000000]: Hey there: " << x << std::endl;
const std::string expected = os.str();
SM_ALL_STREAM("Hey there: " << x );
EXPECT_EQ("[ ALL]" + expected, logger->string());
SM_FINEST_STREAM("Hey there: " << x );
EXPECT_EQ("[FINES]" + expected, logger->string());
SM_VERBOSE_STREAM("Hey there: " << x );
EXPECT_EQ("[VERBO]" + expected, logger->string());
SM_FINER_STREAM("Hey there: " << x );
EXPECT_EQ("[FINER]" + expected, logger->string());
SM_TRACE_STREAM("Hey there: " << x );
EXPECT_EQ("[TRACE]" + expected, logger->string());
SM_FINE_STREAM("Hey there: " << x );
EXPECT_EQ("[ FINE]" + expected, logger->string());
SM_DEBUG_STREAM("Hey there: " << x );
EXPECT_EQ("[DEBUG]" + expected, logger->string());
SM_INFO_STREAM("Hey there: " << x );
EXPECT_EQ("[ INFO]" + expected, logger->string());
SM_WARN_STREAM("Hey there: " << x );
EXPECT_EQ("[ WARN]" + expected, logger->string());
SM_ERROR_STREAM("Hey there: " << x );
EXPECT_EQ("[ERROR]" + expected, logger->string());
SM_FATAL_STREAM("Hey there: " << x );
EXPECT_EQ("[FATAL]" + expected, logger->string());
// test named streams
sm::logging::disableNamedStream("sm");
SM_INFO_STREAM("Hey there: " << x);
EXPECT_EQ("", logger->string()); // all non-named streams disabled
sm::logging::enableNamedStream("sm");
SM_INFO_STREAM_NAMED("test", "Hey there: " << x);
EXPECT_EQ("", logger->string()); // not enabled yet
sm::logging::enableNamedStream("test");
SM_WARN_STREAM_NAMED("test", "Hey there: " << x);
EXPECT_EQ("[ WARN]" + expected, logger->string());
SM_WARN_NAMED("test", "Hey there: %d",x);
EXPECT_EQ("[ WARN]" + expected, logger->string());
sm::logging::disableNamedStream("test");
SM_WARN_STREAM_NAMED("test", "Hey there: " << x);
EXPECT_EQ("", logger->string());
// test deprecation solution
sm::logging::enableNamedStream("sm.test");
SM_WARN_STREAM_NAMED("test", "Hey there: " << x);
EXPECT_EQ("[ WARN]" + expected, logger->string());
SM_INFO("This with printf: %d, %f, %s", 1, 1.0, "one");
for(int i = 0; i < 100; ++i)
{
SM_INFO_STREAM_THROTTLE(1.0,"test throttle: " << (++x));
SM_INFO_THROTTLE(1.0,"test throttle: %d",(++x));
boost::this_thread::sleep( boost::posix_time::milliseconds(100) );
}
}
catch( const std::exception & e )
{
FAIL() << e.what();
}
}
TEST(LoggingTestSuite, testLevel) {
{
sm::logging::Level level;
level = sm::logging::levels::fromString("All");
EXPECT_EQ(sm::logging::Level::All, level);
level = sm::logging::levels::fromString("all");
EXPECT_EQ(sm::logging::Level::All, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Finest");
EXPECT_EQ(sm::logging::Level::Finest, level);
level = sm::logging::levels::fromString("finest");
EXPECT_EQ(sm::logging::Level::Finest, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Verbose");
EXPECT_EQ(sm::logging::Level::Verbose, level);
level = sm::logging::levels::fromString("verbose");
EXPECT_EQ(sm::logging::Level::Verbose, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Finer");
EXPECT_EQ(sm::logging::Level::Finer, level);
level = sm::logging::levels::fromString("finer");
EXPECT_EQ(sm::logging::Level::Finer, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Trace");
EXPECT_EQ(sm::logging::Level::Trace, level);
level = sm::logging::levels::fromString("trace");
EXPECT_EQ(sm::logging::Level::Trace, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Fine");
EXPECT_EQ(sm::logging::Level::Fine, level);
level = sm::logging::levels::fromString("fine");
EXPECT_EQ(sm::logging::Level::Fine, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Debug");
EXPECT_EQ(sm::logging::Level::Debug, level);
level = sm::logging::levels::fromString("debug");
EXPECT_EQ(sm::logging::Level::Debug, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Info");
EXPECT_EQ(sm::logging::Level::Info, level);
level = sm::logging::levels::fromString("info");
EXPECT_EQ(sm::logging::Level::Info, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Warn");
EXPECT_EQ(sm::logging::Level::Warn, level);
level = sm::logging::levels::fromString("warn");
EXPECT_EQ(sm::logging::Level::Warn, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Error");
EXPECT_EQ(sm::logging::Level::Error, level);
level = sm::logging::levels::fromString("error");
EXPECT_EQ(sm::logging::Level::Error, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Fatal");
EXPECT_EQ(sm::logging::Level::Fatal, level);
level = sm::logging::levels::fromString("fatal");
EXPECT_EQ(sm::logging::Level::Fatal, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("nonsense");
EXPECT_EQ(sm::logging::Level::Info, level);
}
}
<commit_msg>unit test to check that enabling stream "sm" works<commit_after>
#include <gtest/gtest.h>
#include <sm/logging.hpp>
#include <sm/logging/StdOutLogger.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
/// \brief Helper logger to catch console output
class TestLogger : public sm::logging::StdOutLogger {
public:
TestLogger() : sm::logging::StdOutLogger() {
formatter.doColor_ = false;
}
virtual ~TestLogger() { }
std::string string() { std::string str = _str; _str.clear(); return str; }
protected:
virtual void logImplementation(const sm::logging::LoggingEvent & event) override {
std::ostringstream os;
os << std::setprecision(6);
formatter.print(event, os);
_str = os.str();
}
virtual Time currentTimeImplementation() const {
return Time();
}
private:
std::string _str;
};
TEST(LoggingTestSuite, testBasic) {
try {
sm::logging::setLevel(sm::logging::Level::All);
boost::shared_ptr<TestLogger> logger(new TestLogger());
sm::logging::setLogger(logger);
int x = 1;
std::ostringstream os;
os << " [0.000000]: Hey there: " << x << std::endl;
const std::string expected = os.str();
SM_ALL_STREAM("Hey there: " << x );
EXPECT_EQ("[ ALL]" + expected, logger->string());
SM_FINEST_STREAM("Hey there: " << x );
EXPECT_EQ("[FINES]" + expected, logger->string());
SM_VERBOSE_STREAM("Hey there: " << x );
EXPECT_EQ("[VERBO]" + expected, logger->string());
SM_FINER_STREAM("Hey there: " << x );
EXPECT_EQ("[FINER]" + expected, logger->string());
SM_TRACE_STREAM("Hey there: " << x );
EXPECT_EQ("[TRACE]" + expected, logger->string());
SM_FINE_STREAM("Hey there: " << x );
EXPECT_EQ("[ FINE]" + expected, logger->string());
SM_DEBUG_STREAM("Hey there: " << x );
EXPECT_EQ("[DEBUG]" + expected, logger->string());
SM_INFO_STREAM("Hey there: " << x );
EXPECT_EQ("[ INFO]" + expected, logger->string());
SM_WARN_STREAM("Hey there: " << x );
EXPECT_EQ("[ WARN]" + expected, logger->string());
SM_ERROR_STREAM("Hey there: " << x );
EXPECT_EQ("[ERROR]" + expected, logger->string());
SM_FATAL_STREAM("Hey there: " << x );
EXPECT_EQ("[FATAL]" + expected, logger->string());
// test named streams
sm::logging::disableNamedStream("sm");
SM_INFO_STREAM("Hey there: " << x);
EXPECT_EQ("", logger->string()); // all non-named streams disabled
sm::logging::enableNamedStream("sm");
SM_INFO_STREAM("Hey there: " << x);
EXPECT_EQ("[ INFO]" + expected, logger->string()); // all non-named streams enabled again
SM_INFO_STREAM_NAMED("test", "Hey there: " << x);
EXPECT_EQ("", logger->string()); // not enabled yet
sm::logging::enableNamedStream("test");
SM_WARN_STREAM_NAMED("test", "Hey there: " << x);
EXPECT_EQ("[ WARN]" + expected, logger->string());
SM_WARN_NAMED("test", "Hey there: %d",x);
EXPECT_EQ("[ WARN]" + expected, logger->string());
sm::logging::disableNamedStream("test");
SM_WARN_STREAM_NAMED("test", "Hey there: " << x);
EXPECT_EQ("", logger->string());
// test deprecation solution
sm::logging::enableNamedStream("sm.test");
SM_WARN_STREAM_NAMED("test", "Hey there: " << x);
EXPECT_EQ("[ WARN]" + expected, logger->string());
SM_INFO("This with printf: %d, %f, %s", 1, 1.0, "one");
for(int i = 0; i < 100; ++i)
{
SM_INFO_STREAM_THROTTLE(1.0,"test throttle: " << (++x));
SM_INFO_THROTTLE(1.0,"test throttle: %d",(++x));
boost::this_thread::sleep( boost::posix_time::milliseconds(100) );
}
}
catch( const std::exception & e )
{
FAIL() << e.what();
}
}
TEST(LoggingTestSuite, testLevel) {
{
sm::logging::Level level;
level = sm::logging::levels::fromString("All");
EXPECT_EQ(sm::logging::Level::All, level);
level = sm::logging::levels::fromString("all");
EXPECT_EQ(sm::logging::Level::All, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Finest");
EXPECT_EQ(sm::logging::Level::Finest, level);
level = sm::logging::levels::fromString("finest");
EXPECT_EQ(sm::logging::Level::Finest, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Verbose");
EXPECT_EQ(sm::logging::Level::Verbose, level);
level = sm::logging::levels::fromString("verbose");
EXPECT_EQ(sm::logging::Level::Verbose, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Finer");
EXPECT_EQ(sm::logging::Level::Finer, level);
level = sm::logging::levels::fromString("finer");
EXPECT_EQ(sm::logging::Level::Finer, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Trace");
EXPECT_EQ(sm::logging::Level::Trace, level);
level = sm::logging::levels::fromString("trace");
EXPECT_EQ(sm::logging::Level::Trace, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Fine");
EXPECT_EQ(sm::logging::Level::Fine, level);
level = sm::logging::levels::fromString("fine");
EXPECT_EQ(sm::logging::Level::Fine, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Debug");
EXPECT_EQ(sm::logging::Level::Debug, level);
level = sm::logging::levels::fromString("debug");
EXPECT_EQ(sm::logging::Level::Debug, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Info");
EXPECT_EQ(sm::logging::Level::Info, level);
level = sm::logging::levels::fromString("info");
EXPECT_EQ(sm::logging::Level::Info, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Warn");
EXPECT_EQ(sm::logging::Level::Warn, level);
level = sm::logging::levels::fromString("warn");
EXPECT_EQ(sm::logging::Level::Warn, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Error");
EXPECT_EQ(sm::logging::Level::Error, level);
level = sm::logging::levels::fromString("error");
EXPECT_EQ(sm::logging::Level::Error, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("Fatal");
EXPECT_EQ(sm::logging::Level::Fatal, level);
level = sm::logging::levels::fromString("fatal");
EXPECT_EQ(sm::logging::Level::Fatal, level);
}
{
sm::logging::Level level;
level = sm::logging::levels::fromString("nonsense");
EXPECT_EQ(sm::logging::Level::Info, level);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: svmedit2.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: pb $ $Date: 2001-05-21 11:12:34 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "svmedit2.hxx"
#include "xtextedt.hxx"
ExtMultiLineEdit::ExtMultiLineEdit( Window* pParent, WinBits nWinStyle ) :
MultiLineEdit( pParent, nWinStyle )
{
}
ExtMultiLineEdit::ExtMultiLineEdit( Window* pParent, const ResId& rResId ) :
MultiLineEdit( pParent, rResId )
{
}
ExtMultiLineEdit::~ExtMultiLineEdit()
{
}
void ExtMultiLineEdit::InsertText( const String& rNew, BOOL bSelect )
{
GetTextView()->InsertText( rNew, FALSE );
}
void ExtMultiLineEdit::SetAutoScroll( BOOL bAutoScroll )
{
GetTextView()->SetAutoScroll( bAutoScroll );
}
void ExtMultiLineEdit::SetAttrib( const TextAttrib& rAttr, ULONG nPara, USHORT nStart, USHORT nEnd )
{
GetTextEngine()->SetAttrib( rAttr, nPara, nStart, nEnd );
}
void ExtMultiLineEdit::SetLeftMargin( USHORT nLeftMargin )
{
GetTextEngine()->SetLeftMargin( nLeftMargin );
}
ULONG ExtMultiLineEdit::GetParagraphCount() const
{
return GetTextEngine()->GetParagraphCount();
}
<commit_msg>fix: #88546# forward EnableCursor() to TextView<commit_after>/*************************************************************************
*
* $RCSfile: svmedit2.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: pb $ $Date: 2001-07-05 12:49:24 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "svmedit2.hxx"
#include "xtextedt.hxx"
ExtMultiLineEdit::ExtMultiLineEdit( Window* pParent, WinBits nWinStyle ) :
MultiLineEdit( pParent, nWinStyle )
{
}
ExtMultiLineEdit::ExtMultiLineEdit( Window* pParent, const ResId& rResId ) :
MultiLineEdit( pParent, rResId )
{
}
ExtMultiLineEdit::~ExtMultiLineEdit()
{
}
void ExtMultiLineEdit::InsertText( const String& rNew, BOOL bSelect )
{
GetTextView()->InsertText( rNew, FALSE );
}
void ExtMultiLineEdit::SetAutoScroll( BOOL bAutoScroll )
{
GetTextView()->SetAutoScroll( bAutoScroll );
}
void ExtMultiLineEdit::EnableCursor( BOOL bEnable )
{
GetTextView()->EnableCursor( bEnable );
}
void ExtMultiLineEdit::SetAttrib( const TextAttrib& rAttr, ULONG nPara, USHORT nStart, USHORT nEnd )
{
GetTextEngine()->SetAttrib( rAttr, nPara, nStart, nEnd );
}
void ExtMultiLineEdit::SetLeftMargin( USHORT nLeftMargin )
{
GetTextEngine()->SetLeftMargin( nLeftMargin );
}
ULONG ExtMultiLineEdit::GetParagraphCount() const
{
return GetTextEngine()->GetParagraphCount();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: outlundo.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:59:18 $
*
* 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 _OUTLUNDO_HXX
#define _OUTLUNDO_HXX
#include <outliner.hxx>
#ifndef _EDITDATA_HXX
#include <editdata.hxx>
#endif
#ifndef _EDITUND2_HXX
#include <editund2.hxx>
#endif
class OutlinerUndoBase : public EditUndo
{
private:
Outliner* mpOutliner;
public:
OutlinerUndoBase( USHORT nId, Outliner* pOutliner );
Outliner* GetOutliner() const { return mpOutliner; }
};
class OutlinerUndoChangeDepth : public OutlinerUndoBase
{
private:
USHORT mnPara;
USHORT mnOldDepth;
USHORT mnNewDepth;
public:
OutlinerUndoChangeDepth( Outliner* pOutliner, USHORT nPara, USHORT nOldDepth, USHORT nNewDepth );
virtual void Undo();
virtual void Redo();
virtual void Repeat();
};
// Hilfs-Undo: Wenn es fuer eine Aktion keine OutlinerUndoAction gibst, weil
// die EditEngine das handelt, aber z.B. noch das Bullet neu berechnet werden muss.
class OutlinerUndoCheckPara : public OutlinerUndoBase
{
private:
USHORT mnPara;
public:
OutlinerUndoCheckPara( Outliner* pOutliner, USHORT nPara );
virtual void Undo();
virtual void Redo();
virtual void Repeat();
};
// -------------------------------------
class OLUndoExpand : public EditUndo
{
void Restore( BOOL bUndo );
public:
OLUndoExpand( Outliner* pOut, USHORT nId );
~OLUndoExpand();
virtual void Undo();
virtual void Redo();
virtual void Repeat();
USHORT* pParas; // 0 == nCount enthaelt Absatznummer
Outliner* pOutliner;
USHORT nCount;
};
#endif
<commit_msg>INTEGRATION: CWS sb59 (1.3.488); FILE MERGED 2006/08/03 13:51:53 cl 1.3.488.1: removed compiler warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: outlundo.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-10-12 13:02: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 _OUTLUNDO_HXX
#define _OUTLUNDO_HXX
#include <outliner.hxx>
#ifndef _EDITDATA_HXX
#include <editdata.hxx>
#endif
#ifndef _EDITUND2_HXX
#include <editund2.hxx>
#endif
class OutlinerUndoBase : public EditUndo
{
private:
Outliner* mpOutliner;
public:
OutlinerUndoBase( USHORT nId, Outliner* pOutliner );
Outliner* GetOutliner() const { return mpOutliner; }
};
class OutlinerUndoChangeDepth : public OutlinerUndoBase
{
using SfxUndoAction::Repeat;
private:
USHORT mnPara;
USHORT mnOldDepth;
USHORT mnNewDepth;
public:
OutlinerUndoChangeDepth( Outliner* pOutliner, USHORT nPara, USHORT nOldDepth, USHORT nNewDepth );
virtual void Undo();
virtual void Redo();
virtual void Repeat();
};
// Hilfs-Undo: Wenn es fuer eine Aktion keine OutlinerUndoAction gibst, weil
// die EditEngine das handelt, aber z.B. noch das Bullet neu berechnet werden muss.
class OutlinerUndoCheckPara : public OutlinerUndoBase
{
using SfxUndoAction::Repeat;
private:
USHORT mnPara;
public:
OutlinerUndoCheckPara( Outliner* pOutliner, USHORT nPara );
virtual void Undo();
virtual void Redo();
virtual void Repeat();
};
// -------------------------------------
class OLUndoExpand : public EditUndo
{
using SfxUndoAction::Repeat;
void Restore( BOOL bUndo );
public:
OLUndoExpand( Outliner* pOut, USHORT nId );
~OLUndoExpand();
virtual void Undo();
virtual void Redo();
virtual void Repeat();
USHORT* pParas; // 0 == nCount enthaelt Absatznummer
Outliner* pOutliner;
USHORT nCount;
};
#endif
<|endoftext|>
|
<commit_before><commit_msg>fdo#84573 COLOR PICKER: Improve keyboard navigation<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2014 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
// ItemDataTest.cpp: Unit test for CItemData class
#ifdef WIN32
#include "../ui/Windows/stdafx.h"
#endif
#include "core/ItemData.h"
#include "gtest/gtest.h"
// We need to call CItemData::SetSessionKey() exactly once.
// That's what the following is for:
class ItemDataEnv : public ::testing::Environment
{
public:
ItemDataEnv() { }
virtual void SetUp() { CItemData::SetSessionKey(); }
};
static ::testing::Environment *const env = ::testing::AddGlobalTestEnvironment(new ItemDataEnv);
// A fixture for factoring common code across tests
class ItemDataTest : public ::testing::Test
{
protected:
ItemDataTest(); // to init members
CItemData emptyItem, fullItem;
void SetUp();
// members used to populate and test fullItem:
const StringX title, password, user, notes, group;
const StringX url, at, email, polname, symbols, runcmd;
const time_t aTime, cTime, xTime, pmTime, rmTime;
const int16 iDCA, iSDCA;
const int32 kbs;
time_t tVal;
int16 iVal16;
int32 iVal32;
};
ItemDataTest::ItemDataTest()
: title(_T("a-title")), password(_T("b-password!?")),
user(_T("C-UserR-ינור")), // non-English
notes(_T("N is for notes\nwhich can span lines\r\nin several ways.")),
group(_T("Groups.are.nested.by.dots")), url(_T("http://pwsafe.org/")),
at(_T("\\u\\t\\t\\n\\p\\t\\n")), email(_T("joe@spammenot.com")),
polname(_T("liberal")), symbols(_T("<-_+=@?>")), runcmd(_T("Run 4 your life")),
aTime(1409901292), // time test was first added, from http://www.unixtimestamp.com/
cTime(1409901293), xTime(1409901294), pmTime(1409901295), rmTime(1409901296),
iDCA(3), iSDCA(8), kbs(0x12345678),
tVal(0), iVal16(-1), iVal32(-1)
{}
void ItemDataTest::SetUp()
{
fullItem.SetTitle(title);
fullItem.SetPassword(password);
fullItem.SetUser(user);
fullItem.SetNotes(notes);
fullItem.SetGroup(group);
fullItem.SetURL(url);
fullItem.SetAutoType(at);
fullItem.SetEmail(email);
fullItem.SetPolicyName(polname);
fullItem.SetSymbols(symbols);
fullItem.SetRunCommand(runcmd);
fullItem.SetATime(aTime);
fullItem.SetCTime(cTime);
fullItem.SetXTime(xTime);
fullItem.SetPMTime(pmTime);
fullItem.SetRMTime(rmTime);
fullItem.SetDCA(iDCA);
fullItem.SetShiftDCA(iSDCA);
fullItem.SetKBShortcut(kbs);
}
// And now the tests...
TEST_F(ItemDataTest, EmptyItems)
{
CItemData di2;
const StringX t(L"title");
EXPECT_TRUE(emptyItem == di2);
emptyItem.SetTitle(t);
EXPECT_FALSE(emptyItem == di2);
di2.SetTitle(t);
EXPECT_TRUE(emptyItem == di2);
}
TEST_F(ItemDataTest, CopyCtor)
{
emptyItem.SetTitle(_T("title"));
emptyItem.SetPassword(_T("password!"));
CItemData di2(emptyItem);
EXPECT_TRUE(emptyItem == di2);
}
TEST_F(ItemDataTest, Getters_n_Setters)
{
// Setters called in SetUp()
EXPECT_EQ(title, fullItem.GetTitle());
EXPECT_EQ(password, fullItem.GetPassword());
EXPECT_EQ(user, fullItem.GetUser());
EXPECT_EQ(notes, fullItem.GetNotes());
EXPECT_EQ(group, fullItem.GetGroup());
EXPECT_EQ(url, fullItem.GetURL());
EXPECT_EQ(at, fullItem.GetAutoType());
EXPECT_EQ(email, fullItem.GetEmail());
EXPECT_EQ(polname, fullItem.GetPolicyName());
EXPECT_EQ(symbols, fullItem.GetSymbols());
EXPECT_EQ(runcmd, fullItem.GetRunCommand());
EXPECT_EQ(aTime, fullItem.GetATime(tVal));
EXPECT_EQ(cTime, fullItem.GetCTime(tVal));
EXPECT_EQ(xTime, fullItem.GetXTime(tVal));
EXPECT_EQ(pmTime, fullItem.GetPMTime(tVal));
EXPECT_EQ(rmTime, fullItem.GetRMTime(tVal));
EXPECT_EQ(iDCA, fullItem.GetDCA(iVal16));
EXPECT_EQ(iSDCA, fullItem.GetShiftDCA(iVal16));
EXPECT_EQ(kbs, fullItem.GetKBShortcut(iVal32));
}
TEST_F(ItemDataTest, PlainTextSerialization)
{
std::vector<char> v;
emptyItem.SerializePlainText(v);
CItemData di;
EXPECT_TRUE(di.DeSerializePlainText(v));
EXPECT_EQ(emptyItem, di);
fullItem.SerializePlainText(v);
EXPECT_TRUE(di.DeSerializePlainText(v));
EXPECT_EQ(fullItem, di);
}
<commit_msg>Added minimal test for CItemData::Unknowns<commit_after>/*
* Copyright (c) 2003-2014 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
// ItemDataTest.cpp: Unit test for CItemData class
#ifdef WIN32
#include "../ui/Windows/stdafx.h"
#endif
#include "core/ItemData.h"
#include "gtest/gtest.h"
// We need to call CItemData::SetSessionKey() exactly once.
// That's what the following is for:
class ItemDataEnv : public ::testing::Environment
{
public:
ItemDataEnv() { }
virtual void SetUp() { CItemData::SetSessionKey(); }
};
static ::testing::Environment *const env = ::testing::AddGlobalTestEnvironment(new ItemDataEnv);
// A fixture for factoring common code across tests
class ItemDataTest : public ::testing::Test
{
protected:
ItemDataTest(); // to init members
CItemData emptyItem, fullItem;
void SetUp();
// members used to populate and test fullItem:
const StringX title, password, user, notes, group;
const StringX url, at, email, polname, symbols, runcmd;
const time_t aTime, cTime, xTime, pmTime, rmTime;
const int16 iDCA, iSDCA;
const int32 kbs;
time_t tVal;
int16 iVal16;
int32 iVal32;
};
ItemDataTest::ItemDataTest()
: title(_T("a-title")), password(_T("b-password!?")),
user(_T("C-UserR-ינור")), // non-English
notes(_T("N is for notes\nwhich can span lines\r\nin several ways.")),
group(_T("Groups.are.nested.by.dots")), url(_T("http://pwsafe.org/")),
at(_T("\\u\\t\\t\\n\\p\\t\\n")), email(_T("joe@spammenot.com")),
polname(_T("liberal")), symbols(_T("<-_+=@?>")), runcmd(_T("Run 4 your life")),
aTime(1409901292), // time test was first added, from http://www.unixtimestamp.com/
cTime(1409901293), xTime(1409901294), pmTime(1409901295), rmTime(1409901296),
iDCA(3), iSDCA(8), kbs(0x12345678),
tVal(0), iVal16(-1), iVal32(-1)
{}
void ItemDataTest::SetUp()
{
fullItem.SetTitle(title);
fullItem.SetPassword(password);
fullItem.SetUser(user);
fullItem.SetNotes(notes);
fullItem.SetGroup(group);
fullItem.SetURL(url);
fullItem.SetAutoType(at);
fullItem.SetEmail(email);
fullItem.SetPolicyName(polname);
fullItem.SetSymbols(symbols);
fullItem.SetRunCommand(runcmd);
fullItem.SetATime(aTime);
fullItem.SetCTime(cTime);
fullItem.SetXTime(xTime);
fullItem.SetPMTime(pmTime);
fullItem.SetRMTime(rmTime);
fullItem.SetDCA(iDCA);
fullItem.SetShiftDCA(iSDCA);
fullItem.SetKBShortcut(kbs);
}
// And now the tests...
TEST_F(ItemDataTest, EmptyItems)
{
CItemData di2;
const StringX t(L"title");
EXPECT_TRUE(emptyItem == di2);
emptyItem.SetTitle(t);
EXPECT_FALSE(emptyItem == di2);
di2.SetTitle(t);
EXPECT_TRUE(emptyItem == di2);
}
TEST_F(ItemDataTest, CopyCtor)
{
emptyItem.SetTitle(_T("title"));
emptyItem.SetPassword(_T("password!"));
CItemData di2(emptyItem);
EXPECT_TRUE(emptyItem == di2);
}
TEST_F(ItemDataTest, Getters_n_Setters)
{
// Setters called in SetUp()
EXPECT_EQ(title, fullItem.GetTitle());
EXPECT_EQ(password, fullItem.GetPassword());
EXPECT_EQ(user, fullItem.GetUser());
EXPECT_EQ(notes, fullItem.GetNotes());
EXPECT_EQ(group, fullItem.GetGroup());
EXPECT_EQ(url, fullItem.GetURL());
EXPECT_EQ(at, fullItem.GetAutoType());
EXPECT_EQ(email, fullItem.GetEmail());
EXPECT_EQ(polname, fullItem.GetPolicyName());
EXPECT_EQ(symbols, fullItem.GetSymbols());
EXPECT_EQ(runcmd, fullItem.GetRunCommand());
EXPECT_EQ(aTime, fullItem.GetATime(tVal));
EXPECT_EQ(cTime, fullItem.GetCTime(tVal));
EXPECT_EQ(xTime, fullItem.GetXTime(tVal));
EXPECT_EQ(pmTime, fullItem.GetPMTime(tVal));
EXPECT_EQ(rmTime, fullItem.GetRMTime(tVal));
EXPECT_EQ(iDCA, fullItem.GetDCA(iVal16));
EXPECT_EQ(iSDCA, fullItem.GetShiftDCA(iVal16));
EXPECT_EQ(kbs, fullItem.GetKBShortcut(iVal32));
}
TEST_F(ItemDataTest, PlainTextSerialization)
{
std::vector<char> v;
emptyItem.SerializePlainText(v);
CItemData di;
EXPECT_TRUE(di.DeSerializePlainText(v));
EXPECT_EQ(emptyItem, di);
fullItem.SerializePlainText(v);
EXPECT_TRUE(di.DeSerializePlainText(v));
EXPECT_EQ(fullItem, di);
}
TEST_F(ItemDataTest, UnknownFields)
{
unsigned char u1t = 100, u2t = 200, u3t = 100;
unsigned char u1v[] = {10, 11, 33, 57};
unsigned char u2v[] = {92, 77, 76, 40, 65, 66};
unsigned char u3v[] = {1};
ASSERT_EQ(0, emptyItem.NumberUnknownFields());
emptyItem.SetUnknownField(u1t, sizeof(u1v), u1v);
emptyItem.SetUnknownField(u2t, sizeof(u2v), u2v);
emptyItem.SetUnknownField(u3t, sizeof(u3v), u3v);
EXPECT_EQ(3, emptyItem.NumberUnknownFields());
// Getting Unknown Fields is done by private
// member functions, which make sense considering
// how they're processed. Worth exposing an API
// just for testing, TBD.
}
<|endoftext|>
|
<commit_before><commit_msg>SAL_DLLPUBLIC->SW_DLLPUBLIC<commit_after><|endoftext|>
|
<commit_before>#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <yarp/os/LogStream.h>
#include <yarp/os/Network.h>
#include <yarp/os/ResourceFinder.h>
#include "iCubProprioception/SuperimposerFactory.h"
using namespace yarp::os;
int main(int argc, char* argv[])
{
ConstString log_ID = "[Main]";
yInfo() << log_ID << "Configuring and starting module...";
Network yarp;
if (!yarp.checkNetwork(3.0))
{
yError() << log_ID << "YARP seems unavailable.";
return EXIT_FAILURE;
}
ResourceFinder rf;
rf.setVerbose(true);
rf.setDefaultConfigFile("iCubProprioception-Config-SIM.ini");
rf.setDefaultContext("iCubProprioception");
rf.configure(argc, argv);
/* Initialize OpenGL context */
SuperimposerFactory::initOGL(320, 240, 1);
/* SuperimposerFactory, derived from RFModule, must be declared, initialized and run in the main thread (thread_0). */
SuperimposerFactory sh;
sh.setProjectName("iCubProprioception");
if (sh.runModuleThreaded(rf) == 0)
{
while (!sh.isStopping())
{
glfwPollEvents();
}
}
sh.joinModule();
glfwMakeContextCurrent(NULL);
glfwTerminate();
yInfo() << log_ID << "Main returning.";
yInfo() << log_ID << "Application closed.";
return EXIT_SUCCESS;
}
<commit_msg>Remove unneeded include<commit_after>#include <yarp/os/LogStream.h>
#include <yarp/os/Network.h>
#include <yarp/os/ResourceFinder.h>
#include "iCubProprioception/SuperimposerFactory.h"
using namespace yarp::os;
int main(int argc, char* argv[])
{
ConstString log_ID = "[Main]";
yInfo() << log_ID << "Configuring and starting module...";
Network yarp;
if (!yarp.checkNetwork(3.0))
{
yError() << log_ID << "YARP seems unavailable.";
return EXIT_FAILURE;
}
ResourceFinder rf;
rf.setVerbose(true);
rf.setDefaultConfigFile("iCubProprioception-Config-SIM.ini");
rf.setDefaultContext("iCubProprioception");
rf.configure(argc, argv);
/* Initialize OpenGL context */
SuperimposerFactory::initOGL(320, 240, 1);
/* SuperimposerFactory, derived from RFModule, must be declared, initialized and run in the main thread (thread_0). */
SuperimposerFactory sh;
sh.setProjectName("iCubProprioception");
if (sh.runModuleThreaded(rf) == 0)
{
while (!sh.isStopping())
{
glfwPollEvents();
}
}
sh.joinModule();
glfwMakeContextCurrent(NULL);
glfwTerminate();
yInfo() << log_ID << "Main returning.";
yInfo() << log_ID << "Application closed.";
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/include/usr/fapi2/plat_target.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file plat_target.H
/// @brief Define FAPI2 target functions for the platform layer.
///
#ifndef __FAPI2_PLAT_TARGET__
#define __FAPI2_PLAT_TARGET__
// HB platform support
#include <targeting/common/target.H>
#include <multicast_defs.H>
#include <multicast_group_defs.H>
#include <devicefw/userif.H>
#include <targeting/common/utilFilter.H>
#include <fapiPlatTrace.H>
#include <errl/errlmanager.H>
namespace fapi2
{
// Since the EKB definition of MulticastCoreSelect does not contain
// an "invalid"/"no core selected" enum, declare one here for initialization
// convenience purposes.
static const MulticastCoreSelect MCCORE_NONE =
static_cast<MulticastCoreSelect>(0);
/**
* @brief plat_target_handle_t class
*
* This class serves as a wrapper for TARGETING::Target and multicast-
* specific attributes. This class allows conversion from fapi2::Target
* to TARGETING::Target and in the other direction via overloaded
* constructors and conversion operators.
* Conversion examples:
* fapi2::Target<fapi2::TARGET_TYPE_CORE>l_fapiCore(l_targetingCore)
* TARGETING::Target* l_targetingCore = l_fapiCore.get()
*/
class plat_target_handle_t
{
private:
const TARGETING::Target* iv_pTarget; // Hostboot target type
bool iv_multicast; // Whether a multicast SCOM op
// is to be executed on this target
MulticastGroup iv_group; // The selected group for multicast
MulticastType iv_multicastOp; // The type of multicast operation
MulticastCoreSelect iv_coreSelect; // Which cores to run SCOM op on
public:
/**
* @brief Parametrized constructor for plat_target_handle_t
*
* @param[in] i_target the const target for which to construct
* plat_target_handle_t
* @param[in] i_multicast whether the plat_target_handle_t is
* a multicast target wrapper
* @param[in] i_group the multicast group
* @param[in] i_op the type of multicast operation
* @param[in] i_coreSelect which cores to run the operation on
*/
plat_target_handle_t(const TARGETING::Target* i_target = nullptr,
bool i_multicast = false,
MulticastGroup i_group = MCGROUP_ALL,
MulticastType i_op = MULTICAST_OR,
MulticastCoreSelect i_coreSelect = MCCORE_NONE):
iv_pTarget(i_target),
iv_multicast(i_multicast),
iv_group(i_group),
iv_multicastOp(i_op),
iv_coreSelect(i_coreSelect)
{
}
/**
* @brief fapi2::Target to TARGETING::Target* converter
*
* @return the underlying TARGETING::Target*
*/
operator TARGETING::Target*() const
{
return const_cast<TARGETING::Target*>(iv_pTarget);
}
/**
* @brief fapi2::Target to const TARGETING::Target* converter
*
* @return the underlying const TARGETING::Target*
*/
operator const TARGETING::Target*() const
{
return iv_pTarget;
}
/**
* @brief Overloaded equality operator (allows to compare plat_target_t
* to nullptr)
*
* @param[in] i_rhs the right side of equality operation
*
* @return whether the passed pointer is equal to the underlying
* TARGETING::Target* pointer of plat_target_t
*/
bool operator==(const TARGETING::Target* const i_rhs) const
{
return (iv_pTarget == i_rhs);
}
/**
* @brief Overloaded inequality operator
*
* @param[in] i_rhs the right side of inequality operation
*
* @return whether the passed pointer is not equal to the underlying
* TARGETING::Target* pointer of plat_target_t
*/
bool operator!=(const TARGETING::Target* const i_rhs) const
{
return (iv_pTarget != i_rhs);
}
/**
* @brief Overloaded less than operator
*
* @param[in] i_rhs the right-side plat_target_handle_t
*
* @return whether this class' Target* is less that right-side's
*/
bool operator<(const plat_target_handle_t& i_rhs) const
{
return iv_pTarget < i_rhs.iv_pTarget;
}
/**
* @brief The getter function for internal iv_multicast member
*
* @return true if target supports multicast; false otherwise
*/
bool isMulticast() const
{
return iv_multicast;
}
/**
* @brief The getter function for internal iv_group member
*
* @return The multicast group requested for this target
* @note The returned value only makes sense if isMulticast is true
*/
MulticastGroup getMulticastGroup() const
{
return iv_group;
}
/**
* @brief The getter function for internal iv_multicastOp member
*
* @return The type of multicast operation requested
*/
MulticastType getMulticastOp() const
{
return iv_multicastOp;
}
/**
* @brief The getter function for internal iv_coreSelect member
*
* @return Which cores to run the SCOM op on
*/
MulticastCoreSelect getCoreSelect() const
{
return iv_coreSelect;
}
}; //class plat_target_handle_t
// Forward declaration
uint64_t getMulticastAddr(uint64_t i_addr,
MulticastGroup i_group,
MulticastType i_op,
MulticastCoreSelect i_coreSelect);
/// @brief Get the multicast children targets
/// @param[in] i_target The parent target
/// @param[in] i_child The child targeting type
/// @return TargetHandleList a list of the multicast children targets
// TODO: move function to .C in other commit
inline TARGETING::TargetHandleList getMulticastChildren(plat_target_handle_t i_target,
TARGETING::TYPE i_child)
{
errlHndl_t l_errl = nullptr;
uint64_t l_buffer = 0x0;
size_t l_size = sizeof(l_buffer);
// TODO: make these symbolic in other commit
uint64_t mcastGrp1ScomAddr = 0xF0001;
uint64_t mcastBitSelectAddr = 0xF0008;
TARGETING::TargetHandleList l_children, o_list;
TARGETING::Target* l_hbTarg = i_target; //force a cast operator
// Before doing anything, make sure the target we have is a valid type
// to be a multicast base
assert( TARGETING::TYPE_PROC == l_hbTarg->getAttr<TARGETING::ATTR_TYPE>(),
"getMulticastChildren: Unsupported multicast type 0x%X used",
l_hbTarg->getAttr<TARGETING::ATTR_TYPE>() );
uint64_t l_writeData = 0;
l_errl = deviceWrite(l_hbTarg, &l_writeData, l_size, DEVICE_SCOM_ADDRESS(mcastBitSelectAddr));
if (l_errl)
{
FAPI_ERR("getMulticastChildren: Error from deviceWrite");
l_errl->collectTrace(FAPI_TRACE_NAME, 256 );
l_errl->collectTrace(FAPI_IMP_TRACE_NAME, 384 );
errlCommit(l_errl, SECURE_COMP_ID);
}
else
{
assert(l_size == sizeof(l_buffer), "size of buffer changed after deviceWrite");
mcastGrp1ScomAddr = getMulticastAddr(mcastGrp1ScomAddr, i_target.getMulticastGroup(),
fapi2::MULTICAST_BITX, MCCORE_NONE);
/*
* This "magic" SCOM operation will perform a "grab bit 0" multicast
* read from an address in the PCB slave that is guaranteed to be
* readable (since it does not depend on a chiplet being powered/
* enabled/clocked) and always have bit 0 set to '1'
* (per definition).
* The result of the operation will be a 64bit value that will
* contain said bit 0, i.e. a '1' for all members of the multicast
* group, and a '0' for all others.
*/
// This function contains two scoms so not necessarily thread safe
// Each individual scom is protected, but not the greater operation
l_errl = deviceRead(l_hbTarg, static_cast<void *>(&l_buffer), l_size,
DEVICE_SCOM_ADDRESS(mcastGrp1ScomAddr));
if (l_errl)
{
FAPI_ERR("getMulticastChildren: Error from deviceRead");
errlCommit(l_errl, SECURE_COMP_ID);
}
else
{
assert(l_size == sizeof(l_buffer), "size of buffer changed after deviceRead");
getChildChiplets(l_children, l_hbTarg, i_child, false);
for (auto& l_tar : l_children)
{
// Get each pervasive parent
TARGETING::TargetHandleList l_parentList;
TARGETING::getParentPervasiveTargetsByState(l_parentList,
l_tar,
TARGETING::CLASS_NA,
TARGETING::TYPE_PERV,
TARGETING::UTIL_FILTER_ALL);
if (l_parentList.size() == 1)
{
TARGETING::Target* l_parentTarget = l_parentList[0];
const int l_unit = l_parentTarget->getAttr<TARGETING::ATTR_CHIP_UNIT>();
// Check if the chip_unit has an enabled bit from the deviceRead
if ((l_buffer >> (63 - l_unit)) & 1)
{
o_list.push_back(l_tar);
}
}
}
}
}
return o_list;
}
} // End namespace fapi2
#endif // __FAPI2_PLAT_TARGET__
<commit_msg>Hostboot getCoreSelect for unicast target<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/include/usr/fapi2/plat_target.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file plat_target.H
/// @brief Define FAPI2 target functions for the platform layer.
///
#ifndef __FAPI2_PLAT_TARGET__
#define __FAPI2_PLAT_TARGET__
// HB platform support
#include <targeting/common/target.H>
#include <multicast_defs.H>
#include <multicast_group_defs.H>
#include <devicefw/userif.H>
#include <targeting/common/utilFilter.H>
#include <fapiPlatTrace.H>
#include <errl/errlmanager.H>
namespace fapi2
{
// Since the EKB definition of MulticastCoreSelect does not contain
// an "invalid"/"no core selected" enum, declare one here for initialization
// convenience purposes.
static const MulticastCoreSelect MCCORE_NONE =
static_cast<MulticastCoreSelect>(0);
// local const due to include issues
const uint8_t NUM_CORES_PER_EQ = 4;
/**
* @brief plat_target_handle_t class
*
* This class serves as a wrapper for TARGETING::Target and multicast-
* specific attributes. This class allows conversion from fapi2::Target
* to TARGETING::Target and in the other direction via overloaded
* constructors and conversion operators.
* Conversion examples:
* fapi2::Target<fapi2::TARGET_TYPE_CORE>l_fapiCore(l_targetingCore)
* TARGETING::Target* l_targetingCore = l_fapiCore.get()
*/
class plat_target_handle_t
{
private:
const TARGETING::Target* iv_pTarget; // Hostboot target type
bool iv_multicast; // Whether a multicast SCOM op
// is to be executed on this target
MulticastGroup iv_group; // The selected group for multicast
MulticastType iv_multicastOp; // The type of multicast operation
MulticastCoreSelect iv_coreSelect; // Which cores to run SCOM op on
public:
/**
* @brief Parametrized constructor for plat_target_handle_t
*
* @param[in] i_target the const target for which to construct
* plat_target_handle_t
* @param[in] i_multicast whether the plat_target_handle_t is
* a multicast target wrapper
* @param[in] i_group the multicast group
* @param[in] i_op the type of multicast operation
* @param[in] i_coreSelect which cores to run the operation on
*/
plat_target_handle_t(const TARGETING::Target* i_target = nullptr,
bool i_multicast = false,
MulticastGroup i_group = MCGROUP_ALL,
MulticastType i_op = MULTICAST_OR,
MulticastCoreSelect i_coreSelect = MCCORE_NONE):
iv_pTarget(i_target),
iv_multicast(i_multicast),
iv_group(i_group),
iv_multicastOp(i_op),
iv_coreSelect(i_coreSelect)
{
if ((i_target != nullptr) && (!i_multicast))
{
if (i_target->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_CORE)
{
const uint8_t l_chip_unit = i_target->getAttr<TARGETING::ATTR_CHIP_UNIT>();
// calculate the chip number relative to the EQ
const uint8_t l_chip_unit_eq = l_chip_unit % NUM_CORES_PER_EQ;
switch (l_chip_unit_eq)
{
// seed the iv_coreSelect with the proper multicast mask
case(0): iv_coreSelect=MCCORE_0; break;
case(1): iv_coreSelect=MCCORE_1; break;
case(2): iv_coreSelect=MCCORE_2; break;
case(3): iv_coreSelect=MCCORE_3; break;
default:
// Impossible, but to be safe
assert(0, "plat_target_handle_t Bug must be one of the values above");
}
}
}
}
/**
* @brief fapi2::Target to TARGETING::Target* converter
*
* @return the underlying TARGETING::Target*
*/
operator TARGETING::Target*() const
{
return const_cast<TARGETING::Target*>(iv_pTarget);
}
/**
* @brief fapi2::Target to const TARGETING::Target* converter
*
* @return the underlying const TARGETING::Target*
*/
operator const TARGETING::Target*() const
{
return iv_pTarget;
}
/**
* @brief Overloaded equality operator (allows to compare plat_target_t
* to nullptr)
*
* @param[in] i_rhs the right side of equality operation
*
* @return whether the passed pointer is equal to the underlying
* TARGETING::Target* pointer of plat_target_t
*/
bool operator==(const TARGETING::Target* const i_rhs) const
{
return (iv_pTarget == i_rhs);
}
/**
* @brief Overloaded inequality operator
*
* @param[in] i_rhs the right side of inequality operation
*
* @return whether the passed pointer is not equal to the underlying
* TARGETING::Target* pointer of plat_target_t
*/
bool operator!=(const TARGETING::Target* const i_rhs) const
{
return (iv_pTarget != i_rhs);
}
/**
* @brief Overloaded less than operator
*
* @param[in] i_rhs the right-side plat_target_handle_t
*
* @return whether this class' Target* is less that right-side's
*/
bool operator<(const plat_target_handle_t& i_rhs) const
{
return iv_pTarget < i_rhs.iv_pTarget;
}
/**
* @brief The getter function for internal iv_multicast member
*
* @return true if target supports multicast; false otherwise
*/
bool isMulticast() const
{
return iv_multicast;
}
/**
* @brief The getter function for internal iv_group member
*
* @return The multicast group requested for this target
* @note The returned value only makes sense if isMulticast is true
*/
MulticastGroup getMulticastGroup() const
{
return iv_group;
}
/**
* @brief The getter function for internal iv_multicastOp member
*
* @return The type of multicast operation requested
*/
MulticastType getMulticastOp() const
{
return iv_multicastOp;
}
/**
* @brief The getter function for internal iv_coreSelect member
*
* @return Which cores to run the SCOM op on
*/
MulticastCoreSelect getCoreSelect() const
{
return iv_coreSelect;
}
}; //class plat_target_handle_t
// Forward declaration
uint64_t getMulticastAddr(uint64_t i_addr,
MulticastGroup i_group,
MulticastType i_op,
MulticastCoreSelect i_coreSelect);
/// @brief Get the multicast children targets
/// @param[in] i_target The parent target
/// @param[in] i_child The child targeting type
/// @return TargetHandleList a list of the multicast children targets
// TODO: move function to .C in other commit
inline TARGETING::TargetHandleList getMulticastChildren(plat_target_handle_t i_target,
TARGETING::TYPE i_child)
{
errlHndl_t l_errl = nullptr;
uint64_t l_buffer = 0x0;
size_t l_size = sizeof(l_buffer);
// TODO: make these symbolic in other commit
uint64_t mcastGrp1ScomAddr = 0xF0001;
uint64_t mcastBitSelectAddr = 0xF0008;
TARGETING::TargetHandleList l_children, o_list;
TARGETING::Target* l_hbTarg = i_target; //force a cast operator
// Before doing anything, make sure the target we have is a valid type
// to be a multicast base
assert( TARGETING::TYPE_PROC == l_hbTarg->getAttr<TARGETING::ATTR_TYPE>(),
"getMulticastChildren: Unsupported multicast type 0x%X used",
l_hbTarg->getAttr<TARGETING::ATTR_TYPE>() );
uint64_t l_writeData = 0;
l_errl = deviceWrite(l_hbTarg, &l_writeData, l_size, DEVICE_SCOM_ADDRESS(mcastBitSelectAddr));
if (l_errl)
{
FAPI_ERR("getMulticastChildren: Error from deviceWrite");
l_errl->collectTrace(FAPI_TRACE_NAME, 256 );
l_errl->collectTrace(FAPI_IMP_TRACE_NAME, 384 );
errlCommit(l_errl, SECURE_COMP_ID);
}
else
{
assert(l_size == sizeof(l_buffer), "size of buffer changed after deviceWrite");
mcastGrp1ScomAddr = getMulticastAddr(mcastGrp1ScomAddr, i_target.getMulticastGroup(),
fapi2::MULTICAST_BITX, MCCORE_NONE);
/*
* This "magic" SCOM operation will perform a "grab bit 0" multicast
* read from an address in the PCB slave that is guaranteed to be
* readable (since it does not depend on a chiplet being powered/
* enabled/clocked) and always have bit 0 set to '1'
* (per definition).
* The result of the operation will be a 64bit value that will
* contain said bit 0, i.e. a '1' for all members of the multicast
* group, and a '0' for all others.
*/
// This function contains two scoms so not necessarily thread safe
// Each individual scom is protected, but not the greater operation
l_errl = deviceRead(l_hbTarg, static_cast<void *>(&l_buffer), l_size,
DEVICE_SCOM_ADDRESS(mcastGrp1ScomAddr));
if (l_errl)
{
FAPI_ERR("getMulticastChildren: Error from deviceRead");
errlCommit(l_errl, SECURE_COMP_ID);
}
else
{
assert(l_size == sizeof(l_buffer), "size of buffer changed after deviceRead");
getChildChiplets(l_children, l_hbTarg, i_child, false);
for (auto& l_tar : l_children)
{
// Get each pervasive parent
TARGETING::TargetHandleList l_parentList;
TARGETING::getParentPervasiveTargetsByState(l_parentList,
l_tar,
TARGETING::CLASS_NA,
TARGETING::TYPE_PERV,
TARGETING::UTIL_FILTER_ALL);
if (l_parentList.size() == 1)
{
TARGETING::Target* l_parentTarget = l_parentList[0];
const int l_unit = l_parentTarget->getAttr<TARGETING::ATTR_CHIP_UNIT>();
// Check if the chip_unit has an enabled bit from the deviceRead
if ((l_buffer >> (63 - l_unit)) & 1)
{
o_list.push_back(l_tar);
}
}
}
}
}
return o_list;
}
} // End namespace fapi2
#endif // __FAPI2_PLAT_TARGET__
<|endoftext|>
|
<commit_before><commit_msg>A follow-up to r40192. Change the log message to avoid confusion. The original log message sounded like SSL renegotiation was attempted.<commit_after><|endoftext|>
|
<commit_before>#include "rollinghash.h"
#include "builtinmutation.h"
#include "util.h"
#include <memory.h>
// we use 1G memory
const int BLOOM_FILTER_LENGTH = (1<<29);
RollingHash::RollingHash(int window, bool allowTwoSub) {
mWindow = min(48, window);
mAllowTwoSub = allowTwoSub;
mBloomFilterArray = new char[BLOOM_FILTER_LENGTH];
memset(mBloomFilterArray, 0, BLOOM_FILTER_LENGTH * sizeof(char));
}
RollingHash::~RollingHash() {
delete mBloomFilterArray;
mBloomFilterArray = NULL;
}
void RollingHash::initMutations(vector<Mutation>& mutationList) {
for(int i=0; i<mutationList.size(); i++) {
Mutation m = mutationList[i];
string s1 = m.mLeft + m.mCenter + m.mRight;
add(s1, i);
const int margin = 4;
// handle the case mRight is incomplete, but at least margin
int left = max((size_t)mWindow+2, m.mLeft.length() + m.mCenter.length() + margin+1);
string s2 = s1.substr(left - (mWindow+2), mWindow+2);
add(s2,i);
//handle the case mleft is incomplete, but at least margin
int right = min(s1.length() - (mWindow+2), m.mLeft.length()-margin-1);
string s3 = s1.substr(right, mWindow+2);
add(s3,i);
}
}
map<long, vector<int> > RollingHash::getKeyTargets() {
return mKeyTargets;
}
bool RollingHash::add(string s, int target, bool allowIndel) {
if(s.length() < mWindow + 2)
return false;
int center = s.length() / 2;
int start = center - mWindow / 2;
// mutations cannot happen in skipStart to skipEnd
int skipStart = center - 1;
int skipEnd = center + 1;
const char* data = s.c_str();
long* hashes = new long[mWindow];
memset(hashes, 0, sizeof(long)*mWindow);
long* accum = new long[mWindow];
memset(accum, 0, sizeof(long)*mWindow);
// initialize
long origin = 0;
for(int i=0; i<mWindow; i++) {
hashes[i] = hash(data[start + i], i);
origin += hashes[i];
accum[i] = origin;
}
addHash(origin, target);
const char bases[4] = {'A', 'T', 'C', 'G'};
// make subsitution hashes, we allow up to 2 sub mutations
for(int i=0; i<mWindow; i++) {
if(i+start >= skipStart && i+start <= skipEnd )
continue;
for(int b1=0; b1<4; b1++){
char base1 = bases[b1];
if(base1 == data[start + i])
continue;
long mut1 = origin - hash(data[start + i], i) + hash(base1, i);
addHash(mut1, target);
/*cout<<mut1<<":"<<i<<base1<<":";
for(int p=0; p<mWindow; p++) {
if(p==i)
cout<<base1;
else
cout<<data[start + p];
}
cout<<endl;*/
if(mAllowTwoSub) {
for(int j=i+1; j<mWindow; j++) {
if(j+start >= skipStart && j+start <= skipEnd )
continue;
for(int b2=0; b2<4; b2++){
char base2 = bases[b2];
if(base2 == data[start + j])
continue;
long mut2 = mut1 - hash(data[start + j], j) + hash(base2, j);
addHash(mut2, target);
/*cout<<mut2<<":"<<i<<base1<<j<<base2<<":";
for(int p=0; p<mWindow; p++) {
if(p==i)
cout<<base1;
else if(p==j)
cout<<base2;
else
cout<<data[start + p];
}
cout<<endl;*/
}
}
}
}
}
int altForDel = start - 1;
long altVal = hash(data[altForDel], 0);
if(allowIndel) {
// make indel hashes, we only allow 1 indel
for(int i=0; i<mWindow; i++) {
if(i+start >= skipStart && i+start <= skipEnd )
continue;
// make del of i first
long mutOfDel;
if (i==0)
mutOfDel = origin - accum[i] + altVal;
else
mutOfDel = origin - accum[i] + (accum[i-1]<<1) + altVal;
if(mutOfDel != origin)
addHash(mutOfDel, target);
// make insertion
for(int b=0; b<4; b++){
char base = bases[b];
// shift the first base
long mutOfIns = origin - accum[i] + hash(base, i) + ((accum[i] - hashes[0]) >> 1);
if(mutOfIns != origin && mutOfIns != mutOfDel){
addHash(mutOfIns, target);
/*cout << mutOfIns<<", insert at " << i << " with " << base << ": ";
for(int p=1;p<=i;p++)
cout << data[start + p];
cout << base;
for(int p=i+1;p<mWindow;p++)
cout << data[start + p];
cout << endl;*/
}
}
}
}
delete hashes;
delete accum;
}
vector<int> RollingHash::hitTargets(const string s) {
vector<int> ret;
if(s.length() < mWindow)
return ret;
const char* data = s.c_str();
// initialize
long curHash = 0;
for(int i=0; i<mWindow; i++) {
long h = hash(data[i], i);
curHash += h;
}
addHit(ret, curHash);
for(int i=mWindow; i<s.length(); i++) {
curHash = ((curHash - hash(data[i - mWindow], 0))>>1) + hash(data[i], mWindow-1);
addHit(ret, curHash);
}
return ret;
}
inline void RollingHash::addHit(vector<int>& ret, long hash) {
//update bloom filter array
const long bloomFilterFactors[3] = {1713137323, 371371377, 7341234131};
for(int b=0; b<3; b++) {
if(mBloomFilterArray[(bloomFilterFactors[b] * hash) & (BLOOM_FILTER_LENGTH-1)] == 0 )
return;
}
if(mKeyTargets.count(hash)) {
for(int i=0; i<mKeyTargets[hash].size(); i++) {
int val = mKeyTargets[hash][i];
bool alreadyIn = false;
for(int j=0; j<ret.size(); j++) {
if(val == ret[j]){
alreadyIn = true;
break;
}
}
if(!alreadyIn) {
ret.push_back(val);
}
}
}
}
void RollingHash::addHash(long hash, int target) {
if(mKeyTargets.count(hash) == 0)
mKeyTargets[hash] = vector<int>();
else {
for(int i=0; i<mKeyTargets[hash].size(); i++) {
if(mKeyTargets[hash][i] == target)
return ;
}
}
mKeyTargets[hash].push_back(target);
//update bloom filter array
const long bloomFilterFactors[3] = {1713137323, 371371377, 7341234131};
for(int b=0; b<3; b++) {
mBloomFilterArray[(bloomFilterFactors[b] * hash) & (BLOOM_FILTER_LENGTH-1) ] = 1;
}
}
inline long RollingHash::char2val(char c) {
switch (c) {
case 'A':
return 517;
case 'T':
return 433;
case 'C':
return 1123;
case 'G':
return 127;
case 'N':
return 1;
default:
return 0;
}
}
inline long RollingHash::hash(char c, int pos) {
long val = char2val(c);
const long num = 2;
return val * (num << pos );
}
void RollingHash::dump() {
map<long, vector<int> >::iterator iter;
for(iter= mKeyTargets.begin(); iter!=mKeyTargets.end(); iter++) {
if(iter->second.size() < 2)
continue;
cout << iter->first << endl;
for(int i=0; i<iter->second.size(); i++)
cout << iter->second[i] << "\t";
cout << endl;
}
}
bool RollingHash::test(){
vector<Mutation> mutationList = Mutation::parseBuiltIn();
RollingHash rh(48);
rh.initMutations(mutationList);
bool result = true;
for(int i=0; i<mutationList.size(); i++) {
Mutation m = mutationList[i];
string s = m.mLeft + m.mCenter + m.mRight;
vector<int> targets = rh.hitTargets(s);
cout << i << ", " << s << endl;
bool found = false;
for(int t=0; t<targets.size(); t++){
cout << targets[t] << "\t";
if(targets[t] == i)
found = true;
}
cout << endl;
result &= found;
}
return result;
}
<commit_msg>small fix for indel<commit_after>#include "rollinghash.h"
#include "builtinmutation.h"
#include "util.h"
#include <memory.h>
// we use 1G memory
const int BLOOM_FILTER_LENGTH = (1<<29);
RollingHash::RollingHash(int window, bool allowTwoSub) {
mWindow = min(48, window);
mAllowTwoSub = allowTwoSub;
mBloomFilterArray = new char[BLOOM_FILTER_LENGTH];
memset(mBloomFilterArray, 0, BLOOM_FILTER_LENGTH * sizeof(char));
}
RollingHash::~RollingHash() {
delete mBloomFilterArray;
mBloomFilterArray = NULL;
}
void RollingHash::initMutations(vector<Mutation>& mutationList) {
for(int i=0; i<mutationList.size(); i++) {
Mutation m = mutationList[i];
string s1 = m.mLeft + m.mCenter + m.mRight;
add(s1, i, !m.isSmallIndel());
const int margin = 4;
// handle the case mRight is incomplete, but at least margin
int left = max((size_t)mWindow+2, m.mLeft.length() + m.mCenter.length() + margin+1);
string s2 = s1.substr(left - (mWindow+2), mWindow+2);
add(s2,i, !m.isSmallIndel());
//handle the case mleft is incomplete, but at least margin
int right = min(s1.length() - (mWindow+2), m.mLeft.length()-margin-1);
string s3 = s1.substr(right, mWindow+2);
add(s3,i, !m.isSmallIndel());
}
}
map<long, vector<int> > RollingHash::getKeyTargets() {
return mKeyTargets;
}
bool RollingHash::add(string s, int target, bool allowIndel) {
if(s.length() < mWindow + 2)
return false;
int center = s.length() / 2;
int start = center - mWindow / 2;
// mutations cannot happen in skipStart to skipEnd
int skipStart = center - 1;
int skipEnd = center + 1;
const char* data = s.c_str();
long* hashes = new long[mWindow];
memset(hashes, 0, sizeof(long)*mWindow);
long* accum = new long[mWindow];
memset(accum, 0, sizeof(long)*mWindow);
// initialize
long origin = 0;
for(int i=0; i<mWindow; i++) {
hashes[i] = hash(data[start + i], i);
origin += hashes[i];
accum[i] = origin;
}
addHash(origin, target);
const char bases[4] = {'A', 'T', 'C', 'G'};
// make subsitution hashes, we allow up to 2 sub mutations
for(int i=0; i<mWindow; i++) {
if(i+start >= skipStart && i+start <= skipEnd )
continue;
for(int b1=0; b1<4; b1++){
char base1 = bases[b1];
if(base1 == data[start + i])
continue;
long mut1 = origin - hash(data[start + i], i) + hash(base1, i);
addHash(mut1, target);
/*cout<<mut1<<":"<<i<<base1<<":";
for(int p=0; p<mWindow; p++) {
if(p==i)
cout<<base1;
else
cout<<data[start + p];
}
cout<<endl;*/
if(mAllowTwoSub) {
for(int j=i+1; j<mWindow; j++) {
if(j+start >= skipStart && j+start <= skipEnd )
continue;
for(int b2=0; b2<4; b2++){
char base2 = bases[b2];
if(base2 == data[start + j])
continue;
long mut2 = mut1 - hash(data[start + j], j) + hash(base2, j);
addHash(mut2, target);
/*cout<<mut2<<":"<<i<<base1<<j<<base2<<":";
for(int p=0; p<mWindow; p++) {
if(p==i)
cout<<base1;
else if(p==j)
cout<<base2;
else
cout<<data[start + p];
}
cout<<endl;*/
}
}
}
}
}
int altForDel = start - 1;
long altVal = hash(data[altForDel], 0);
if(allowIndel) {
// make indel hashes, we only allow 1 indel
for(int i=0; i<mWindow; i++) {
if(i+start >= skipStart && i+start <= skipEnd )
continue;
// make del of i first
long mutOfDel;
if (i==0)
mutOfDel = origin - accum[i] + altVal;
else
mutOfDel = origin - accum[i] + (accum[i-1]<<1) + altVal;
if(mutOfDel != origin)
addHash(mutOfDel, target);
// make insertion
for(int b=0; b<4; b++){
char base = bases[b];
// shift the first base
long mutOfIns = origin - accum[i] + hash(base, i) + ((accum[i] - hashes[0]) >> 1);
if(mutOfIns != origin && mutOfIns != mutOfDel){
addHash(mutOfIns, target);
/*cout << mutOfIns<<", insert at " << i << " with " << base << ": ";
for(int p=1;p<=i;p++)
cout << data[start + p];
cout << base;
for(int p=i+1;p<mWindow;p++)
cout << data[start + p];
cout << endl;*/
}
}
}
}
delete hashes;
delete accum;
}
vector<int> RollingHash::hitTargets(const string s) {
vector<int> ret;
if(s.length() < mWindow)
return ret;
const char* data = s.c_str();
// initialize
long curHash = 0;
for(int i=0; i<mWindow; i++) {
long h = hash(data[i], i);
curHash += h;
}
addHit(ret, curHash);
for(int i=mWindow; i<s.length(); i++) {
curHash = ((curHash - hash(data[i - mWindow], 0))>>1) + hash(data[i], mWindow-1);
addHit(ret, curHash);
}
return ret;
}
inline void RollingHash::addHit(vector<int>& ret, long hash) {
//update bloom filter array
const long bloomFilterFactors[3] = {1713137323, 371371377, 7341234131};
for(int b=0; b<3; b++) {
if(mBloomFilterArray[(bloomFilterFactors[b] * hash) & (BLOOM_FILTER_LENGTH-1)] == 0 )
return;
}
if(mKeyTargets.count(hash)) {
for(int i=0; i<mKeyTargets[hash].size(); i++) {
int val = mKeyTargets[hash][i];
bool alreadyIn = false;
for(int j=0; j<ret.size(); j++) {
if(val == ret[j]){
alreadyIn = true;
break;
}
}
if(!alreadyIn) {
ret.push_back(val);
}
}
}
}
void RollingHash::addHash(long hash, int target) {
if(mKeyTargets.count(hash) == 0)
mKeyTargets[hash] = vector<int>();
else {
for(int i=0; i<mKeyTargets[hash].size(); i++) {
if(mKeyTargets[hash][i] == target)
return ;
}
}
mKeyTargets[hash].push_back(target);
//update bloom filter array
const long bloomFilterFactors[3] = {1713137323, 371371377, 7341234131};
for(int b=0; b<3; b++) {
mBloomFilterArray[(bloomFilterFactors[b] * hash) & (BLOOM_FILTER_LENGTH-1) ] = 1;
}
}
inline long RollingHash::char2val(char c) {
switch (c) {
case 'A':
return 517;
case 'T':
return 433;
case 'C':
return 1123;
case 'G':
return 127;
case 'N':
return 1;
default:
return 0;
}
}
inline long RollingHash::hash(char c, int pos) {
long val = char2val(c);
const long num = 2;
return val * (num << pos );
}
void RollingHash::dump() {
map<long, vector<int> >::iterator iter;
for(iter= mKeyTargets.begin(); iter!=mKeyTargets.end(); iter++) {
if(iter->second.size() < 2)
continue;
cout << iter->first << endl;
for(int i=0; i<iter->second.size(); i++)
cout << iter->second[i] << "\t";
cout << endl;
}
}
bool RollingHash::test(){
vector<Mutation> mutationList = Mutation::parseBuiltIn();
RollingHash rh(48);
rh.initMutations(mutationList);
bool result = true;
for(int i=0; i<mutationList.size(); i++) {
Mutation m = mutationList[i];
string s = m.mLeft + m.mCenter + m.mRight;
vector<int> targets = rh.hitTargets(s);
cout << i << ", " << s << endl;
bool found = false;
for(int t=0; t<targets.size(); t++){
cout << targets[t] << "\t";
if(targets[t] == i)
found = true;
}
cout << endl;
result &= found;
}
return result;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/include/usr/ipmi/ipmiwatchdog.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2014,2015 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __IPMIWATCHDOG_IPMIWATCHDOG_H
#define __IPMIWATCHDOG_IPMIWATCHDOG_H
/**
* @file ipmiwatchdog.H
*
* IPMI watchdog interface launched from the IStep Dispatcher
*
*/
/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>
#include <errl/errlentry.H>
namespace IPMIWATCHDOG
{
/******************************************************************************/
// Globals/Constants
/******************************************************************************/
/**
* @brief the default watchdog countdown setting it to 120 seconds.
*
* @TODO RTC:124499 revisit after performace improvments
*
*/
const uint16_t DEFAULT_WATCHDOG_COUNTDOWN = 120;
/**
* @brief the default watchdog countdown for transition between hostboot
* and OPAL (value is in seconds)
*/
const uint16_t DEFAULT_HB_OPAL_TRANSITION_COUNTDOWN = 30;
/******************************************************************************/
// Typedef/Enumerations
/******************************************************************************/
/**
* @brief Used in Byte 1 field of the set watchdog command
*/
enum TIMER_USE
{
DO_NOT_LOG = 0x80, // bit 7
DO_NOT_STOP = 0x40, // bit 6
BIOS_FRB2 = 0x01, // bit 0
BIOS_POST = 0x02, // bit 1
OS_LOAD = 0x03, // bits 0 & 1
SMS_OS = 0x04, // bit 2
OEM = 0x05, // bits 2 & 0
};
/**
* @brief Used in Byte 2 field of the set watchdog command
*/
enum TIMER_ACTIONS
{
NO_ACTIONS = 0x00, // all bits
PRE_TIMEOUT_INT_SMI = 0x10, // bit 4
PRE_TIMEOUT_INT_NMI = 0x20, // bit 5
PRE_TIMEOUT_INT_MSG = 0x30, // bits 4 & 5
TIMEOUT_HARD_RESET = 0x01, // bit 0
TIMEOUT_PWR_DOWN = 0x02, // bit 1
TIMEOUT_PWR_CYCLE = 0x03, // bits 0 & 1
};
/**
* @brief Used in Byte 4 field of the set watchdog command
* set to 1 to clear the flag set to 0 to leave alone
*/
enum TIMER_USE_CLR_FLAGS
{
OEM_FLAG = 0x20, // bit 5
SMS_OS_FLAG = 0x10, // bit 4
OS_LOAD_FLAG = 0x08, // bit 3
BIOS_POST_FLAG = 0x04, // bit 2
BIOS_FRB2_FLAG = 0x02, // bit 1
};
/******************************************************************************/
// Functions
/******************************************************************************/
/**
* @brief Sets the ipmi watchdog timer on the BMC
*
* Called by hostboot to set a watchdog timer on the BMC
* @param[in] i_countdown_secs, initial countdown in seconds
* @param[in] i_timer_use, Sets watchdog timer use bits.
* @param[in] i_timer_action, Sets watchdog timer experation action.
* @param[in] i_timer_clr_flag, Sets the Watchdog interrupt flag to clear.
* @return none
*/
errlHndl_t setWatchDogTimer( const uint16_t i_countdown_secs,
const uint8_t i_timer_use
= static_cast<uint8_t>(DO_NOT_STOP | BIOS_FRB2),
const TIMER_ACTIONS i_timer_action
= TIMEOUT_PWR_CYCLE,
const TIMER_USE_CLR_FLAGS i_timer_clr_flag
= BIOS_FRB2_FLAG);
/**
* @brief Resets the ipmi watchdog timer on the BMC
*
* Called by hostboot to reset a watchdog timer countdown on the BMC.
* If the BMC returns an error code indicating the watchdog timer
* has not been started, this function will start the watchdog timer.
*
* @return error
*/
errlHndl_t resetWatchDogTimer();
} // namespace
#endif
<commit_msg>Change IPMI watchdog action to hard reset<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/include/usr/ipmi/ipmiwatchdog.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2014,2015 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __IPMIWATCHDOG_IPMIWATCHDOG_H
#define __IPMIWATCHDOG_IPMIWATCHDOG_H
/**
* @file ipmiwatchdog.H
*
* IPMI watchdog interface launched from the IStep Dispatcher
*
*/
/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>
#include <errl/errlentry.H>
namespace IPMIWATCHDOG
{
/******************************************************************************/
// Globals/Constants
/******************************************************************************/
/**
* @brief the default watchdog countdown setting it to 120 seconds.
*
* @TODO RTC:124499 revisit after performace improvments
*
*/
const uint16_t DEFAULT_WATCHDOG_COUNTDOWN = 120;
/**
* @brief the default watchdog countdown for transition between hostboot
* and OPAL (value is in seconds)
*/
const uint16_t DEFAULT_HB_OPAL_TRANSITION_COUNTDOWN = 30;
/******************************************************************************/
// Typedef/Enumerations
/******************************************************************************/
/**
* @brief Used in Byte 1 field of the set watchdog command
*/
enum TIMER_USE
{
DO_NOT_LOG = 0x80, // bit 7
DO_NOT_STOP = 0x40, // bit 6
BIOS_FRB2 = 0x01, // bit 0
BIOS_POST = 0x02, // bit 1
OS_LOAD = 0x03, // bits 0 & 1
SMS_OS = 0x04, // bit 2
OEM = 0x05, // bits 2 & 0
};
/**
* @brief Used in Byte 2 field of the set watchdog command
*/
enum TIMER_ACTIONS
{
NO_ACTIONS = 0x00, // all bits
PRE_TIMEOUT_INT_SMI = 0x10, // bit 4
PRE_TIMEOUT_INT_NMI = 0x20, // bit 5
PRE_TIMEOUT_INT_MSG = 0x30, // bits 4 & 5
TIMEOUT_HARD_RESET = 0x01, // bit 0
TIMEOUT_PWR_DOWN = 0x02, // bit 1
TIMEOUT_PWR_CYCLE = 0x03, // bits 0 & 1
};
/**
* @brief Used in Byte 4 field of the set watchdog command
* set to 1 to clear the flag set to 0 to leave alone
*/
enum TIMER_USE_CLR_FLAGS
{
OEM_FLAG = 0x20, // bit 5
SMS_OS_FLAG = 0x10, // bit 4
OS_LOAD_FLAG = 0x08, // bit 3
BIOS_POST_FLAG = 0x04, // bit 2
BIOS_FRB2_FLAG = 0x02, // bit 1
};
/******************************************************************************/
// Functions
/******************************************************************************/
/**
* @brief Sets the ipmi watchdog timer on the BMC
*
* Called by hostboot to set a watchdog timer on the BMC
* @param[in] i_countdown_secs, initial countdown in seconds
* @param[in] i_timer_use, Sets watchdog timer use bits.
* @param[in] i_timer_action, Sets watchdog timer experation action.
* @param[in] i_timer_clr_flag, Sets the Watchdog interrupt flag to clear.
* @return none
*/
errlHndl_t setWatchDogTimer( const uint16_t i_countdown_secs,
const uint8_t i_timer_use
= static_cast<uint8_t>(DO_NOT_STOP | BIOS_FRB2),
const TIMER_ACTIONS i_timer_action
= TIMEOUT_HARD_RESET,
const TIMER_USE_CLR_FLAGS i_timer_clr_flag
= BIOS_FRB2_FLAG);
/**
* @brief Resets the ipmi watchdog timer on the BMC
*
* Called by hostboot to reset a watchdog timer countdown on the BMC.
* If the BMC returns an error code indicating the watchdog timer
* has not been started, this function will start the watchdog timer.
*
* @return error
*/
errlHndl_t resetWatchDogTimer();
} // namespace
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: factory.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-08 07:38:10 $
*
* 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
*
************************************************************************/
#define _SOT_FACTORY_CXX
#define SOT_STRING_LIST
#include <factory.hxx>
#include <tools/debug.hxx>
#include <tools/string.hxx>
#include <object.hxx>
#include <sotdata.hxx>
#include <clsids.hxx>
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DATAFLAVOR_HPP_
#include <com/sun/star/datatransfer/DataFlavor.hpp>
#endif
/************** class SotData_Impl *********************************************/
/*************************************************************************
|* SotData_Impl::SotData_Impl
|*
|* Beschreibung
*************************************************************************/
SotData_Impl::SotData_Impl()
: nSvObjCount( 0 )
, pObjectList( NULL )
, pFactoryList( NULL )
, pSotObjectFactory( NULL )
, pSotStorageStreamFactory( NULL )
, pSotStorageFactory( NULL )
, pDataFlavorList( NULL )
{
}
/*************************************************************************
|* SOTDATA()
|*
|* Beschreibung
*************************************************************************/
namespace { struct ImplData : public rtl::Static<SotData_Impl, ImplData> {}; }
SotData_Impl * SOTDATA()
{
return &ImplData::get();
}
/*************************************************************************
|* SotFactory::DeInit()
|*
|* Beschreibung
*************************************************************************/
void SotFactory::DeInit()
{
SotData_Impl * pSotData = SOTDATA();
if( pSotData->nSvObjCount )
{
#ifdef DBG_UTIL
ByteString aStr( "Objects alive: " );
aStr.Append( ByteString::CreateFromInt32( pSotData->nSvObjCount ) );
DBG_WARNING( aStr.GetBuffer() )
/*
SotObjectList *pObjList = pSotData->pObjectList;
if( pObjList )
{
SotObject * p = pObjList->First();
while( p )
{
String aStr( "Factory: " );
aStr += p->GetSvFactory()->GetClassName();
aStr += " Count: ";
aStr += p->GetRefCount();
DBG_TRACE( "\tReferences:" );
p->TestObjRef( FALSE );
#ifdef TEST_INVARIANT
DBG_TRACE( "\tInvariant:" );
p->TestInvariant( TRUE );
#endif
p = pObjList->Next();
}
}
*/
#endif
return;
}
// Muss von hinten nach vorne zerstoert werden. Das ist die umgekehrte
// Reihenfolge der Erzeugung
SotFactoryList* pFactoryList = pSotData->pFactoryList;
if( pFactoryList )
{
SotFactory * pFact = pFactoryList->Last();
while( NULL != (pFact = pFactoryList->Remove()) )
{
delete pFact;
pFact = pFactoryList->Last();
}
delete pFactoryList;
pSotData->pFactoryList = NULL;
}
delete pSotData->pObjectList;
pSotData->pObjectList = NULL;
if( pSotData->pDataFlavorList )
{
for( ULONG i = 0, nMax = pSotData->pDataFlavorList->Count(); i < nMax; i++ )
delete (::com::sun::star::datatransfer::DataFlavor*) pSotData->pDataFlavorList->GetObject( i );
delete pSotData->pDataFlavorList;
pSotData->pDataFlavorList = NULL;
}
//delete pSOTDATA();
//SOTDATA() = NULL;
}
/************** class SotFactory *****************************************/
/*************************************************************************
|* SotFactory::SotFactory()
|*
|* Beschreibung
*************************************************************************/
TYPEINIT0(SotFactory);
SotFactory::SotFactory( const SvGlobalName & rName,
const String & rClassName,
CreateInstanceType pCreateFuncP )
: SvGlobalName ( rName )
, pCreateFunc ( pCreateFuncP )
, aClassName ( rClassName )
, nSuperCount ( 0 )
, pSuperClasses ( NULL )
{
#ifdef DBG_UTIL
SvGlobalName aEmptyName;
if( aEmptyName != *this )
{ // wegen Sfx-BasicFactories
DBG_ASSERT( aEmptyName != *this, "create factory without SvGlobalName" )
if( Find( *this ) )
{
/*
String aStr( GetClassName() );
aStr += ", UniqueName: ";
aStr += GetHexName();
aStr += ", create factories with the same unique name";
DBG_ERROR( aStr );
*/
DBG_ERROR( "create factories with the same unique name" );
}
}
#endif
SotData_Impl * pSotData = SOTDATA();
if( !pSotData->pFactoryList )
pSotData->pFactoryList = new SotFactoryList();
// muss nach hinten, wegen Reihenfolge beim zerstoeren
pSotData->pFactoryList->Insert( this, LIST_APPEND );
}
//=========================================================================
SotFactory::~SotFactory()
{
delete [] pSuperClasses;
}
/*************************************************************************
|* SotFactory::
|*
|* Beschreibung Zugriffsmethoden auf SotData_Impl-Daten
*************************************************************************/
UINT32 SotFactory::GetSvObjectCount()
{
return SOTDATA()->nSvObjCount;
}
const SotFactoryList * SotFactory::GetFactoryList()
{
return SOTDATA()->pFactoryList;
}
/*************************************************************************
|* SotFactory::Find()
|*
|* Beschreibung
*************************************************************************/
const SotFactory* SotFactory::Find( const SvGlobalName & rFactName )
{
SvGlobalName aEmpty;
SotData_Impl * pSotData = SOTDATA();
if( rFactName != aEmpty && pSotData->pFactoryList )
{
SotFactory * pFact = pSotData->pFactoryList->First();
while( pFact )
{
if( *pFact == rFactName )
return pFact;
pFact = pSotData->pFactoryList->Next();
}
}
return 0;
}
/*************************************************************************
|* SotFactory::PutSuperClass()
|*
|* Beschreibung
*************************************************************************/
void SotFactory::PutSuperClass( const SotFactory * pFact )
{
nSuperCount++;
if( !pSuperClasses )
pSuperClasses = new const SotFactory * [ nSuperCount ];
else
{
const SotFactory ** pTmp = new const SotFactory * [ nSuperCount ];
memcpy( (void *)pTmp, (void *)pSuperClasses,
sizeof( void * ) * (nSuperCount -1) );
delete [] pSuperClasses;
pSuperClasses = pTmp;
}
pSuperClasses[ nSuperCount -1 ] = pFact;
}
/*************************************************************************
|* SotFactory::IncSvObjectCount()
|*
|* Beschreibung
*************************************************************************/
void SotFactory::IncSvObjectCount( SotObject * pObj )
{
SotData_Impl * pSotData = SOTDATA();
pSotData->nSvObjCount++;
if( !pSotData->pObjectList )
pSotData->pObjectList = new SotObjectList();
if( pObj )
pSotData->pObjectList->Insert( pObj );
}
/*************************************************************************
|* SotFactory::DecSvObjectCount()
|*
|* Beschreibung
*************************************************************************/
void SotFactory::DecSvObjectCount( SotObject * pObj )
{
SotData_Impl * pSotData = SOTDATA();
pSotData->nSvObjCount--;
if( pObj )
pSotData->pObjectList->Remove( pObj );
if( !pSotData->nSvObjCount )
{
//keine internen und externen Referenzen mehr
}
}
/*************************************************************************
|* SotFactory::TestInvariant()
|*
|* Beschreibung
*************************************************************************/
void SotFactory::TestInvariant()
{
#ifdef TEST_INVARIANT
SotData_Impl * pSotData = SOTDATA();
if( pSotData->pObjectList )
{
ULONG nCount = pSotData->pObjectList->Count();
for( ULONG i = 0; i < nCount ; i++ )
{
pSotData->pObjectList->GetObject( i )->TestInvariant( FALSE );
}
}
#endif
}
/*************************************************************************
|* SotFactory::CreateInstance()
|*
|* Beschreibung
*************************************************************************/
void * SotFactory::CreateInstance( SotObject ** ppObj ) const
{
DBG_ASSERT( pCreateFunc, "SotFactory::CreateInstance: pCreateFunc == 0" );
return pCreateFunc( ppObj );
}
//=========================================================================
void * SotFactory::CastAndAddRef
(
SotObject * pObj /* Das Objekt von dem der Typ gepr"uft wird. */
) const
/* [Beschreibung]
Ist eine Optimierung, damit die Ref-Klassen k"urzer implementiert
werden k"onnen. pObj wird auf den Typ der Factory gecastet.
In c++ (wenn es immer erlaubt w"are) w"urde der void * wie im
Beispiel gebildet.
Factory der Klasse SvPersist.
void * p = (void *)(SvPersist *)pObj;
[R"uckgabewert]
void *, NULL, pObj war NULL oder das Objekt war nicht vom Typ
der Factory.
Ansonsten wird pObj zuerst auf den Typ der Factory
gecastet und dann auf void *.
[Querverweise]
<SotObject::CastAndAddRef>
*/
{
return pObj ? pObj->CastAndAddRef( this ) : NULL;
}
//=========================================================================
void * SotFactory::AggCastAndAddRef
(
SotObject * pObj /* Das Objekt von dem der Typ gepr"uft wird. */
) const
/* [Beschreibung]
Ist eine Optimierung, damit die Ref-Klassen k"urzer implementiert
werden k"onnen. pObj wird auf den Typ der Factory gecastet.
In c++ (wenn es immer erlaubt w"are) w"urde der void * wie im
Beispiel gebildet.
Factory der Klasse SvPersist.
void * p = (void *)(SvPersist *)pObj;
Hinzu kommt noch, dass ein Objekt aus meheren c++ Objekten
zusammengesetzt sein kann. Diese Methode sucht nach einem
passenden Objekt.
[R"uckgabewert]
void *, NULL, pObj war NULL oder das Objekt war nicht vom Typ
der Factory.
Ansonsten wird pObj zuerst auf den Typ der Factory
gecastet und dann auf void *.
[Querverweise]
<SvObject::AggCast>
*/
{
void * pRet = NULL;
if( pObj )
{
pRet = pObj->AggCast( this );
if( pRet )
pObj->AddRef();
}
return pRet;
}
/*************************************************************************
|* SotFactory::Is()
|*
|* Beschreibung
*************************************************************************/
BOOL SotFactory::Is( const SotFactory * pSuperCl ) const
{
if( this == pSuperCl )
return TRUE;
for( USHORT i = 0; i < nSuperCount; i++ )
{
if( pSuperClasses[ i ]->Is( pSuperCl ) )
return TRUE;
}
return FALSE;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.9.8); FILE MERGED 2005/10/21 16:25:05 pl 1.9.8.1: #i55991# removed warnings for linux platform<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: factory.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2006-06-20 05:52:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#define _SOT_FACTORY_CXX
#define SOT_STRING_LIST
#include <factory.hxx>
#include <tools/debug.hxx>
#include <tools/string.hxx>
#include <object.hxx>
#include <sotdata.hxx>
#include <clsids.hxx>
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DATAFLAVOR_HPP_
#include <com/sun/star/datatransfer/DataFlavor.hpp>
#endif
/************** class SotData_Impl *********************************************/
/*************************************************************************
|* SotData_Impl::SotData_Impl
|*
|* Beschreibung
*************************************************************************/
SotData_Impl::SotData_Impl()
: nSvObjCount( 0 )
, pObjectList( NULL )
, pFactoryList( NULL )
, pSotObjectFactory( NULL )
, pSotStorageStreamFactory( NULL )
, pSotStorageFactory( NULL )
, pDataFlavorList( NULL )
{
}
/*************************************************************************
|* SOTDATA()
|*
|* Beschreibung
*************************************************************************/
namespace { struct ImplData : public rtl::Static<SotData_Impl, ImplData> {}; }
SotData_Impl * SOTDATA()
{
return &ImplData::get();
}
/*************************************************************************
|* SotFactory::DeInit()
|*
|* Beschreibung
*************************************************************************/
void SotFactory::DeInit()
{
SotData_Impl * pSotData = SOTDATA();
if( pSotData->nSvObjCount )
{
#ifdef DBG_UTIL
ByteString aStr( "Objects alive: " );
aStr.Append( ByteString::CreateFromInt32( pSotData->nSvObjCount ) );
DBG_WARNING( aStr.GetBuffer() )
/*
SotObjectList *pObjList = pSotData->pObjectList;
if( pObjList )
{
SotObject * p = pObjList->First();
while( p )
{
String aStr( "Factory: " );
aStr += p->GetSvFactory()->GetClassName();
aStr += " Count: ";
aStr += p->GetRefCount();
DBG_TRACE( "\tReferences:" );
p->TestObjRef( FALSE );
#ifdef TEST_INVARIANT
DBG_TRACE( "\tInvariant:" );
p->TestInvariant( TRUE );
#endif
p = pObjList->Next();
}
}
*/
#endif
return;
}
// Muss von hinten nach vorne zerstoert werden. Das ist die umgekehrte
// Reihenfolge der Erzeugung
SotFactoryList* pFactoryList = pSotData->pFactoryList;
if( pFactoryList )
{
SotFactory * pFact = pFactoryList->Last();
while( NULL != (pFact = pFactoryList->Remove()) )
{
delete pFact;
pFact = pFactoryList->Last();
}
delete pFactoryList;
pSotData->pFactoryList = NULL;
}
delete pSotData->pObjectList;
pSotData->pObjectList = NULL;
if( pSotData->pDataFlavorList )
{
for( ULONG i = 0, nMax = pSotData->pDataFlavorList->Count(); i < nMax; i++ )
delete (::com::sun::star::datatransfer::DataFlavor*) pSotData->pDataFlavorList->GetObject( i );
delete pSotData->pDataFlavorList;
pSotData->pDataFlavorList = NULL;
}
//delete pSOTDATA();
//SOTDATA() = NULL;
}
/************** class SotFactory *****************************************/
/*************************************************************************
|* SotFactory::SotFactory()
|*
|* Beschreibung
*************************************************************************/
TYPEINIT0(SotFactory);
SotFactory::SotFactory( const SvGlobalName & rName,
const String & rClassName,
CreateInstanceType pCreateFuncP )
: SvGlobalName ( rName )
, nSuperCount ( 0 )
, pSuperClasses ( NULL )
, pCreateFunc ( pCreateFuncP )
, aClassName ( rClassName )
{
#ifdef DBG_UTIL
SvGlobalName aEmptyName;
if( aEmptyName != *this )
{ // wegen Sfx-BasicFactories
DBG_ASSERT( aEmptyName != *this, "create factory without SvGlobalName" )
if( Find( *this ) )
{
/*
String aStr( GetClassName() );
aStr += ", UniqueName: ";
aStr += GetHexName();
aStr += ", create factories with the same unique name";
DBG_ERROR( aStr );
*/
DBG_ERROR( "create factories with the same unique name" );
}
}
#endif
SotData_Impl * pSotData = SOTDATA();
if( !pSotData->pFactoryList )
pSotData->pFactoryList = new SotFactoryList();
// muss nach hinten, wegen Reihenfolge beim zerstoeren
pSotData->pFactoryList->Insert( this, LIST_APPEND );
}
//=========================================================================
SotFactory::~SotFactory()
{
delete [] pSuperClasses;
}
/*************************************************************************
|* SotFactory::
|*
|* Beschreibung Zugriffsmethoden auf SotData_Impl-Daten
*************************************************************************/
UINT32 SotFactory::GetSvObjectCount()
{
return SOTDATA()->nSvObjCount;
}
const SotFactoryList * SotFactory::GetFactoryList()
{
return SOTDATA()->pFactoryList;
}
/*************************************************************************
|* SotFactory::Find()
|*
|* Beschreibung
*************************************************************************/
const SotFactory* SotFactory::Find( const SvGlobalName & rFactName )
{
SvGlobalName aEmpty;
SotData_Impl * pSotData = SOTDATA();
if( rFactName != aEmpty && pSotData->pFactoryList )
{
SotFactory * pFact = pSotData->pFactoryList->First();
while( pFact )
{
if( *pFact == rFactName )
return pFact;
pFact = pSotData->pFactoryList->Next();
}
}
return 0;
}
/*************************************************************************
|* SotFactory::PutSuperClass()
|*
|* Beschreibung
*************************************************************************/
void SotFactory::PutSuperClass( const SotFactory * pFact )
{
nSuperCount++;
if( !pSuperClasses )
pSuperClasses = new const SotFactory * [ nSuperCount ];
else
{
const SotFactory ** pTmp = new const SotFactory * [ nSuperCount ];
memcpy( (void *)pTmp, (void *)pSuperClasses,
sizeof( void * ) * (nSuperCount -1) );
delete [] pSuperClasses;
pSuperClasses = pTmp;
}
pSuperClasses[ nSuperCount -1 ] = pFact;
}
/*************************************************************************
|* SotFactory::IncSvObjectCount()
|*
|* Beschreibung
*************************************************************************/
void SotFactory::IncSvObjectCount( SotObject * pObj )
{
SotData_Impl * pSotData = SOTDATA();
pSotData->nSvObjCount++;
if( !pSotData->pObjectList )
pSotData->pObjectList = new SotObjectList();
if( pObj )
pSotData->pObjectList->Insert( pObj );
}
/*************************************************************************
|* SotFactory::DecSvObjectCount()
|*
|* Beschreibung
*************************************************************************/
void SotFactory::DecSvObjectCount( SotObject * pObj )
{
SotData_Impl * pSotData = SOTDATA();
pSotData->nSvObjCount--;
if( pObj )
pSotData->pObjectList->Remove( pObj );
if( !pSotData->nSvObjCount )
{
//keine internen und externen Referenzen mehr
}
}
/*************************************************************************
|* SotFactory::TestInvariant()
|*
|* Beschreibung
*************************************************************************/
void SotFactory::TestInvariant()
{
#ifdef TEST_INVARIANT
SotData_Impl * pSotData = SOTDATA();
if( pSotData->pObjectList )
{
ULONG nCount = pSotData->pObjectList->Count();
for( ULONG i = 0; i < nCount ; i++ )
{
pSotData->pObjectList->GetObject( i )->TestInvariant( FALSE );
}
}
#endif
}
/*************************************************************************
|* SotFactory::CreateInstance()
|*
|* Beschreibung
*************************************************************************/
void * SotFactory::CreateInstance( SotObject ** ppObj ) const
{
DBG_ASSERT( pCreateFunc, "SotFactory::CreateInstance: pCreateFunc == 0" );
return pCreateFunc( ppObj );
}
//=========================================================================
void * SotFactory::CastAndAddRef
(
SotObject * pObj /* Das Objekt von dem der Typ gepr"uft wird. */
) const
/* [Beschreibung]
Ist eine Optimierung, damit die Ref-Klassen k"urzer implementiert
werden k"onnen. pObj wird auf den Typ der Factory gecastet.
In c++ (wenn es immer erlaubt w"are) w"urde der void * wie im
Beispiel gebildet.
Factory der Klasse SvPersist.
void * p = (void *)(SvPersist *)pObj;
[R"uckgabewert]
void *, NULL, pObj war NULL oder das Objekt war nicht vom Typ
der Factory.
Ansonsten wird pObj zuerst auf den Typ der Factory
gecastet und dann auf void *.
[Querverweise]
<SotObject::CastAndAddRef>
*/
{
return pObj ? pObj->CastAndAddRef( this ) : NULL;
}
//=========================================================================
void * SotFactory::AggCastAndAddRef
(
SotObject * pObj /* Das Objekt von dem der Typ gepr"uft wird. */
) const
/* [Beschreibung]
Ist eine Optimierung, damit die Ref-Klassen k"urzer implementiert
werden k"onnen. pObj wird auf den Typ der Factory gecastet.
In c++ (wenn es immer erlaubt w"are) w"urde der void * wie im
Beispiel gebildet.
Factory der Klasse SvPersist.
void * p = (void *)(SvPersist *)pObj;
Hinzu kommt noch, dass ein Objekt aus meheren c++ Objekten
zusammengesetzt sein kann. Diese Methode sucht nach einem
passenden Objekt.
[R"uckgabewert]
void *, NULL, pObj war NULL oder das Objekt war nicht vom Typ
der Factory.
Ansonsten wird pObj zuerst auf den Typ der Factory
gecastet und dann auf void *.
[Querverweise]
<SvObject::AggCast>
*/
{
void * pRet = NULL;
if( pObj )
{
pRet = pObj->AggCast( this );
if( pRet )
pObj->AddRef();
}
return pRet;
}
/*************************************************************************
|* SotFactory::Is()
|*
|* Beschreibung
*************************************************************************/
BOOL SotFactory::Is( const SotFactory * pSuperCl ) const
{
if( this == pSuperCl )
return TRUE;
for( USHORT i = 0; i < nSuperCount; i++ )
{
if( pSuperClasses[ i ]->Is( pSuperCl ) )
return TRUE;
}
return FALSE;
}
<|endoftext|>
|
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGOutputSocket.cpp
Author: Bertrand Coconnier
Date started: 09/10/11
Purpose: Manage output of sim parameters to a socket
Called by: FGOutput
------------- Copyright (C) 2011 Bertrand Coconnier -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU 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., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
This is the place where you create output routines to dump data for perusal
later.
HISTORY
--------------------------------------------------------------------------------
09/10/11 BC Created
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include <cstring>
#include <cstdlib>
#include "FGOutputSocket.h"
#include "FGFDMExec.h"
#include "models/FGAerodynamics.h"
#include "models/FGAccelerations.h"
#include "models/FGAircraft.h"
#include "models/FGAtmosphere.h"
#include "models/FGAuxiliary.h"
#include "models/FGPropulsion.h"
#include "models/FGMassBalance.h"
#include "models/FGPropagate.h"
#include "models/FGGroundReactions.h"
#include "models/FGFCS.h"
#include "models/atmosphere/FGWinds.h"
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id: FGOutputSocket.cpp,v 1.2 2012/12/15 16:13:57 bcoconni Exp $";
static const char *IdHdr = ID_OUTPUTSOCKET;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGOutputSocket::FGOutputSocket(FGFDMExec* fdmex) :
FGOutputType(fdmex),
socket(0)
{
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGOutputSocket::~FGOutputSocket()
{
delete socket;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutputSocket::SetOutputName(const string& fname)
{
// tokenize the output name
size_t dot_pos = fname.find(':', 0);
size_t slash_pos = fname.find('/', 0);
string name = fname.substr(0, dot_pos);
string proto = "TCP";
if(dot_pos + 1 < slash_pos)
proto = fname.substr(dot_pos + 1, slash_pos - 1);
string port = "1138";
if(slash_pos < string::npos)
port = fname.substr(slash_pos + 1, string::npos);
// set the model name
Name = name + ":" + port + "/" + proto;
// set the socket params
SockName = name;
SockPort = atoi(port.c_str());
if (proto == "UDP")
SockProtocol = FGfdmSocket::ptUDP;
else // Default to TCP
SockProtocol = FGfdmSocket::ptTCP;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutputSocket::Load(Element* el)
{
if (!FGOutputType::Load(el))
return false;
SetOutputName(el->GetAttributeValue("name") + ":" +
el->GetAttributeValue("protocol") + "/" +
el->GetAttributeValue("port"));
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutputSocket::InitModel(void)
{
if (FGOutputType::InitModel()) {
string scratch;
delete socket;
socket = new FGfdmSocket(SockName, SockPort, SockProtocol);
if (socket == 0) return false;
if (!socket->GetConnectStatus()) return false;
socket->Clear();
socket->Clear("<LABELS>");
socket->Append("Time");
if (SubSystems & ssAerosurfaces) {
socket->Append("Aileron Command");
socket->Append("Elevator Command");
socket->Append("Rudder Command");
socket->Append("Flap Command");
socket->Append("Left Aileron Position");
socket->Append("Right Aileron Position");
socket->Append("Elevator Position");
socket->Append("Rudder Position");
socket->Append("Flap Position");
}
if (SubSystems & ssRates) {
socket->Append("P");
socket->Append("Q");
socket->Append("R");
socket->Append("PDot");
socket->Append("QDot");
socket->Append("RDot");
}
if (SubSystems & ssVelocities) {
socket->Append("QBar");
socket->Append("Vtotal");
socket->Append("UBody");
socket->Append("VBody");
socket->Append("WBody");
socket->Append("UAero");
socket->Append("VAero");
socket->Append("WAero");
socket->Append("Vn");
socket->Append("Ve");
socket->Append("Vd");
}
if (SubSystems & ssForces) {
socket->Append("F_Drag");
socket->Append("F_Side");
socket->Append("F_Lift");
socket->Append("LoD");
socket->Append("Fx");
socket->Append("Fy");
socket->Append("Fz");
}
if (SubSystems & ssMoments) {
socket->Append("L");
socket->Append("M");
socket->Append("N");
}
if (SubSystems & ssAtmosphere) {
socket->Append("Rho");
socket->Append("SL pressure");
socket->Append("Ambient pressure");
socket->Append("Turbulence Magnitude");
socket->Append("Turbulence Direction X");
socket->Append("Turbulence Direction Y");
socket->Append("Turbulence Direction Z");
socket->Append("NWind");
socket->Append("EWind");
socket->Append("DWind");
}
if (SubSystems & ssMassProps) {
socket->Append("Ixx");
socket->Append("Ixy");
socket->Append("Ixz");
socket->Append("Iyx");
socket->Append("Iyy");
socket->Append("Iyz");
socket->Append("Izx");
socket->Append("Izy");
socket->Append("Izz");
socket->Append("Mass");
socket->Append("Xcg");
socket->Append("Ycg");
socket->Append("Zcg");
}
if (SubSystems & ssPropagate) {
socket->Append("Altitude");
socket->Append("Phi (deg)");
socket->Append("Tht (deg)");
socket->Append("Psi (deg)");
socket->Append("Alpha (deg)");
socket->Append("Beta (deg)");
socket->Append("Latitude (deg)");
socket->Append("Longitude (deg)");
}
if (SubSystems & ssAeroFunctions) {
scratch = Aerodynamics->GetAeroFunctionStrings(",");
if (scratch.length() != 0) socket->Append(scratch);
}
if (SubSystems & ssFCS) {
scratch = FCS->GetComponentStrings(",");
if (scratch.length() != 0) socket->Append(scratch);
}
if (SubSystems & ssGroundReactions)
socket->Append(GroundReactions->GetGroundReactionStrings(","));
if (SubSystems & ssPropulsion && Propulsion->GetNumEngines() > 0)
socket->Append(Propulsion->GetPropulsionStrings(","));
if (OutputProperties.size() > 0) {
for (unsigned int i=0;i<OutputProperties.size();i++)
socket->Append(OutputProperties[i]->GetPrintableName());
}
socket->Send();
return true;
}
return false;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutputSocket::Print(void)
{
string asciiData, scratch;
if (socket == 0) return;
if (!socket->GetConnectStatus()) return;
socket->Clear();
socket->Append(FDMExec->GetSimTime());
if (SubSystems & ssAerosurfaces) {
socket->Append(FCS->GetDaCmd());
socket->Append(FCS->GetDeCmd());
socket->Append(FCS->GetDrCmd());
socket->Append(FCS->GetDfCmd());
socket->Append(FCS->GetDaLPos());
socket->Append(FCS->GetDaRPos());
socket->Append(FCS->GetDePos());
socket->Append(FCS->GetDrPos());
socket->Append(FCS->GetDfPos());
}
if (SubSystems & ssRates) {
socket->Append(radtodeg*Propagate->GetPQR(eP));
socket->Append(radtodeg*Propagate->GetPQR(eQ));
socket->Append(radtodeg*Propagate->GetPQR(eR));
socket->Append(radtodeg*Accelerations->GetPQRdot(eP));
socket->Append(radtodeg*Accelerations->GetPQRdot(eQ));
socket->Append(radtodeg*Accelerations->GetPQRdot(eR));
}
if (SubSystems & ssVelocities) {
socket->Append(Auxiliary->Getqbar());
socket->Append(Auxiliary->GetVt());
socket->Append(Propagate->GetUVW(eU));
socket->Append(Propagate->GetUVW(eV));
socket->Append(Propagate->GetUVW(eW));
socket->Append(Auxiliary->GetAeroUVW(eU));
socket->Append(Auxiliary->GetAeroUVW(eV));
socket->Append(Auxiliary->GetAeroUVW(eW));
socket->Append(Propagate->GetVel(eNorth));
socket->Append(Propagate->GetVel(eEast));
socket->Append(Propagate->GetVel(eDown));
}
if (SubSystems & ssForces) {
socket->Append(Aerodynamics->GetvFw()(eDrag));
socket->Append(Aerodynamics->GetvFw()(eSide));
socket->Append(Aerodynamics->GetvFw()(eLift));
socket->Append(Aerodynamics->GetLoD());
socket->Append(Aircraft->GetForces(eX));
socket->Append(Aircraft->GetForces(eY));
socket->Append(Aircraft->GetForces(eZ));
}
if (SubSystems & ssMoments) {
socket->Append(Aircraft->GetMoments(eL));
socket->Append(Aircraft->GetMoments(eM));
socket->Append(Aircraft->GetMoments(eN));
}
if (SubSystems & ssAtmosphere) {
socket->Append(Atmosphere->GetDensity());
socket->Append(Atmosphere->GetPressureSL());
socket->Append(Atmosphere->GetPressure());
socket->Append(Winds->GetTurbMagnitude());
socket->Append(Winds->GetTurbDirection().Dump(","));
socket->Append(Winds->GetTotalWindNED().Dump(","));
}
if (SubSystems & ssMassProps) {
socket->Append(MassBalance->GetJ()(1,1));
socket->Append(MassBalance->GetJ()(1,2));
socket->Append(MassBalance->GetJ()(1,3));
socket->Append(MassBalance->GetJ()(2,1));
socket->Append(MassBalance->GetJ()(2,2));
socket->Append(MassBalance->GetJ()(2,3));
socket->Append(MassBalance->GetJ()(3,1));
socket->Append(MassBalance->GetJ()(3,2));
socket->Append(MassBalance->GetJ()(3,3));
socket->Append(MassBalance->GetMass());
socket->Append(MassBalance->GetXYZcg()(eX));
socket->Append(MassBalance->GetXYZcg()(eY));
socket->Append(MassBalance->GetXYZcg()(eZ));
}
if (SubSystems & ssPropagate) {
socket->Append(Propagate->GetAltitudeASL());
socket->Append(radtodeg*Propagate->GetEuler(ePhi));
socket->Append(radtodeg*Propagate->GetEuler(eTht));
socket->Append(radtodeg*Propagate->GetEuler(ePsi));
socket->Append(Auxiliary->Getalpha(inDegrees));
socket->Append(Auxiliary->Getbeta(inDegrees));
socket->Append(Propagate->GetLocation().GetLatitudeDeg());
socket->Append(Propagate->GetLocation().GetLongitudeDeg());
}
if (SubSystems & ssAeroFunctions) {
scratch = Aerodynamics->GetAeroFunctionValues(",");
if (scratch.length() != 0) socket->Append(scratch);
}
if (SubSystems & ssFCS) {
scratch = FCS->GetComponentValues(",");
if (scratch.length() != 0) socket->Append(scratch);
}
if (SubSystems & ssGroundReactions) {
socket->Append(GroundReactions->GetGroundReactionValues(","));
}
if (SubSystems & ssPropulsion && Propulsion->GetNumEngines() > 0) {
socket->Append(Propulsion->GetPropulsionValues(","));
}
for (unsigned int i=0;i<OutputProperties.size();i++) {
socket->Append(OutputProperties[i]->getDoubleValue());
}
socket->Send();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutputSocket::SocketStatusOutput(const string& out_str)
{
string asciiData;
if (socket == 0) return;
socket->Clear();
asciiData = string("<STATUS>") + out_str;
socket->Append(asciiData.c_str());
socket->Send();
}
}
<commit_msg>Bug fix : the protocol was not correctly extracted and always falled back to default TCP. Thanks to Ron Jensen for reporting the bug (the network interface between FG and JSBSim was broken)<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGOutputSocket.cpp
Author: Bertrand Coconnier
Date started: 09/10/11
Purpose: Manage output of sim parameters to a socket
Called by: FGOutput
------------- Copyright (C) 2011 Bertrand Coconnier -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU 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., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
This is the place where you create output routines to dump data for perusal
later.
HISTORY
--------------------------------------------------------------------------------
09/10/11 BC Created
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include <cstring>
#include <cstdlib>
#include "FGOutputSocket.h"
#include "FGFDMExec.h"
#include "models/FGAerodynamics.h"
#include "models/FGAccelerations.h"
#include "models/FGAircraft.h"
#include "models/FGAtmosphere.h"
#include "models/FGAuxiliary.h"
#include "models/FGPropulsion.h"
#include "models/FGMassBalance.h"
#include "models/FGPropagate.h"
#include "models/FGGroundReactions.h"
#include "models/FGFCS.h"
#include "models/atmosphere/FGWinds.h"
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id: FGOutputSocket.cpp,v 1.3 2013/01/06 15:56:40 bcoconni Exp $";
static const char *IdHdr = ID_OUTPUTSOCKET;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGOutputSocket::FGOutputSocket(FGFDMExec* fdmex) :
FGOutputType(fdmex),
socket(0)
{
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGOutputSocket::~FGOutputSocket()
{
delete socket;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutputSocket::SetOutputName(const string& fname)
{
// tokenize the output name
size_t dot_pos = fname.find(':', 0);
size_t slash_pos = fname.find('/', 0);
string name = fname.substr(0, dot_pos);
string proto = "TCP";
if(dot_pos + 1 < slash_pos)
proto = fname.substr(dot_pos + 1, slash_pos - dot_pos - 1);
string port = "1138";
if(slash_pos < string::npos)
port = fname.substr(slash_pos + 1, string::npos);
// set the model name
Name = name + ":" + port + "/" + proto;
// set the socket params
SockName = name;
SockPort = atoi(port.c_str());
if (proto == "UDP")
SockProtocol = FGfdmSocket::ptUDP;
else // Default to TCP
SockProtocol = FGfdmSocket::ptTCP;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutputSocket::Load(Element* el)
{
if (!FGOutputType::Load(el))
return false;
SetOutputName(el->GetAttributeValue("name") + ":" +
el->GetAttributeValue("protocol") + "/" +
el->GetAttributeValue("port"));
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutputSocket::InitModel(void)
{
if (FGOutputType::InitModel()) {
string scratch;
delete socket;
socket = new FGfdmSocket(SockName, SockPort, SockProtocol);
if (socket == 0) return false;
if (!socket->GetConnectStatus()) return false;
socket->Clear();
socket->Clear("<LABELS>");
socket->Append("Time");
if (SubSystems & ssAerosurfaces) {
socket->Append("Aileron Command");
socket->Append("Elevator Command");
socket->Append("Rudder Command");
socket->Append("Flap Command");
socket->Append("Left Aileron Position");
socket->Append("Right Aileron Position");
socket->Append("Elevator Position");
socket->Append("Rudder Position");
socket->Append("Flap Position");
}
if (SubSystems & ssRates) {
socket->Append("P");
socket->Append("Q");
socket->Append("R");
socket->Append("PDot");
socket->Append("QDot");
socket->Append("RDot");
}
if (SubSystems & ssVelocities) {
socket->Append("QBar");
socket->Append("Vtotal");
socket->Append("UBody");
socket->Append("VBody");
socket->Append("WBody");
socket->Append("UAero");
socket->Append("VAero");
socket->Append("WAero");
socket->Append("Vn");
socket->Append("Ve");
socket->Append("Vd");
}
if (SubSystems & ssForces) {
socket->Append("F_Drag");
socket->Append("F_Side");
socket->Append("F_Lift");
socket->Append("LoD");
socket->Append("Fx");
socket->Append("Fy");
socket->Append("Fz");
}
if (SubSystems & ssMoments) {
socket->Append("L");
socket->Append("M");
socket->Append("N");
}
if (SubSystems & ssAtmosphere) {
socket->Append("Rho");
socket->Append("SL pressure");
socket->Append("Ambient pressure");
socket->Append("Turbulence Magnitude");
socket->Append("Turbulence Direction X");
socket->Append("Turbulence Direction Y");
socket->Append("Turbulence Direction Z");
socket->Append("NWind");
socket->Append("EWind");
socket->Append("DWind");
}
if (SubSystems & ssMassProps) {
socket->Append("Ixx");
socket->Append("Ixy");
socket->Append("Ixz");
socket->Append("Iyx");
socket->Append("Iyy");
socket->Append("Iyz");
socket->Append("Izx");
socket->Append("Izy");
socket->Append("Izz");
socket->Append("Mass");
socket->Append("Xcg");
socket->Append("Ycg");
socket->Append("Zcg");
}
if (SubSystems & ssPropagate) {
socket->Append("Altitude");
socket->Append("Phi (deg)");
socket->Append("Tht (deg)");
socket->Append("Psi (deg)");
socket->Append("Alpha (deg)");
socket->Append("Beta (deg)");
socket->Append("Latitude (deg)");
socket->Append("Longitude (deg)");
}
if (SubSystems & ssAeroFunctions) {
scratch = Aerodynamics->GetAeroFunctionStrings(",");
if (scratch.length() != 0) socket->Append(scratch);
}
if (SubSystems & ssFCS) {
scratch = FCS->GetComponentStrings(",");
if (scratch.length() != 0) socket->Append(scratch);
}
if (SubSystems & ssGroundReactions)
socket->Append(GroundReactions->GetGroundReactionStrings(","));
if (SubSystems & ssPropulsion && Propulsion->GetNumEngines() > 0)
socket->Append(Propulsion->GetPropulsionStrings(","));
if (OutputProperties.size() > 0) {
for (unsigned int i=0;i<OutputProperties.size();i++)
socket->Append(OutputProperties[i]->GetPrintableName());
}
socket->Send();
return true;
}
return false;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutputSocket::Print(void)
{
string asciiData, scratch;
if (socket == 0) return;
if (!socket->GetConnectStatus()) return;
socket->Clear();
socket->Append(FDMExec->GetSimTime());
if (SubSystems & ssAerosurfaces) {
socket->Append(FCS->GetDaCmd());
socket->Append(FCS->GetDeCmd());
socket->Append(FCS->GetDrCmd());
socket->Append(FCS->GetDfCmd());
socket->Append(FCS->GetDaLPos());
socket->Append(FCS->GetDaRPos());
socket->Append(FCS->GetDePos());
socket->Append(FCS->GetDrPos());
socket->Append(FCS->GetDfPos());
}
if (SubSystems & ssRates) {
socket->Append(radtodeg*Propagate->GetPQR(eP));
socket->Append(radtodeg*Propagate->GetPQR(eQ));
socket->Append(radtodeg*Propagate->GetPQR(eR));
socket->Append(radtodeg*Accelerations->GetPQRdot(eP));
socket->Append(radtodeg*Accelerations->GetPQRdot(eQ));
socket->Append(radtodeg*Accelerations->GetPQRdot(eR));
}
if (SubSystems & ssVelocities) {
socket->Append(Auxiliary->Getqbar());
socket->Append(Auxiliary->GetVt());
socket->Append(Propagate->GetUVW(eU));
socket->Append(Propagate->GetUVW(eV));
socket->Append(Propagate->GetUVW(eW));
socket->Append(Auxiliary->GetAeroUVW(eU));
socket->Append(Auxiliary->GetAeroUVW(eV));
socket->Append(Auxiliary->GetAeroUVW(eW));
socket->Append(Propagate->GetVel(eNorth));
socket->Append(Propagate->GetVel(eEast));
socket->Append(Propagate->GetVel(eDown));
}
if (SubSystems & ssForces) {
socket->Append(Aerodynamics->GetvFw()(eDrag));
socket->Append(Aerodynamics->GetvFw()(eSide));
socket->Append(Aerodynamics->GetvFw()(eLift));
socket->Append(Aerodynamics->GetLoD());
socket->Append(Aircraft->GetForces(eX));
socket->Append(Aircraft->GetForces(eY));
socket->Append(Aircraft->GetForces(eZ));
}
if (SubSystems & ssMoments) {
socket->Append(Aircraft->GetMoments(eL));
socket->Append(Aircraft->GetMoments(eM));
socket->Append(Aircraft->GetMoments(eN));
}
if (SubSystems & ssAtmosphere) {
socket->Append(Atmosphere->GetDensity());
socket->Append(Atmosphere->GetPressureSL());
socket->Append(Atmosphere->GetPressure());
socket->Append(Winds->GetTurbMagnitude());
socket->Append(Winds->GetTurbDirection().Dump(","));
socket->Append(Winds->GetTotalWindNED().Dump(","));
}
if (SubSystems & ssMassProps) {
socket->Append(MassBalance->GetJ()(1,1));
socket->Append(MassBalance->GetJ()(1,2));
socket->Append(MassBalance->GetJ()(1,3));
socket->Append(MassBalance->GetJ()(2,1));
socket->Append(MassBalance->GetJ()(2,2));
socket->Append(MassBalance->GetJ()(2,3));
socket->Append(MassBalance->GetJ()(3,1));
socket->Append(MassBalance->GetJ()(3,2));
socket->Append(MassBalance->GetJ()(3,3));
socket->Append(MassBalance->GetMass());
socket->Append(MassBalance->GetXYZcg()(eX));
socket->Append(MassBalance->GetXYZcg()(eY));
socket->Append(MassBalance->GetXYZcg()(eZ));
}
if (SubSystems & ssPropagate) {
socket->Append(Propagate->GetAltitudeASL());
socket->Append(radtodeg*Propagate->GetEuler(ePhi));
socket->Append(radtodeg*Propagate->GetEuler(eTht));
socket->Append(radtodeg*Propagate->GetEuler(ePsi));
socket->Append(Auxiliary->Getalpha(inDegrees));
socket->Append(Auxiliary->Getbeta(inDegrees));
socket->Append(Propagate->GetLocation().GetLatitudeDeg());
socket->Append(Propagate->GetLocation().GetLongitudeDeg());
}
if (SubSystems & ssAeroFunctions) {
scratch = Aerodynamics->GetAeroFunctionValues(",");
if (scratch.length() != 0) socket->Append(scratch);
}
if (SubSystems & ssFCS) {
scratch = FCS->GetComponentValues(",");
if (scratch.length() != 0) socket->Append(scratch);
}
if (SubSystems & ssGroundReactions) {
socket->Append(GroundReactions->GetGroundReactionValues(","));
}
if (SubSystems & ssPropulsion && Propulsion->GetNumEngines() > 0) {
socket->Append(Propulsion->GetPropulsionValues(","));
}
for (unsigned int i=0;i<OutputProperties.size();i++) {
socket->Append(OutputProperties[i]->getDoubleValue());
}
socket->Send();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutputSocket::SocketStatusOutput(const string& out_str)
{
string asciiData;
if (socket == 0) return;
socket->Clear();
asciiData = string("<STATUS>") + out_str;
socket->Append(asciiData.c_str());
socket->Send();
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: redlnitr.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: fme $ $Date: 2002-04-22 12:35:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _REDLNITR_HXX
#define _REDLNITR_HXX
#include "ndhints.hxx"
#include "redlenum.hxx" // SwRedlineType
#include "swfont.hxx"
#ifndef _SVSTDARR_USHORTS
#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>
#endif
class SwTxtNode;
class SwDoc;
class SfxItemSet;
class SwAttrHandler;
class SwExtend
{
SwFont *pFnt;
const SvUShorts ⇒ // XAMA: Array of xub_StrLen
xub_StrLen nStart;
xub_StrLen nPos;
xub_StrLen nEnd;
sal_Bool _Leave( SwFont& rFnt, xub_StrLen nNew );
sal_Bool Inside() const { return ( nPos >= nStart && nPos < nEnd ); }
void ActualizeFont( SwFont &rFnt, xub_StrLen nAttr );
public:
SwExtend( const SvUShorts &rA, xub_StrLen nSt ) : rArr( rA ), pFnt(0),
nStart( nSt ), nPos( STRING_LEN ), nEnd( nStart + rA.Count() ) {}
~SwExtend() { delete pFnt; }
sal_Bool IsOn() const { return pFnt != 0; }
void Reset() { if( pFnt ) { delete pFnt; pFnt = NULL; } nPos = STRING_LEN; }
sal_Bool Leave( SwFont& rFnt, xub_StrLen nNew )
{ if( pFnt ) return _Leave( rFnt, nNew ); return sal_False; }
short Enter( SwFont& rFnt, xub_StrLen nNew );
xub_StrLen Next( xub_StrLen nNext );
SwFont* GetFont() { return pFnt; }
void UpdateFont( SwFont &rFnt ) { ActualizeFont( rFnt, rArr[ nPos - nStart ] ); }
};
class SwRedlineItr
{
SwpHtStart_SAR aHints;
const SwDoc& rDoc;
const SwTxtNode& rNd;
SwAttrHandler& rAttrHandler;
SfxItemSet *pSet;
SwExtend *pExt;
ULONG nNdIdx;
xub_StrLen nFirst;
xub_StrLen nAct;
xub_StrLen nStart;
xub_StrLen nEnd;
sal_Bool bOn;
sal_Bool bShow;
void _Clear( SwFont* pFnt );
sal_Bool _ChkSpecialUnderline() const;
void FillHints( MSHORT nAuthor, SwRedlineType eType );
short _Seek( SwFont& rFnt, xub_StrLen nNew, xub_StrLen nOld );
xub_StrLen _GetNextRedln( xub_StrLen nNext );
inline short EnterExtend( SwFont& rFnt, xub_StrLen nNew )
{ if( pExt ) return pExt->Enter( rFnt, nNew ); return 0; }
inline xub_StrLen NextExtend( xub_StrLen nNext )
{ if( pExt ) return pExt->Next( nNext ); return nNext; }
public:
SwRedlineItr( const SwTxtNode& rTxtNd, SwFont& rFnt, SwAttrHandler& rAH,
xub_StrLen nRedlPos, sal_Bool bShw, const SvUShorts *pArr = 0,
xub_StrLen nStart = STRING_LEN );
~SwRedlineItr();
inline sal_Bool IsOn() const { return bOn || ( pExt && pExt->IsOn() ); }
inline void Clear( SwFont* pFnt ) { if( bOn ) _Clear( pFnt ); }
void ChangeTxtAttr( SwFont* pFnt, SwTxtAttr &rHt, sal_Bool bChg );
inline short Seek( SwFont& rFnt, xub_StrLen nNew, xub_StrLen nOld )
{ if( bShow || pExt ) return _Seek( rFnt, nNew, nOld ); return 0; }
inline void Reset() { if( nAct != nFirst ) nAct = STRING_LEN;
if( pExt ) pExt->Reset(); }
inline xub_StrLen GetNextRedln( xub_StrLen nNext )
{ if( bShow || pExt ) return _GetNextRedln( nNext ); return nNext; }
inline sal_Bool ChkSpecialUnderline() const
{ if ( IsOn() ) return _ChkSpecialUnderline(); return sal_False; }
sal_Bool CheckLine( xub_StrLen nChkStart, xub_StrLen nChkEnd );
inline sal_Bool LeaveExtend( SwFont& rFnt, xub_StrLen nNew )
{ return pExt->Leave(rFnt, nNew ); }
inline sal_Bool ExtOn() { if( pExt ) return pExt->IsOn(); return sal_False; }
inline void UpdateExtFont( SwFont &rFnt ) {
ASSERT( ExtOn(), "UpdateExtFont without ExtOn" )
pExt->UpdateFont( rFnt ); }
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.1426); FILE MERGED 2005/09/05 13:41:04 rt 1.7.1426.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: redlnitr.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:04:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _REDLNITR_HXX
#define _REDLNITR_HXX
#include "ndhints.hxx"
#include "redlenum.hxx" // SwRedlineType
#include "swfont.hxx"
#ifndef _SVSTDARR_USHORTS
#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>
#endif
class SwTxtNode;
class SwDoc;
class SfxItemSet;
class SwAttrHandler;
class SwExtend
{
SwFont *pFnt;
const SvUShorts ⇒ // XAMA: Array of xub_StrLen
xub_StrLen nStart;
xub_StrLen nPos;
xub_StrLen nEnd;
sal_Bool _Leave( SwFont& rFnt, xub_StrLen nNew );
sal_Bool Inside() const { return ( nPos >= nStart && nPos < nEnd ); }
void ActualizeFont( SwFont &rFnt, xub_StrLen nAttr );
public:
SwExtend( const SvUShorts &rA, xub_StrLen nSt ) : rArr( rA ), pFnt(0),
nStart( nSt ), nPos( STRING_LEN ), nEnd( nStart + rA.Count() ) {}
~SwExtend() { delete pFnt; }
sal_Bool IsOn() const { return pFnt != 0; }
void Reset() { if( pFnt ) { delete pFnt; pFnt = NULL; } nPos = STRING_LEN; }
sal_Bool Leave( SwFont& rFnt, xub_StrLen nNew )
{ if( pFnt ) return _Leave( rFnt, nNew ); return sal_False; }
short Enter( SwFont& rFnt, xub_StrLen nNew );
xub_StrLen Next( xub_StrLen nNext );
SwFont* GetFont() { return pFnt; }
void UpdateFont( SwFont &rFnt ) { ActualizeFont( rFnt, rArr[ nPos - nStart ] ); }
};
class SwRedlineItr
{
SwpHtStart_SAR aHints;
const SwDoc& rDoc;
const SwTxtNode& rNd;
SwAttrHandler& rAttrHandler;
SfxItemSet *pSet;
SwExtend *pExt;
ULONG nNdIdx;
xub_StrLen nFirst;
xub_StrLen nAct;
xub_StrLen nStart;
xub_StrLen nEnd;
sal_Bool bOn;
sal_Bool bShow;
void _Clear( SwFont* pFnt );
sal_Bool _ChkSpecialUnderline() const;
void FillHints( MSHORT nAuthor, SwRedlineType eType );
short _Seek( SwFont& rFnt, xub_StrLen nNew, xub_StrLen nOld );
xub_StrLen _GetNextRedln( xub_StrLen nNext );
inline short EnterExtend( SwFont& rFnt, xub_StrLen nNew )
{ if( pExt ) return pExt->Enter( rFnt, nNew ); return 0; }
inline xub_StrLen NextExtend( xub_StrLen nNext )
{ if( pExt ) return pExt->Next( nNext ); return nNext; }
public:
SwRedlineItr( const SwTxtNode& rTxtNd, SwFont& rFnt, SwAttrHandler& rAH,
xub_StrLen nRedlPos, sal_Bool bShw, const SvUShorts *pArr = 0,
xub_StrLen nStart = STRING_LEN );
~SwRedlineItr();
inline sal_Bool IsOn() const { return bOn || ( pExt && pExt->IsOn() ); }
inline void Clear( SwFont* pFnt ) { if( bOn ) _Clear( pFnt ); }
void ChangeTxtAttr( SwFont* pFnt, SwTxtAttr &rHt, sal_Bool bChg );
inline short Seek( SwFont& rFnt, xub_StrLen nNew, xub_StrLen nOld )
{ if( bShow || pExt ) return _Seek( rFnt, nNew, nOld ); return 0; }
inline void Reset() { if( nAct != nFirst ) nAct = STRING_LEN;
if( pExt ) pExt->Reset(); }
inline xub_StrLen GetNextRedln( xub_StrLen nNext )
{ if( bShow || pExt ) return _GetNextRedln( nNext ); return nNext; }
inline sal_Bool ChkSpecialUnderline() const
{ if ( IsOn() ) return _ChkSpecialUnderline(); return sal_False; }
sal_Bool CheckLine( xub_StrLen nChkStart, xub_StrLen nChkEnd );
inline sal_Bool LeaveExtend( SwFont& rFnt, xub_StrLen nNew )
{ return pExt->Leave(rFnt, nNew ); }
inline sal_Bool ExtOn() { if( pExt ) return pExt->IsOn(); return sal_False; }
inline void UpdateExtFont( SwFont &rFnt ) {
ASSERT( ExtOn(), "UpdateExtFont without ExtOn" )
pExt->UpdateFont( rFnt ); }
};
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include <stdint.h>
namespace c2py
{
template <size_t ... vals>
inline constexpr int64_t tsum() noexcept {
if constexpr (sizeof...(vals) == 0) return 0;
else return (vals + ...);
}
static_assert(tsum<1, 2, 3>() == 6);
template <class ... T>
inline constexpr int64_t tsum(const T& ... vals) noexcept {
if constexpr (sizeof...(vals) == 0) return 0;
else return (vals + ...);
}
static_assert(tsum(1, 2, 3) == 6);
}
<commit_msg>Delete algorithm.hpp<commit_after><|endoftext|>
|
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
* Copyright (C) 2003 3Dlabs Inc. Ltd.
*
* This application is open source and may be redistributed and/or modified
* freely and without restriction, both in commericial and non commericial
* applications, as long as this copyright notice is maintained.
*
* This application 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.
*
*/
/* file: src/osgGL2/ProgramObject.cpp
* author: Mike Weiblen 2003-07-14
*
* See http://www.3dlabs.com/opengl2/ for more information regarding
* the OpenGL Shading Language.
*/
#include <fstream>
#include <osg/Notify>
#include <osg/State>
#include <osg/ref_ptr>
#include <osg/Timer>
#include <osgGL2/ProgramObject>
#include <osgGL2/Extensions>
#include <list>
using namespace osgGL2;
///////////////////////////////////////////////////////////////////////////
// static cache of deleted GL2 objects which may only
// by actually deleted in the correct GL context.
typedef std::list<GLhandleARB> GL2ObjectList;
typedef std::map<unsigned int, GL2ObjectList> DeletedGL2ObjectCache;
static DeletedGL2ObjectCache s_deletedGL2ObjectCache;
void ProgramObject::deleteObject(unsigned int contextID, GLhandleARB handle)
{
if (handle!=0)
{
// add handle to the cache for the appropriate context.
s_deletedGL2ObjectCache[contextID].push_back(handle);
}
}
void ProgramObject::flushDeletedGL2Objects(unsigned int contextID,double /*currentTime*/, double& availableTime)
{
// if no time available don't try to flush objects.
if (availableTime<=0.0) return;
const osg::Timer& timer = *osg::Timer::instance();
osg::Timer_t start_tick = timer.tick();
double elapsedTime = 0.0;
DeletedGL2ObjectCache::iterator citr = s_deletedGL2ObjectCache.find(contextID);
if( citr != s_deletedGL2ObjectCache.end() )
{
const Extensions* extensions = Extensions::Get(contextID,true);
if (!extensions->isShaderObjectsSupported())
return;
GL2ObjectList& vpObjectList = citr->second;
for(GL2ObjectList::iterator titr=vpObjectList.begin();
titr!=vpObjectList.end() && elapsedTime<availableTime;
)
{
extensions->glDeleteObject( *titr );
titr = vpObjectList.erase( titr );
elapsedTime = timer.delta_s(start_tick,timer.tick());
}
}
availableTime -= elapsedTime;
}
///////////////////////////////////////////////////////////////////////////
// osgGL2::ProgramObject
///////////////////////////////////////////////////////////////////////////
ProgramObject::ProgramObject()
{
}
ProgramObject::ProgramObject(const ProgramObject& rhs, const osg::CopyOp& copyop):
osg::StateAttribute(rhs, copyop)
{
}
// virtual
ProgramObject::~ProgramObject()
{
for( unsigned int cxt=0; cxt<_pcpoList.size(); ++cxt )
{
if( ! _pcpoList[cxt] ) continue;
PerContextProgObj* pcpo = _pcpoList[cxt].get();
deleteObject( cxt, pcpo->getHandle() );
// TODO add shader objects to delete list.
_pcpoList[cxt] = 0;
}
}
// mark each PCPO (per-context ProgramObject) as needing a relink
void ProgramObject::dirtyProgramObject()
{
for( unsigned int cxt=0; cxt<_pcpoList.size(); ++cxt )
{
if( ! _pcpoList[cxt] ) continue;
PerContextProgObj* pcpo = _pcpoList[cxt].get();
pcpo->markAsDirty();
}
}
void ProgramObject::addShader( ShaderObject* shader )
{
_shaderObjectList.push_back(shader);
dirtyProgramObject();
}
void ProgramObject::apply(osg::State& state) const
{
const unsigned int contextID = state.getContextID();
const Extensions* extensions = Extensions::Get(contextID,true);
if (!extensions->isShaderObjectsSupported())
return;
// if there are no ShaderObjects attached (ie it is "empty"),
// indicates to use GL 1.x "fixed functionality" rendering.
if( _shaderObjectList.size() == 0 )
{
// glProgramObject handle 0 == GL 1.x fixed functionality
extensions->glUseProgramObject( 0 );
return;
}
PerContextProgObj* pcpo = getPCPO( contextID );
// if the first apply(), attach glShaderObjects to the glProgramObject
if( pcpo->isUnattached() )
{
for( unsigned int i=0; i < _shaderObjectList.size() ; ++i )
{
if( ! _shaderObjectList[i] ) continue;
_shaderObjectList[i]->attach( contextID, pcpo->getHandle() );
}
pcpo->markAsAttached();
}
// if we're dirty, build all attached objects, then build ourself
if( pcpo->isDirty() )
{
for( unsigned int i=0; i < _shaderObjectList.size() ; ++i )
{
if( ! _shaderObjectList[i] ) continue;
_shaderObjectList[i]->build( contextID );
}
if( pcpo->build() )
pcpo->markAsClean();
}
// make this glProgramObject part of current GL state
pcpo->use();
}
ProgramObject::PerContextProgObj* ProgramObject::getPCPO(unsigned int contextID) const
{
if( ! _pcpoList[contextID].valid() )
{
_pcpoList[contextID] = new PerContextProgObj( this, Extensions::Get(contextID,true) );
}
return _pcpoList[contextID].get();
}
///////////////////////////////////////////////////////////////////////////
// PCPO : OSG abstraction of the per-context Program Object
ProgramObject::PerContextProgObj::PerContextProgObj(const ProgramObject* parent, Extensions* extensions) :
Referenced()
{
_parent = parent;
_extensions = extensions;
_handle= _extensions->glCreateProgramObject();
markAsDirty();
_unattached = true;
}
ProgramObject::PerContextProgObj::PerContextProgObj(const PerContextProgObj& rhs) :
Referenced()
{
_parent = rhs._parent;
_extensions = rhs._extensions;
_handle= rhs._handle;
_dirty = rhs._dirty;
_unattached = rhs._unattached;
}
ProgramObject::PerContextProgObj::~PerContextProgObj()
{
}
bool ProgramObject::PerContextProgObj::build() const
{
_extensions->glLinkProgram(_handle);
return true;
}
void ProgramObject::PerContextProgObj::use() const
{
_extensions->glUseProgramObject( _handle );
}
///////////////////////////////////////////////////////////////////////////
// osgGL2::ShaderObject
///////////////////////////////////////////////////////////////////////////
ShaderObject::ShaderObject() :
_type(UNKNOWN)
{
}
ShaderObject::ShaderObject(Type type) :
_type(type)
{
}
ShaderObject::ShaderObject(Type type, const char* sourceText) :
_type(type)
{
setShaderSource(sourceText);
}
ShaderObject::ShaderObject(const ShaderObject& rhs, const osg::CopyOp& copyop):
osg::Object(rhs, copyop)
{
/*TODO*/
}
ShaderObject::~ShaderObject()
{
/*TODO*/
}
// mark each PCSO (per-context Shader Object) as needing a recompile
void ShaderObject::dirtyShaderObject()
{
for( unsigned int cxt=0; cxt<_pcsoList.size(); ++cxt )
{
if( ! _pcsoList[cxt] ) continue;
PerContextShaderObj* pcso = _pcsoList[cxt].get();
pcso->markAsDirty();
}
}
void ShaderObject::setShaderSource( const char* sourceText )
{
_shaderSource = sourceText;
dirtyShaderObject();
}
bool ShaderObject::loadShaderSourceFromFile( const char* fileName )
{
std::ifstream sourceFile;
sourceFile.open(fileName, std::ios::binary);
if(!sourceFile)
{
osg::notify(osg::WARN)<<"Error: can't open file \""<<fileName<<"\""<<std::endl;
return false;
}
osg::notify(osg::INFO)<<"Loading shader source file \""<<fileName<<"\""<<std::endl;
sourceFile.seekg(0, std::ios::end);
int length = sourceFile.tellg();
char *text = new char[length + 1];
sourceFile.seekg(0, std::ios::beg);
sourceFile.read(text, length);
sourceFile.close();
text[length] = '\0';
setShaderSource( text );
delete text;
return true;
}
bool ShaderObject::build(unsigned int contextID ) const
{
PerContextShaderObj* pcso = getPCSO( contextID );
if( pcso->isDirty() )
{
if( pcso->build() )
pcso->markAsClean();
}
return true; /*TODO*/
}
ShaderObject::PerContextShaderObj* ShaderObject::getPCSO(unsigned int contextID) const
{
if( ! _pcsoList[contextID].valid() )
{
_pcsoList[contextID] = new PerContextShaderObj( this, Extensions::Get(contextID,true) );
}
return _pcsoList[contextID].get();
}
void ShaderObject::attach(unsigned int contextID, GLhandleARB progObj) const
{
getPCSO( contextID )->attach( progObj );
}
///////////////////////////////////////////////////////////////////////////
// PCSO : OSG abstraction of the per-context Shader Object
ShaderObject::PerContextShaderObj::PerContextShaderObj(const ShaderObject* parent, Extensions* extensions) :
Referenced()
{
_parent = parent;
_extensions = extensions;
_handle = _extensions->glCreateShaderObject( parent->getType() );
markAsDirty();
}
ShaderObject::PerContextShaderObj::PerContextShaderObj(const PerContextShaderObj& rhs) :
Referenced()
{
_parent = rhs._parent;
_extensions = rhs._extensions;
_handle = rhs._handle;
_dirty = rhs._dirty;
}
ShaderObject::PerContextShaderObj::~PerContextShaderObj()
{
}
bool ShaderObject::PerContextShaderObj::build()
{
const char* sourceText = _parent->getShaderSource().c_str();
_extensions->glShaderSource( _handle, 1, &sourceText, NULL );
_extensions->glCompileShader( _handle );
// _extensions->glAttachObject( _handle, vertShaderObject );
return true;
}
void ShaderObject::PerContextShaderObj::attach(GLhandleARB progObj)
{
_extensions->glAttachObject(progObj, _handle);
}
/*EOF*/
<commit_msg>From Romano Magacho. add osg:: to Referenced() calls for IRIX build.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
* Copyright (C) 2003 3Dlabs Inc. Ltd.
*
* This application is open source and may be redistributed and/or modified
* freely and without restriction, both in commericial and non commericial
* applications, as long as this copyright notice is maintained.
*
* This application 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.
*
*/
/* file: src/osgGL2/ProgramObject.cpp
* author: Mike Weiblen 2003-07-14
*
* See http://www.3dlabs.com/opengl2/ for more information regarding
* the OpenGL Shading Language.
*/
#include <fstream>
#include <osg/Notify>
#include <osg/State>
#include <osg/ref_ptr>
#include <osg/Timer>
#include <osgGL2/ProgramObject>
#include <osgGL2/Extensions>
#include <list>
using namespace osgGL2;
///////////////////////////////////////////////////////////////////////////
// static cache of deleted GL2 objects which may only
// by actually deleted in the correct GL context.
typedef std::list<GLhandleARB> GL2ObjectList;
typedef std::map<unsigned int, GL2ObjectList> DeletedGL2ObjectCache;
static DeletedGL2ObjectCache s_deletedGL2ObjectCache;
void ProgramObject::deleteObject(unsigned int contextID, GLhandleARB handle)
{
if (handle!=0)
{
// add handle to the cache for the appropriate context.
s_deletedGL2ObjectCache[contextID].push_back(handle);
}
}
void ProgramObject::flushDeletedGL2Objects(unsigned int contextID,double /*currentTime*/, double& availableTime)
{
// if no time available don't try to flush objects.
if (availableTime<=0.0) return;
const osg::Timer& timer = *osg::Timer::instance();
osg::Timer_t start_tick = timer.tick();
double elapsedTime = 0.0;
DeletedGL2ObjectCache::iterator citr = s_deletedGL2ObjectCache.find(contextID);
if( citr != s_deletedGL2ObjectCache.end() )
{
const Extensions* extensions = Extensions::Get(contextID,true);
if (!extensions->isShaderObjectsSupported())
return;
GL2ObjectList& vpObjectList = citr->second;
for(GL2ObjectList::iterator titr=vpObjectList.begin();
titr!=vpObjectList.end() && elapsedTime<availableTime;
)
{
extensions->glDeleteObject( *titr );
titr = vpObjectList.erase( titr );
elapsedTime = timer.delta_s(start_tick,timer.tick());
}
}
availableTime -= elapsedTime;
}
///////////////////////////////////////////////////////////////////////////
// osgGL2::ProgramObject
///////////////////////////////////////////////////////////////////////////
ProgramObject::ProgramObject()
{
}
ProgramObject::ProgramObject(const ProgramObject& rhs, const osg::CopyOp& copyop):
osg::StateAttribute(rhs, copyop)
{
}
// virtual
ProgramObject::~ProgramObject()
{
for( unsigned int cxt=0; cxt<_pcpoList.size(); ++cxt )
{
if( ! _pcpoList[cxt] ) continue;
PerContextProgObj* pcpo = _pcpoList[cxt].get();
deleteObject( cxt, pcpo->getHandle() );
// TODO add shader objects to delete list.
_pcpoList[cxt] = 0;
}
}
// mark each PCPO (per-context ProgramObject) as needing a relink
void ProgramObject::dirtyProgramObject()
{
for( unsigned int cxt=0; cxt<_pcpoList.size(); ++cxt )
{
if( ! _pcpoList[cxt] ) continue;
PerContextProgObj* pcpo = _pcpoList[cxt].get();
pcpo->markAsDirty();
}
}
void ProgramObject::addShader( ShaderObject* shader )
{
_shaderObjectList.push_back(shader);
dirtyProgramObject();
}
void ProgramObject::apply(osg::State& state) const
{
const unsigned int contextID = state.getContextID();
const Extensions* extensions = Extensions::Get(contextID,true);
if (!extensions->isShaderObjectsSupported())
return;
// if there are no ShaderObjects attached (ie it is "empty"),
// indicates to use GL 1.x "fixed functionality" rendering.
if( _shaderObjectList.size() == 0 )
{
// glProgramObject handle 0 == GL 1.x fixed functionality
extensions->glUseProgramObject( 0 );
return;
}
PerContextProgObj* pcpo = getPCPO( contextID );
// if the first apply(), attach glShaderObjects to the glProgramObject
if( pcpo->isUnattached() )
{
for( unsigned int i=0; i < _shaderObjectList.size() ; ++i )
{
if( ! _shaderObjectList[i] ) continue;
_shaderObjectList[i]->attach( contextID, pcpo->getHandle() );
}
pcpo->markAsAttached();
}
// if we're dirty, build all attached objects, then build ourself
if( pcpo->isDirty() )
{
for( unsigned int i=0; i < _shaderObjectList.size() ; ++i )
{
if( ! _shaderObjectList[i] ) continue;
_shaderObjectList[i]->build( contextID );
}
if( pcpo->build() )
pcpo->markAsClean();
}
// make this glProgramObject part of current GL state
pcpo->use();
}
ProgramObject::PerContextProgObj* ProgramObject::getPCPO(unsigned int contextID) const
{
if( ! _pcpoList[contextID].valid() )
{
_pcpoList[contextID] = new PerContextProgObj( this, Extensions::Get(contextID,true) );
}
return _pcpoList[contextID].get();
}
///////////////////////////////////////////////////////////////////////////
// PCPO : OSG abstraction of the per-context Program Object
ProgramObject::PerContextProgObj::PerContextProgObj(const ProgramObject* parent, Extensions* extensions) :
osg::Referenced()
{
_parent = parent;
_extensions = extensions;
_handle= _extensions->glCreateProgramObject();
markAsDirty();
_unattached = true;
}
ProgramObject::PerContextProgObj::PerContextProgObj(const PerContextProgObj& rhs) :
osg::Referenced()
{
_parent = rhs._parent;
_extensions = rhs._extensions;
_handle= rhs._handle;
_dirty = rhs._dirty;
_unattached = rhs._unattached;
}
ProgramObject::PerContextProgObj::~PerContextProgObj()
{
}
bool ProgramObject::PerContextProgObj::build() const
{
_extensions->glLinkProgram(_handle);
return true;
}
void ProgramObject::PerContextProgObj::use() const
{
_extensions->glUseProgramObject( _handle );
}
///////////////////////////////////////////////////////////////////////////
// osgGL2::ShaderObject
///////////////////////////////////////////////////////////////////////////
ShaderObject::ShaderObject() :
_type(UNKNOWN)
{
}
ShaderObject::ShaderObject(Type type) :
_type(type)
{
}
ShaderObject::ShaderObject(Type type, const char* sourceText) :
_type(type)
{
setShaderSource(sourceText);
}
ShaderObject::ShaderObject(const ShaderObject& rhs, const osg::CopyOp& copyop):
osg::Object(rhs, copyop)
{
/*TODO*/
}
ShaderObject::~ShaderObject()
{
/*TODO*/
}
// mark each PCSO (per-context Shader Object) as needing a recompile
void ShaderObject::dirtyShaderObject()
{
for( unsigned int cxt=0; cxt<_pcsoList.size(); ++cxt )
{
if( ! _pcsoList[cxt] ) continue;
PerContextShaderObj* pcso = _pcsoList[cxt].get();
pcso->markAsDirty();
}
}
void ShaderObject::setShaderSource( const char* sourceText )
{
_shaderSource = sourceText;
dirtyShaderObject();
}
bool ShaderObject::loadShaderSourceFromFile( const char* fileName )
{
std::ifstream sourceFile;
sourceFile.open(fileName, std::ios::binary);
if(!sourceFile)
{
osg::notify(osg::WARN)<<"Error: can't open file \""<<fileName<<"\""<<std::endl;
return false;
}
osg::notify(osg::INFO)<<"Loading shader source file \""<<fileName<<"\""<<std::endl;
sourceFile.seekg(0, std::ios::end);
int length = sourceFile.tellg();
char *text = new char[length + 1];
sourceFile.seekg(0, std::ios::beg);
sourceFile.read(text, length);
sourceFile.close();
text[length] = '\0';
setShaderSource( text );
delete text;
return true;
}
bool ShaderObject::build(unsigned int contextID ) const
{
PerContextShaderObj* pcso = getPCSO( contextID );
if( pcso->isDirty() )
{
if( pcso->build() )
pcso->markAsClean();
}
return true; /*TODO*/
}
ShaderObject::PerContextShaderObj* ShaderObject::getPCSO(unsigned int contextID) const
{
if( ! _pcsoList[contextID].valid() )
{
_pcsoList[contextID] = new PerContextShaderObj( this, Extensions::Get(contextID,true) );
}
return _pcsoList[contextID].get();
}
void ShaderObject::attach(unsigned int contextID, GLhandleARB progObj) const
{
getPCSO( contextID )->attach( progObj );
}
///////////////////////////////////////////////////////////////////////////
// PCSO : OSG abstraction of the per-context Shader Object
ShaderObject::PerContextShaderObj::PerContextShaderObj(const ShaderObject* parent, Extensions* extensions) :
osg::Referenced()
{
_parent = parent;
_extensions = extensions;
_handle = _extensions->glCreateShaderObject( parent->getType() );
markAsDirty();
}
ShaderObject::PerContextShaderObj::PerContextShaderObj(const PerContextShaderObj& rhs) :
osg::Referenced()
{
_parent = rhs._parent;
_extensions = rhs._extensions;
_handle = rhs._handle;
_dirty = rhs._dirty;
}
ShaderObject::PerContextShaderObj::~PerContextShaderObj()
{
}
bool ShaderObject::PerContextShaderObj::build()
{
const char* sourceText = _parent->getShaderSource().c_str();
_extensions->glShaderSource( _handle, 1, &sourceText, NULL );
_extensions->glCompileShader( _handle );
// _extensions->glAttachObject( _handle, vertShaderObject );
return true;
}
void ShaderObject::PerContextShaderObj::attach(GLhandleARB progObj)
{
_extensions->glAttachObject(progObj, _handle);
}
/*EOF*/
<|endoftext|>
|
<commit_before><commit_msg>Resolve: #i119581# fix import issue for various .doc macro button imports<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "after_streaming_fixture.h"
class VolumeTest : public AfterStreamingFixture {
};
// TODO(phoglund): a number of tests are disabled here on Linux, all pending
// investigation in
// http://code.google.com/p/webrtc/issues/detail?id=367
TEST_F(VolumeTest, DefaultSpeakerVolumeIsAtMost255) {
unsigned int volume = 1000;
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_LE(volume, 255u);
}
TEST_F(VolumeTest, SetVolumeBeforePlayoutWorks) {
// This is a rather specialized test, intended to exercise some PulseAudio
// code. However, these conditions should be satisfied on any platform.
unsigned int original_volume = 0;
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));
Sleep(1000);
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(200));
unsigned int volume;
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_EQ(200u, volume);
PausePlaying();
ResumePlaying();
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
// Ensure the volume has not changed after resuming playout.
EXPECT_EQ(200u, volume);
PausePlaying();
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));
ResumePlaying();
// Ensure the volume set while paused is retained.
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_EQ(100u, volume);
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));
}
TEST_F(VolumeTest, ManualSetVolumeWorks) {
unsigned int original_volume = 0;
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));
Sleep(1000);
TEST_LOG("Setting speaker volume to 0 out of 255.\n");
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(0));
unsigned int volume;
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_EQ(0u, volume);
Sleep(1000);
TEST_LOG("Setting speaker volume to 100 out of 255.\n");
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_EQ(100u, volume);
Sleep(1000);
// Set the volume to 255 very briefly so we don't blast the poor user
// listening to this. This is just to test the call succeeds.
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(255));
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_EQ(255u, volume);
TEST_LOG("Setting speaker volume to the original %d out of 255.\n",
original_volume);
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));
Sleep(1000);
}
#if !defined(WEBRTC_IOS)
TEST_F(VolumeTest, DISABLED_ON_LINUX(DefaultMicrophoneVolumeIsAtMost255)) {
unsigned int volume = 1000;
EXPECT_EQ(0, voe_volume_control_->GetMicVolume(volume));
EXPECT_LE(volume, 255u);
}
TEST_F(VolumeTest, DISABLED_ON_LINUX(
ManualRequiresMicrophoneCanSetMicrophoneVolumeWithAcgOff)) {
SwitchToManualMicrophone();
EXPECT_EQ(0, voe_apm_->SetAgcStatus(false));
unsigned int original_volume = 0;
EXPECT_EQ(0, voe_volume_control_->GetMicVolume(original_volume));
TEST_LOG("Setting microphone volume to 0.\n");
EXPECT_EQ(0, voe_volume_control_->SetMicVolume(channel_));
Sleep(1000);
TEST_LOG("Setting microphone volume to 255.\n");
EXPECT_EQ(0, voe_volume_control_->SetMicVolume(255));
Sleep(1000);
TEST_LOG("Setting microphone volume back to saved value.\n");
EXPECT_EQ(0, voe_volume_control_->SetMicVolume(original_volume));
Sleep(1000);
}
TEST_F(VolumeTest, ChannelScalingIsOneByDefault) {
float scaling = -1.0f;
EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(
channel_, scaling));
EXPECT_FLOAT_EQ(1.0f, scaling);
}
TEST_F(VolumeTest, ManualCanSetChannelScaling) {
EXPECT_EQ(0, voe_volume_control_->SetChannelOutputVolumeScaling(
channel_, 0.1f));
float scaling = 1.0f;
EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(
channel_, scaling));
EXPECT_FLOAT_EQ(0.1f, scaling);
TEST_LOG("Channel scaling set to 0.1: audio should be barely audible.\n");
Sleep(2000);
}
#endif // !WEBRTC_IOS
#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
TEST_F(VolumeTest, InputMutingIsNotEnabledByDefault) {
bool is_muted = true;
EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));
EXPECT_FALSE(is_muted);
}
TEST_F(VolumeTest, DISABLED_ON_LINUX(ManualInputMutingMutesMicrophone)) {
SwitchToManualMicrophone();
// Enable muting.
EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, true));
bool is_muted = false;
EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));
EXPECT_TRUE(is_muted);
TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n");
Sleep(2000);
// Test that we can disable muting.
EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, false));
EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));
EXPECT_FALSE(is_muted);
TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n");
Sleep(2000);
}
TEST_F(VolumeTest, DISABLED_ON_LINUX(SystemInputMutingIsNotEnabledByDefault)) {
bool is_muted = true;
EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));
EXPECT_FALSE(is_muted);
}
TEST_F(VolumeTest, DISABLED_ON_LINUX(ManualSystemInputMutingMutesMicrophone)) {
SwitchToManualMicrophone();
// Enable system input muting.
EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(true));
bool is_muted = false;
EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));
EXPECT_TRUE(is_muted);
TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n");
Sleep(2000);
// Test that we can disable system input muting.
EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(false));
EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));
EXPECT_FALSE(is_muted);
TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n");
Sleep(2000);
}
TEST_F(VolumeTest, SystemOutputMutingIsNotEnabledByDefault) {
bool is_muted = true;
EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));
EXPECT_FALSE(is_muted);
}
TEST_F(VolumeTest, ManualSystemOutputMutingMutesOutput) {
// Enable muting.
EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(true));
bool is_muted = false;
EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));
EXPECT_TRUE(is_muted);
TEST_LOG("Muted: you should hear no audio.\n");
Sleep(2000);
// Test that we can disable muting.
EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(false));
EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));
EXPECT_FALSE(is_muted);
TEST_LOG("Unmuted: you should hear audio.\n");
Sleep(2000);
}
TEST_F(VolumeTest, ManualTestInputAndOutputLevels) {
SwitchToManualMicrophone();
TEST_LOG("Speak and verify that the following levels look right:\n");
for (int i = 0; i < 5; i++) {
Sleep(1000);
unsigned int input_level = 0;
unsigned int output_level = 0;
unsigned int input_level_full_range = 0;
unsigned int output_level_full_range = 0;
EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevel(
input_level));
EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevel(
channel_, output_level));
EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevelFullRange(
input_level_full_range));
EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevelFullRange(
channel_, output_level_full_range));
TEST_LOG(" warped levels (0-9) : in=%5d, out=%5d\n",
input_level, output_level);
TEST_LOG(" linear levels (0-32768): in=%5d, out=%5d\n",
input_level_full_range, output_level_full_range);
}
}
TEST_F(VolumeTest, ChannelsAreNotPannedByDefault) {
float left = -1.0;
float right = -1.0;
EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));
EXPECT_FLOAT_EQ(1.0, left);
EXPECT_FLOAT_EQ(1.0, right);
}
TEST_F(VolumeTest, ManualTestChannelPanning) {
TEST_LOG("Panning left.\n");
EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.8f, 0.1f));
Sleep(1000);
TEST_LOG("Back to center.\n");
EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 1.0f, 1.0f));
Sleep(1000);
TEST_LOG("Panning right.\n");
EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.1f, 0.8f));
Sleep(1000);
// To finish, verify that the getter works.
float left = 0.0f;
float right = 0.0f;
EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));
EXPECT_FLOAT_EQ(0.1f, left);
EXPECT_FLOAT_EQ(0.8f, right);
}
#endif // !WEBRTC_ANDROID && !WEBRTC_IOS
<commit_msg>Disabled flaky test.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "after_streaming_fixture.h"
class VolumeTest : public AfterStreamingFixture {
};
// TODO(phoglund): a number of tests are disabled here on Linux, all pending
// investigation in
// http://code.google.com/p/webrtc/issues/detail?id=367
TEST_F(VolumeTest, DefaultSpeakerVolumeIsAtMost255) {
unsigned int volume = 1000;
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_LE(volume, 255u);
}
TEST_F(VolumeTest, SetVolumeBeforePlayoutWorks) {
// This is a rather specialized test, intended to exercise some PulseAudio
// code. However, these conditions should be satisfied on any platform.
unsigned int original_volume = 0;
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));
Sleep(1000);
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(200));
unsigned int volume;
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_EQ(200u, volume);
PausePlaying();
ResumePlaying();
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
// Ensure the volume has not changed after resuming playout.
EXPECT_EQ(200u, volume);
PausePlaying();
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));
ResumePlaying();
// Ensure the volume set while paused is retained.
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_EQ(100u, volume);
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));
}
TEST_F(VolumeTest, ManualSetVolumeWorks) {
unsigned int original_volume = 0;
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));
Sleep(1000);
TEST_LOG("Setting speaker volume to 0 out of 255.\n");
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(0));
unsigned int volume;
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_EQ(0u, volume);
Sleep(1000);
TEST_LOG("Setting speaker volume to 100 out of 255.\n");
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_EQ(100u, volume);
Sleep(1000);
// Set the volume to 255 very briefly so we don't blast the poor user
// listening to this. This is just to test the call succeeds.
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(255));
EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
EXPECT_EQ(255u, volume);
TEST_LOG("Setting speaker volume to the original %d out of 255.\n",
original_volume);
EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));
Sleep(1000);
}
#if !defined(WEBRTC_IOS)
TEST_F(VolumeTest, DISABLED_ON_LINUX(DefaultMicrophoneVolumeIsAtMost255)) {
unsigned int volume = 1000;
EXPECT_EQ(0, voe_volume_control_->GetMicVolume(volume));
EXPECT_LE(volume, 255u);
}
TEST_F(VolumeTest, DISABLED_ON_LINUX(
ManualRequiresMicrophoneCanSetMicrophoneVolumeWithAcgOff)) {
SwitchToManualMicrophone();
EXPECT_EQ(0, voe_apm_->SetAgcStatus(false));
unsigned int original_volume = 0;
EXPECT_EQ(0, voe_volume_control_->GetMicVolume(original_volume));
TEST_LOG("Setting microphone volume to 0.\n");
EXPECT_EQ(0, voe_volume_control_->SetMicVolume(channel_));
Sleep(1000);
TEST_LOG("Setting microphone volume to 255.\n");
EXPECT_EQ(0, voe_volume_control_->SetMicVolume(255));
Sleep(1000);
TEST_LOG("Setting microphone volume back to saved value.\n");
EXPECT_EQ(0, voe_volume_control_->SetMicVolume(original_volume));
Sleep(1000);
}
TEST_F(VolumeTest, ChannelScalingIsOneByDefault) {
float scaling = -1.0f;
EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(
channel_, scaling));
EXPECT_FLOAT_EQ(1.0f, scaling);
}
TEST_F(VolumeTest, ManualCanSetChannelScaling) {
EXPECT_EQ(0, voe_volume_control_->SetChannelOutputVolumeScaling(
channel_, 0.1f));
float scaling = 1.0f;
EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(
channel_, scaling));
EXPECT_FLOAT_EQ(0.1f, scaling);
TEST_LOG("Channel scaling set to 0.1: audio should be barely audible.\n");
Sleep(2000);
}
#endif // !WEBRTC_IOS
#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
TEST_F(VolumeTest, InputMutingIsNotEnabledByDefault) {
bool is_muted = true;
EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));
EXPECT_FALSE(is_muted);
}
TEST_F(VolumeTest, DISABLED_ON_LINUX(ManualInputMutingMutesMicrophone)) {
SwitchToManualMicrophone();
// Enable muting.
EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, true));
bool is_muted = false;
EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));
EXPECT_TRUE(is_muted);
TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n");
Sleep(2000);
// Test that we can disable muting.
EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, false));
EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));
EXPECT_FALSE(is_muted);
TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n");
Sleep(2000);
}
TEST_F(VolumeTest, DISABLED_ON_LINUX(SystemInputMutingIsNotEnabledByDefault)) {
bool is_muted = true;
EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));
EXPECT_FALSE(is_muted);
}
TEST_F(VolumeTest, DISABLED_ON_LINUX(ManualSystemInputMutingMutesMicrophone)) {
SwitchToManualMicrophone();
// Enable system input muting.
EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(true));
bool is_muted = false;
EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));
EXPECT_TRUE(is_muted);
TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n");
Sleep(2000);
// Test that we can disable system input muting.
EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(false));
EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));
EXPECT_FALSE(is_muted);
TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n");
Sleep(2000);
}
TEST_F(VolumeTest, DISABLED_ON_LINUX(SystemOutputMutingIsNotEnabledByDefault)) {
bool is_muted = true;
EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));
EXPECT_FALSE(is_muted);
}
TEST_F(VolumeTest, ManualSystemOutputMutingMutesOutput) {
// Enable muting.
EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(true));
bool is_muted = false;
EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));
EXPECT_TRUE(is_muted);
TEST_LOG("Muted: you should hear no audio.\n");
Sleep(2000);
// Test that we can disable muting.
EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(false));
EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));
EXPECT_FALSE(is_muted);
TEST_LOG("Unmuted: you should hear audio.\n");
Sleep(2000);
}
TEST_F(VolumeTest, ManualTestInputAndOutputLevels) {
SwitchToManualMicrophone();
TEST_LOG("Speak and verify that the following levels look right:\n");
for (int i = 0; i < 5; i++) {
Sleep(1000);
unsigned int input_level = 0;
unsigned int output_level = 0;
unsigned int input_level_full_range = 0;
unsigned int output_level_full_range = 0;
EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevel(
input_level));
EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevel(
channel_, output_level));
EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevelFullRange(
input_level_full_range));
EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevelFullRange(
channel_, output_level_full_range));
TEST_LOG(" warped levels (0-9) : in=%5d, out=%5d\n",
input_level, output_level);
TEST_LOG(" linear levels (0-32768): in=%5d, out=%5d\n",
input_level_full_range, output_level_full_range);
}
}
TEST_F(VolumeTest, ChannelsAreNotPannedByDefault) {
float left = -1.0;
float right = -1.0;
EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));
EXPECT_FLOAT_EQ(1.0, left);
EXPECT_FLOAT_EQ(1.0, right);
}
TEST_F(VolumeTest, ManualTestChannelPanning) {
TEST_LOG("Panning left.\n");
EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.8f, 0.1f));
Sleep(1000);
TEST_LOG("Back to center.\n");
EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 1.0f, 1.0f));
Sleep(1000);
TEST_LOG("Panning right.\n");
EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.1f, 0.8f));
Sleep(1000);
// To finish, verify that the getter works.
float left = 0.0f;
float right = 0.0f;
EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));
EXPECT_FLOAT_EQ(0.1f, left);
EXPECT_FLOAT_EQ(0.8f, right);
}
#endif // !WEBRTC_ANDROID && !WEBRTC_IOS
<|endoftext|>
|
<commit_before><commit_msg>Cookie finder<commit_after><|endoftext|>
|
<commit_before>#include "viewer/window_manager.hh"
//%deps(OPENGL, GLFW, GLEW, pthread)
#include <atomic>
#include <chrono>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
namespace viewer {
constexpr bool VALGRIND = false;
void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods);
void cursor_position_callback(GLFWwindow *window, double xpos, double ypos);
void mouse_button_callback(GLFWwindow *window, int button, int action, int mods);
void window_size_callback(GLFWwindow *window, int width, int height);
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset);
void error_callback(int error, const char *description);
//
// Manage a global registry of the created windows
//
struct GlobalState {
std::map<GLFWwindow *, std::shared_ptr<SimpleWindow>> windows;
int last_placed_window_x = 0;
};
// Global state singleton
std::shared_ptr<GlobalState> global_state;
std::mutex global_state_mutex;
std::atomic<bool> ready(false);
void render_func() {
while (true) {
if (ready) {
const std::lock_guard<std::mutex> lk(global_state_mutex);
WindowManager::draw(16);
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(16));
}
}
}
std::thread render_thread(render_func);
std::shared_ptr<GlobalState> maybe_create_global_state() {
if (!global_state) {
const std::lock_guard<std::mutex> lk(global_state_mutex);
glfwSetErrorCallback(error_callback);
if (!glfwInit()) {
exit(EXIT_FAILURE);
}
glewExperimental = GL_TRUE;
global_state = std::make_shared<GlobalState>();
ready = true;
// render_thread.detach();
}
return global_state;
}
void WindowManager::register_window(const GlSize &size,
const std::shared_ptr<SimpleWindow> simple_window,
const std::string &window_name,
const int win_ver_maj) {
if (VALGRIND) {
simple_window->close();
return;
}
maybe_create_global_state();
// const std::lock_guard<std::mutex> lk(global_state_mutex);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, win_ver_maj);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
// 8x MSAA
glfwWindowHint(GLFW_SAMPLES, 8);
GLFWwindow *window =
glfwCreateWindow(size.height, size.width, window_name.c_str(), nullptr, nullptr);
simple_window->set_title(window_name);
simple_window->set_window(window);
if (!window) {
glfwTerminate();
std::cerr << "\nFailed to create new window" << std::endl;
exit(EXIT_FAILURE);
}
glfwSetWindowPos(window, global_state->last_placed_window_x, 0);
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, cursor_position_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetWindowSizeCallback(window, window_size_callback);
glfwSetScrollCallback(window, scroll_callback);
global_state->windows[window] = simple_window;
global_state->last_placed_window_x += size.width;
}
//
// Render all of the managed windows
//
void WindowManager::render() {
std::vector<GLFWwindow *> to_erase;
for (auto it = global_state->windows.begin(); it != global_state->windows.end(); it++) {
auto &glfw_win = it->first;
auto &window = it->second;
if (glfwWindowShouldClose(glfw_win)) {
to_erase.push_back(glfw_win);
continue;
}
glfwMakeContextCurrent(glfw_win);
glewInit();
window->render();
glfwSwapBuffers(glfw_win);
}
glfwPollEvents();
for (const auto window_key : to_erase) {
glfwDestroyWindow(window_key);
global_state->windows.erase(window_key);
}
}
bool WindowManager::any_windows() {
// Not thread-safe, figure out later
if (global_state) {
return !global_state->windows.empty();
}
return false;
}
void WindowManager::draw(const int ms) {
int ms_slept = 0;
while (any_windows() && (ms_slept < ms)) {
constexpr int SLEEP_MS = 2;
render();
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_MS));
ms_slept += SLEEP_MS;
}
}
void WindowManager::spin() {
while (any_windows()) {
render();
std::this_thread::sleep_for(std::chrono::milliseconds(16));
}
glfwTerminate();
std::abort();
}
void error_callback(int error, const char *description) {
fputs(description, stderr);
}
void close_window(GLFWwindow *window) {
global_state->windows.at(window)->close();
}
void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods) {
if ((key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) || (key == GLFW_KEY_Q)) {
close_window(window);
glfwSetWindowShouldClose(window, GL_TRUE);
}
global_state->windows.at(window)->key_pressed(key, scancode, action, mods);
}
void cursor_position_callback(GLFWwindow *window, double xpos, double ypos) {
global_state->windows.at(window)->mouse_moved(xpos, ypos);
}
void mouse_button_callback(GLFWwindow *window, int button, int action, int mods) {
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) {
}
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
}
if (action == GLFW_RELEASE) {
}
global_state->windows.at(window)->mouse_button(button, action, mods);
}
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) {
global_state->windows.at(window)->on_scroll(yoffset);
}
void window_size_callback(GLFWwindow *window, int width, int height) {
global_state->windows.at(window)->resize(GlSize(width, height));
}
} // namespace viewer
<commit_msg>Re-detatch<commit_after>#include "viewer/window_manager.hh"
//%deps(OPENGL, GLFW, GLEW, pthread)
#include <atomic>
#include <chrono>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
namespace viewer {
constexpr bool VALGRIND = false;
void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods);
void cursor_position_callback(GLFWwindow *window, double xpos, double ypos);
void mouse_button_callback(GLFWwindow *window, int button, int action, int mods);
void window_size_callback(GLFWwindow *window, int width, int height);
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset);
void error_callback(int error, const char *description);
//
// Manage a global registry of the created windows
//
struct GlobalState {
std::map<GLFWwindow *, std::shared_ptr<SimpleWindow>> windows;
int last_placed_window_x = 0;
};
// Global state singleton
std::shared_ptr<GlobalState> global_state;
std::mutex global_state_mutex;
std::atomic<bool> ready(false);
void render_func() {
while (true) {
if (ready) {
const std::lock_guard<std::mutex> lk(global_state_mutex);
WindowManager::draw(16);
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(16));
}
}
}
std::thread render_thread(render_func);
std::shared_ptr<GlobalState> maybe_create_global_state() {
if (!global_state) {
const std::lock_guard<std::mutex> lk(global_state_mutex);
glfwSetErrorCallback(error_callback);
if (!glfwInit()) {
exit(EXIT_FAILURE);
}
glewExperimental = GL_TRUE;
global_state = std::make_shared<GlobalState>();
ready = true;
render_thread.detach();
}
return global_state;
}
void WindowManager::register_window(const GlSize &size,
const std::shared_ptr<SimpleWindow> simple_window,
const std::string &window_name,
const int win_ver_maj) {
if (VALGRIND) {
simple_window->close();
return;
}
maybe_create_global_state();
// const std::lock_guard<std::mutex> lk(global_state_mutex);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, win_ver_maj);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
// 8x MSAA
glfwWindowHint(GLFW_SAMPLES, 8);
GLFWwindow *window =
glfwCreateWindow(size.height, size.width, window_name.c_str(), nullptr, nullptr);
simple_window->set_title(window_name);
simple_window->set_window(window);
if (!window) {
glfwTerminate();
std::cerr << "\nFailed to create new window" << std::endl;
exit(EXIT_FAILURE);
}
glfwSetWindowPos(window, global_state->last_placed_window_x, 0);
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, cursor_position_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetWindowSizeCallback(window, window_size_callback);
glfwSetScrollCallback(window, scroll_callback);
global_state->windows[window] = simple_window;
global_state->last_placed_window_x += size.width;
}
//
// Render all of the managed windows
//
void WindowManager::render() {
std::vector<GLFWwindow *> to_erase;
for (auto it = global_state->windows.begin(); it != global_state->windows.end(); it++) {
auto &glfw_win = it->first;
auto &window = it->second;
if (glfwWindowShouldClose(glfw_win)) {
to_erase.push_back(glfw_win);
continue;
}
glfwMakeContextCurrent(glfw_win);
glewInit();
window->render();
glfwSwapBuffers(glfw_win);
}
glfwPollEvents();
for (const auto window_key : to_erase) {
glfwDestroyWindow(window_key);
global_state->windows.erase(window_key);
}
}
bool WindowManager::any_windows() {
// Not thread-safe, figure out later
if (global_state) {
return !global_state->windows.empty();
}
return false;
}
void WindowManager::draw(const int ms) {
int ms_slept = 0;
while (any_windows() && (ms_slept < ms)) {
constexpr int SLEEP_MS = 2;
render();
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_MS));
ms_slept += SLEEP_MS;
}
}
void WindowManager::spin() {
while (any_windows()) {
render();
std::this_thread::sleep_for(std::chrono::milliseconds(16));
}
glfwTerminate();
std::abort();
}
void error_callback(int error, const char *description) {
fputs(description, stderr);
}
void close_window(GLFWwindow *window) {
global_state->windows.at(window)->close();
}
void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods) {
if ((key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) || (key == GLFW_KEY_Q)) {
close_window(window);
glfwSetWindowShouldClose(window, GL_TRUE);
}
global_state->windows.at(window)->key_pressed(key, scancode, action, mods);
}
void cursor_position_callback(GLFWwindow *window, double xpos, double ypos) {
global_state->windows.at(window)->mouse_moved(xpos, ypos);
}
void mouse_button_callback(GLFWwindow *window, int button, int action, int mods) {
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) {
}
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
}
if (action == GLFW_RELEASE) {
}
global_state->windows.at(window)->mouse_button(button, action, mods);
}
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) {
global_state->windows.at(window)->on_scroll(yoffset);
}
void window_size_callback(GLFWwindow *window, int width, int height) {
global_state->windows.at(window)->resize(GlSize(width, height));
}
} // namespace viewer
<|endoftext|>
|
<commit_before><commit_msg>coverity#1242879 Untrusted value as argument<commit_after><|endoftext|>
|
<commit_before>#include <boost/test/unit_test.hpp>
using namespace std;
#include "mruset.h"
#include "util.h"
#define NUM_TESTS 16
#define MAX_SIZE 100
class mrutester
{
private:
mruset<int> mru;
std::set<int> set;
public:
mrutester() { mru.max_size(MAX_SIZE); }
int size() const { return set.size(); }
void insert(int n)
{
mru.insert(n);
set.insert(n);
BOOST_CHECK(mru == set);
}
};
BOOST_AUTO_TEST_SUITE(mruset_tests)
// Test that an mruset behaves like a set, as long as no more than MAX_SIZE elements are in it
BOOST_AUTO_TEST_CASE(mruset_like_set)
{
for (int nTest=0; nTest<NUM_TESTS; nTest++)
{
mrutester tester;
while (tester.size() < MAX_SIZE)
tester.insert(GetRandInt(2 * MAX_SIZE));
}
}
// Test that an mruset's size never exceeds its max_size
BOOST_AUTO_TEST_CASE(mruset_limited_size)
{
for (int nTest=0; nTest<NUM_TESTS; nTest++)
{
mruset<int> mru(MAX_SIZE);
for (int nAction=0; nAction<3*MAX_SIZE; nAction++)
{
int n = GetRandInt(2 * MAX_SIZE);
mru.insert(n);
BOOST_CHECK(mru.size() <= MAX_SIZE);
}
}
}
// 16-bit permutation function
int static permute(int n)
{
// hexadecimals of pi; verified to be linearly independent
static const int table[16] = {0x243F, 0x6A88, 0x85A3, 0x08D3, 0x1319, 0x8A2E, 0x0370, 0x7344,
0xA409, 0x3822, 0x299F, 0x31D0, 0x082E, 0xFA98, 0xEC4E, 0x6C89};
int ret = 0;
for (int bit=0; bit<16; bit++)
if (n & (1<<bit))
ret ^= table[bit];
return ret;
}
// Test that an mruset acts like a moving window, if no duplicate elements are added
BOOST_AUTO_TEST_CASE(mruset_window)
{
mruset<int> mru(MAX_SIZE);
for (int n=0; n<10*MAX_SIZE; n++)
{
mru.insert(permute(n));
set<int> tester;
for (int m=max(0,n-MAX_SIZE+1); m<=n; m++)
tester.insert(permute(m));
BOOST_CHECK(mru == tester);
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Update to v3<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Copyright (c) 2013-2014 Memorycoin Dev Team
#include <boost/test/unit_test.hpp>
using namespace std;
#include "mruset.h"
#include "util.h"
#define NUM_TESTS 16
#define MAX_SIZE 100
class mrutester
{
private:
mruset<int> mru;
std::set<int> set;
public:
mrutester() { mru.max_size(MAX_SIZE); }
int size() const { return set.size(); }
void insert(int n)
{
mru.insert(n);
set.insert(n);
BOOST_CHECK(mru == set);
}
};
BOOST_AUTO_TEST_SUITE(mruset_tests)
// Test that an mruset behaves like a set, as long as no more than MAX_SIZE elements are in it
BOOST_AUTO_TEST_CASE(mruset_like_set)
{
for (int nTest=0; nTest<NUM_TESTS; nTest++)
{
mrutester tester;
while (tester.size() < MAX_SIZE)
tester.insert(GetRandInt(2 * MAX_SIZE));
}
}
// Test that an mruset's size never exceeds its max_size
BOOST_AUTO_TEST_CASE(mruset_limited_size)
{
for (int nTest=0; nTest<NUM_TESTS; nTest++)
{
mruset<int> mru(MAX_SIZE);
for (int nAction=0; nAction<3*MAX_SIZE; nAction++)
{
int n = GetRandInt(2 * MAX_SIZE);
mru.insert(n);
BOOST_CHECK(mru.size() <= MAX_SIZE);
}
}
}
// 16-bit permutation function
int static permute(int n)
{
// hexadecimals of pi; verified to be linearly independent
static const int table[16] = {0x243F, 0x6A88, 0x85A3, 0x08D3, 0x1319, 0x8A2E, 0x0370, 0x7344,
0xA409, 0x3822, 0x299F, 0x31D0, 0x082E, 0xFA98, 0xEC4E, 0x6C89};
int ret = 0;
for (int bit=0; bit<16; bit++)
if (n & (1<<bit))
ret ^= table[bit];
return ret;
}
// Test that an mruset acts like a moving window, if no duplicate elements are added
BOOST_AUTO_TEST_CASE(mruset_window)
{
mruset<int> mru(MAX_SIZE);
for (int n=0; n<10*MAX_SIZE; n++)
{
mru.insert(permute(n));
set<int> tester;
for (int m=max(0,n-MAX_SIZE+1); m<=n; m++)
tester.insert(permute(m));
BOOST_CHECK(mru == tester);
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>/*The MIT License (MIT)
Copyright (c) 2014 Johannes Häggqvist
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 <ZAP/Archive.h>
#include <fstream>
#include <sstream>
namespace
{
static const std::istream::pos_type MAGIC_POS = 0;
static const std::istream::pos_type TABLE_POS = 4;
template<typename T>
inline void readField(std::istream *stream, T *field)
{
stream->read(reinterpret_cast<char*>(field), sizeof(T));
}
}
namespace ZAP
{
Archive::Archive() : stream(nullptr)
{
}
Archive::Archive(const std::string &filename) : stream(nullptr)
{
openFile(filename);
}
Archive::Archive(const char *data, std::size_t size) : stream(nullptr)
{
openMemory(data, size);
}
Archive::~Archive()
{
close();
}
bool Archive::openFile(const std::string &filename)
{
std::ifstream *file = new std::ifstream(filename, std::ios::in | std::ios::binary);
if (!file->is_open())
{
return false;
}
stream = file;
return loadStream();
}
bool Archive::openMemory(const char *data, std::size_t size)
{
stream = new std::istringstream(std::string(data, size), std::ios::in | std::ios::binary);
return loadStream();
}
void Archive::close()
{
delete stream;
stream = nullptr;
header = ArchiveHeader();
lookupTable.clear();
}
bool Archive::isOpen() const
{
return (stream != nullptr);
}
Compression Archive::getCompression() const
{
return static_cast<Compression>(header.compression);
}
Version Archive::getVersion() const
{
return static_cast<Version>(header.version);
}
bool Archive::isSupportedCompression() const
{
return supportsCompression(getCompression());
}
bool Archive::hasFile(const std::string &virtual_path) const
{
return (lookupTable.find(virtual_path) != lookupTable.cend());
}
DataPointer Archive::getData(const std::string &virtual_path) const
{
const ArchiveEntry *entry = getEntry(virtual_path);
if (entry == nullptr || !isSupportedCompression())
return DataPointer();
if (entry->compressed_size == 0 || entry->decompressed_size == 0)
return DataPointer();
stream->seekg(entry->index);
std::uint32_t size = entry->decompressed_size;
char *data = new char[entry->compressed_size];
stream->read(data, entry->compressed_size);
if (!decompress(getCompression(), data, entry->compressed_size, size))
{
delete[] data;
data = nullptr;
size = 0;
}
return DataPointer(data, size);
}
std::uint32_t Archive::getDecompressedSize(const std::string &virtual_path) const
{
const ArchiveEntry *entry = getEntry(virtual_path);
if (entry == nullptr)
return 0;
return entry->decompressed_size;
}
std::uint32_t Archive::getCompressedSize(const std::string &virtual_path) const
{
const ArchiveEntry *entry = getEntry(virtual_path);
if (entry == nullptr)
return 0;
return entry->compressed_size;
}
std::size_t Archive::getFileCount() const
{
return lookupTable.size();
}
void Archive::getFileList(std::vector<std::string> &list)
{
for (EntryMap::const_reference entry : lookupTable)
{
list.push_back(entry.first);
}
}
const Archive::ArchiveEntry *Archive::getEntry(const std::string &virtual_path) const
{
if (!isOpen())
return nullptr;
EntryMap::const_iterator it = lookupTable.find(virtual_path);
if (it == lookupTable.cend())
return nullptr;
return &(*it).second;
}
bool Archive::loadStream()
{
if (!parseHeader())
{
close();
return false;
}
else
{
buildLookupTable();
return true;
}
}
bool Archive::parseHeader()
{
// We assume that stream is open
stream->seekg(MAGIC_POS);
readField(stream, &header.magic);
readField(stream, &header.version);
readField(stream, &header.compression);
if (header.magic != 'AZ')
return false;
if (header.version < VERSION_MIN || header.version > VERSION_MAX)
return false;
if (header.compression < COMPRESS_NONE || header.compression >= COMPRESS_LAST)
return false;
return true;
}
void Archive::buildLookupTable()
{
// We assume that stream is open
stream->seekg(TABLE_POS);
lookupTable.clear();
std::uint32_t tableSize = 0;
readField(stream, &tableSize);
for (uint32_t i = 0; i < tableSize; ++i)
{
std::string filename;
char c = '\0';
for(;;)
{
stream->read(&c, 1);
if (c == '\0')
break;
filename += c;
}
ArchiveEntry entry;
readField(stream, &entry.index);
readField(stream, &entry.decompressed_size);
readField(stream, &entry.compressed_size);
lookupTable.emplace(filename, entry);
}
}
}
<commit_msg>Removed unnecessary use of static<commit_after>/*The MIT License (MIT)
Copyright (c) 2014 Johannes Häggqvist
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 <ZAP/Archive.h>
#include <fstream>
#include <sstream>
namespace
{
const std::istream::pos_type MAGIC_POS = 0;
const std::istream::pos_type TABLE_POS = 4;
template<typename T>
inline void readField(std::istream *stream, T *field)
{
stream->read(reinterpret_cast<char*>(field), sizeof(T));
}
}
namespace ZAP
{
Archive::Archive() : stream(nullptr)
{
}
Archive::Archive(const std::string &filename) : stream(nullptr)
{
openFile(filename);
}
Archive::Archive(const char *data, std::size_t size) : stream(nullptr)
{
openMemory(data, size);
}
Archive::~Archive()
{
close();
}
bool Archive::openFile(const std::string &filename)
{
std::ifstream *file = new std::ifstream(filename, std::ios::in | std::ios::binary);
if (!file->is_open())
{
return false;
}
stream = file;
return loadStream();
}
bool Archive::openMemory(const char *data, std::size_t size)
{
stream = new std::istringstream(std::string(data, size), std::ios::in | std::ios::binary);
return loadStream();
}
void Archive::close()
{
delete stream;
stream = nullptr;
header = ArchiveHeader();
lookupTable.clear();
}
bool Archive::isOpen() const
{
return (stream != nullptr);
}
Compression Archive::getCompression() const
{
return static_cast<Compression>(header.compression);
}
Version Archive::getVersion() const
{
return static_cast<Version>(header.version);
}
bool Archive::isSupportedCompression() const
{
return supportsCompression(getCompression());
}
bool Archive::hasFile(const std::string &virtual_path) const
{
return (lookupTable.find(virtual_path) != lookupTable.cend());
}
DataPointer Archive::getData(const std::string &virtual_path) const
{
const ArchiveEntry *entry = getEntry(virtual_path);
if (entry == nullptr || !isSupportedCompression())
return DataPointer();
if (entry->compressed_size == 0 || entry->decompressed_size == 0)
return DataPointer();
stream->seekg(entry->index);
std::uint32_t size = entry->decompressed_size;
char *data = new char[entry->compressed_size];
stream->read(data, entry->compressed_size);
if (!decompress(getCompression(), data, entry->compressed_size, size))
{
delete[] data;
data = nullptr;
size = 0;
}
return DataPointer(data, size);
}
std::uint32_t Archive::getDecompressedSize(const std::string &virtual_path) const
{
const ArchiveEntry *entry = getEntry(virtual_path);
if (entry == nullptr)
return 0;
return entry->decompressed_size;
}
std::uint32_t Archive::getCompressedSize(const std::string &virtual_path) const
{
const ArchiveEntry *entry = getEntry(virtual_path);
if (entry == nullptr)
return 0;
return entry->compressed_size;
}
std::size_t Archive::getFileCount() const
{
return lookupTable.size();
}
void Archive::getFileList(std::vector<std::string> &list)
{
for (EntryMap::const_reference entry : lookupTable)
{
list.push_back(entry.first);
}
}
const Archive::ArchiveEntry *Archive::getEntry(const std::string &virtual_path) const
{
if (!isOpen())
return nullptr;
EntryMap::const_iterator it = lookupTable.find(virtual_path);
if (it == lookupTable.cend())
return nullptr;
return &(*it).second;
}
bool Archive::loadStream()
{
if (!parseHeader())
{
close();
return false;
}
else
{
buildLookupTable();
return true;
}
}
bool Archive::parseHeader()
{
// We assume that stream is open
stream->seekg(MAGIC_POS);
readField(stream, &header.magic);
readField(stream, &header.version);
readField(stream, &header.compression);
if (header.magic != 'AZ')
return false;
if (header.version < VERSION_MIN || header.version > VERSION_MAX)
return false;
if (header.compression < COMPRESS_NONE || header.compression >= COMPRESS_LAST)
return false;
return true;
}
void Archive::buildLookupTable()
{
// We assume that stream is open
stream->seekg(TABLE_POS);
lookupTable.clear();
std::uint32_t tableSize = 0;
readField(stream, &tableSize);
for (uint32_t i = 0; i < tableSize; ++i)
{
std::string filename;
char c = '\0';
for(;;)
{
stream->read(&c, 1);
if (c == '\0')
break;
filename += c;
}
ArchiveEntry entry;
readField(stream, &entry.index);
readField(stream, &entry.decompressed_size);
readField(stream, &entry.compressed_size);
lookupTable.emplace(filename, entry);
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Remove unused typedef<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: unodefaults.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2003-04-17 15:53:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _UNODEFAULTS_HXX
#include <unodefaults.hxx>
#endif
#ifndef _SVDMODEL_HXX
#include <svx/svdmodel.hxx>
#endif
#include <svx/unoprov.hxx>
#include <doc.hxx>
/* -----------------------------13.03.01 14:16--------------------------------
---------------------------------------------------------------------------*/
SwSvxUnoDrawPool::SwSvxUnoDrawPool( SwDoc* pDoc ) throw() :
SvxUnoDrawPool(pDoc->GetDrawModel(), SVXUNO_SERVICEID_COM_SUN_STAR_DRAWING_DEFAULTS_WRITER),
m_pDoc(pDoc)
{
}
/* -----------------------------13.03.01 14:16--------------------------------
---------------------------------------------------------------------------*/
SwSvxUnoDrawPool::~SwSvxUnoDrawPool() throw()
{
}
/* -----------------------------13.03.01 14:16--------------------------------
---------------------------------------------------------------------------*/
SfxItemPool* SwSvxUnoDrawPool::getModelPool( sal_Bool bReadOnly ) throw()
{
if(m_pDoc)
{
SdrModel* pModel = m_pDoc->MakeDrawModel();
return &pModel->GetItemPool();
}
return 0;
}
<commit_msg>INTEGRATION: CWS swobjpos02 (1.3.146); FILE MERGED 2003/10/14 10:54:07 od 1.3.146.1: #i18732# <SwSvxUnoDrawPool::getModelPool(..)> - return writer default pool instead of drawing pool in order get default value of new option 'FollowTextFlow' load/saved.<commit_after>/*************************************************************************
*
* $RCSfile: unodefaults.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2004-02-02 18:42:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _UNODEFAULTS_HXX
#include <unodefaults.hxx>
#endif
#ifndef _SVDMODEL_HXX
#include <svx/svdmodel.hxx>
#endif
#include <svx/unoprov.hxx>
#include <doc.hxx>
/* -----------------------------13.03.01 14:16--------------------------------
---------------------------------------------------------------------------*/
SwSvxUnoDrawPool::SwSvxUnoDrawPool( SwDoc* pDoc ) throw() :
SvxUnoDrawPool(pDoc->GetDrawModel(), SVXUNO_SERVICEID_COM_SUN_STAR_DRAWING_DEFAULTS_WRITER),
m_pDoc(pDoc)
{
}
/* -----------------------------13.03.01 14:16--------------------------------
---------------------------------------------------------------------------*/
SwSvxUnoDrawPool::~SwSvxUnoDrawPool() throw()
{
}
/* -----------------------------13.03.01 14:16--------------------------------
---------------------------------------------------------------------------*/
SfxItemPool* SwSvxUnoDrawPool::getModelPool( sal_Bool bReadOnly ) throw()
{
if(m_pDoc)
{
// DVO, OD 01.10.2003 #i18732# - return item pool of writer document;
// it contains draw model item pool as secondary pool.
//SdrModel* pModel = m_pDoc->MakeDrawModel();
//return &pModel->GetItemPool();
m_pDoc->MakeDrawModel();
return &(m_pDoc->GetAttrPool());
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "UnixSocketHandler.hpp"
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <unistd.h>
#include <resolv.h>
namespace et {
UnixSocketHandler::UnixSocketHandler() {
}
bool UnixSocketHandler::hasData(int fd) {
lock_guard<std::recursive_mutex> guard(mutex);
fd_set input;
FD_ZERO(&input);
FD_SET(fd, &input);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
int n = select(fd + 1, &input, NULL, NULL, &timeout);
if (n == -1) {
// Select timed out or failed.
return false;
} else if (n == 0)
return false;
if (!FD_ISSET(fd, &input)) {
LOG(FATAL) << "FD_ISSET is false but we should have data by now.";
}
return true;
}
ssize_t UnixSocketHandler::read(int fd, void *buf, size_t count) {
lock_guard<std::recursive_mutex> guard(mutex);
if (fd <= 0) {
LOG(FATAL) << "Tried to read from an invalid socket: " << fd;
}
if (activeSockets.find(fd) == activeSockets.end()) {
LOG(INFO) << "Tried to read from a socket that has been closed: " << fd;
return 0;
}
ssize_t readBytes = ::read(fd, buf, count);
if (readBytes == 0) {
// Connection is closed. Instead of closing the socket, set EPIPE.
// In EternalTCP, the server needs to explictly tell the client that
// the session is over.
errno = EPIPE;
return -1;
}
if (readBytes < 0) {
LOG(ERROR) << "Error reading: " << errno << " " << strerror(errno) << endl;
}
return readBytes;
}
ssize_t UnixSocketHandler::write(int fd, const void *buf, size_t count) {
lock_guard<std::recursive_mutex> guard(mutex);
if (fd <= 0) {
LOG(FATAL) << "Tried to write to an invalid socket: " << fd;
}
if (activeSockets.find(fd) == activeSockets.end()) {
LOG(INFO) << "Tried to write to a socket that has been closed: " << fd;
return 0;
}
#ifdef MSG_NOSIGNAL
return ::send(fd, buf, count, MSG_NOSIGNAL);
#else
return ::write(fd, buf, count);
#endif
}
int UnixSocketHandler::connect(const std::string &hostname, int port) {
lock_guard<std::recursive_mutex> guard(mutex);
int sockfd = -1;
addrinfo *results = NULL;
addrinfo *p = NULL;
addrinfo hints;
memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = (AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG);
std::string portname = std::to_string(port);
// (re)initialize the DNS system
::res_init();
int rc = getaddrinfo(hostname.c_str(), portname.c_str(), &hints, &results);
if (rc == EAI_NONAME) {
VLOG_EVERY_N(1, 10) << "Cannot resolve hostname: " << gai_strerror(rc);
if (results) {
freeaddrinfo(results);
}
return -1;
}
if (rc != 0) {
LOG(ERROR) << "Error getting address info for " << hostname << ":"
<< portname << ": " << rc << " (" << gai_strerror(rc) << ")";
if (results) {
freeaddrinfo(results);
}
return -1;
}
// loop through all the results and connect to the first we can
for (p = results; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
LOG(INFO) << "Error creating socket: " << errno
<< " " << strerror(errno);
continue;
}
initSocket(sockfd);
// Set nonblocking just for the connect phase
{
int opts;
opts = fcntl(sockfd, F_GETFL);
FATAL_FAIL(opts);
opts |= O_NONBLOCK;
FATAL_FAIL(fcntl(sockfd, F_SETFL, opts));
}
if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1 &&
errno != EINPROGRESS) {
LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << errno
<< " " << strerror(errno);
::close(sockfd);
sockfd = -1;
continue;
}
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
timeval tv;
tv.tv_sec = 3; /* 3 second timeout */
tv.tv_usec = 0;
if (::select(sockfd + 1, NULL, &fdset, NULL, &tv) == 1) {
int so_error;
socklen_t len = sizeof so_error;
FATAL_FAIL(::getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &so_error, &len));
if (so_error == 0) {
LOG(INFO) << "Connected to server: " << p->ai_canonname << " using fd "
<< sockfd;
// Make sure that socket becomes blocking once it's attached to a
// server.
{
int opts;
opts = fcntl(sockfd, F_GETFL);
FATAL_FAIL(opts);
opts &= (~O_NONBLOCK);
FATAL_FAIL(fcntl(sockfd, F_SETFL, opts));
}
break; // if we get here, we must have connected successfully
} else {
if (p->ai_canonname) {
LOG(INFO) << "Error connecting with " << p->ai_canonname << ": "
<< so_error << " " << strerror(so_error);
} else {
LOG(INFO) << "Error connecting to " << hostname << ": "
<< so_error << " " << strerror(so_error);
}
::close(sockfd);
sockfd = -1;
continue;
}
} else {
LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << errno
<< " " << strerror(errno);
::close(sockfd);
sockfd = -1;
continue;
}
}
if (sockfd == -1) {
LOG(ERROR) << "ERROR, no host found";
} else {
if (activeSockets.find(sockfd) != activeSockets.end()) {
LOG(FATAL) << "Tried to insert an fd that already exists: " << sockfd;
}
activeSockets.insert(sockfd);
}
freeaddrinfo(results);
return sockfd;
}
int UnixSocketHandler::listen(int port) {
lock_guard<std::recursive_mutex> guard(mutex);
if (serverSockets.empty()) {
addrinfo hints, *servinfo, *p;
int rc;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP address
std::string portname = std::to_string(port);
if ((rc = getaddrinfo(NULL, portname.c_str(), &hints, &servinfo)) != 0) {
LOG(ERROR) << "Error getting address info for " << port << ": " << rc
<< " (" << gai_strerror(rc) << ")";
exit(1);
}
// loop through all the results and bind to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
int sockfd;
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) ==
-1) {
LOG(INFO) << "Error creating socket " << p->ai_family << "/"
<< p->ai_socktype << "/" << p->ai_protocol << ": " << errno
<< " " << strerror(errno);
continue;
}
initSocket(sockfd);
// Also set the accept socket as non-blocking
{
int opts;
opts = fcntl(sockfd, F_GETFL);
FATAL_FAIL(opts);
opts |= O_NONBLOCK;
FATAL_FAIL(fcntl(sockfd, F_SETFL, opts));
}
// Also set the accept socket as reusable
{
int flag = 1;
FATAL_FAIL(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag,
sizeof(int)));
}
if (p->ai_family == AF_INET6) {
// Also ensure that IPV6 sockets only listen on IPV6
// interfaces. We will create another socket object for IPV4
// if it doesn't already exist.
int flag = 1;
FATAL_FAIL(setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&flag,
sizeof(int)));
}
if (::bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
// This most often happens because the port is in use.
LOG(ERROR) << "Error binding " << p->ai_family << "/" << p->ai_socktype
<< "/" << p->ai_protocol << ": " << errno << " "
<< strerror(errno);
cerr << "Error binding " << p->ai_family << "/" << p->ai_socktype << "/"
<< p->ai_protocol << ": " << errno << " " << strerror(errno)
<< flush;
exit(1);
// close(sockfd);
// continue;
}
// Listen
FATAL_FAIL(::listen(sockfd, 32));
LOG(INFO) << "Listening on " << inet_ntoa(((sockaddr_in*)p->ai_addr)->sin_addr) << ":" << port << "/" << p->ai_family << "/" << p->ai_socktype
<< "/" << p->ai_protocol;
// if we get here, we must have connected successfully
serverSockets.push_back(sockfd);
activeSockets.insert(sockfd);
}
if (serverSockets.empty()) {
LOG(FATAL) << "Could not bind to any interface!";
}
}
for (int sockfd : serverSockets) {
sockaddr_in client;
socklen_t c = sizeof(sockaddr_in);
int client_sock = ::accept(sockfd, (sockaddr *)&client, &c);
if (client_sock >= 0) {
initSocket(client_sock);
activeSockets.insert(client_sock);
// Make sure that socket becomes blocking once it's attached to a client.
{
int opts;
opts = fcntl(client_sock, F_GETFL);
FATAL_FAIL(opts);
opts &= (~O_NONBLOCK);
FATAL_FAIL(fcntl(client_sock, F_SETFL, opts));
}
return client_sock;
} else if (errno != EAGAIN && errno != EWOULDBLOCK) {
FATAL_FAIL(-1); // LOG(FATAL) with the error
}
}
return -1;
}
void UnixSocketHandler::stopListening() {
lock_guard<std::recursive_mutex> guard(mutex);
for (int sockfd : serverSockets) {
close(sockfd);
}
}
void UnixSocketHandler::close(int fd) {
lock_guard<std::recursive_mutex> guard(mutex);
if (fd == -1) {
return;
}
if (activeSockets.find(fd) == activeSockets.end()) {
// Connection was already killed.
LOG(ERROR) << "Tried to close a connection that doesn't exist: " << fd;
return;
}
activeSockets.erase(activeSockets.find(fd));
#if 0
// Shutting down connection before closing to prevent the server
// from closing it.
VLOG(1) << "Shutting down connection: " << fd << endl;
int rc = ::shutdown(fd, SHUT_RDWR);
if (rc == -1) {
if (errno == ENOTCONN || errno == EADDRNOTAVAIL) {
// Shutdown is failing on OS/X with errno (49): Can't assign requested address
// Possibly an OS bug but I don't think it's necessary anyways.
// ENOTCONN is harmless
} else {
FATAL_FAIL(rc);
}
}
#endif
VLOG(1) << "Closing connection: " << fd << endl;
FATAL_FAIL(::close(fd));
}
void UnixSocketHandler::initSocket(int fd) {
int flag = 1;
FATAL_FAIL(setsockopt(fd, /* socket affected */
IPPROTO_TCP, /* set option at TCP level */
TCP_NODELAY, /* name of option */
(char *)&flag, /* the cast is historical cruft */
sizeof(int))); /* length of option value */
timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)));
FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv)));
#ifndef MSG_NOSIGNAL
// If we don't have MSG_NOSIGNAL, use SO_NOSIGPIPE
int val = 1;
FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&val, sizeof(val)));
#endif
}
}
<commit_msg>handle additional cases where ai_canonname is NULL. #43<commit_after>#include "UnixSocketHandler.hpp"
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <unistd.h>
#include <resolv.h>
namespace et {
UnixSocketHandler::UnixSocketHandler() {
}
bool UnixSocketHandler::hasData(int fd) {
lock_guard<std::recursive_mutex> guard(mutex);
fd_set input;
FD_ZERO(&input);
FD_SET(fd, &input);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
int n = select(fd + 1, &input, NULL, NULL, &timeout);
if (n == -1) {
// Select timed out or failed.
return false;
} else if (n == 0)
return false;
if (!FD_ISSET(fd, &input)) {
LOG(FATAL) << "FD_ISSET is false but we should have data by now.";
}
return true;
}
ssize_t UnixSocketHandler::read(int fd, void *buf, size_t count) {
lock_guard<std::recursive_mutex> guard(mutex);
if (fd <= 0) {
LOG(FATAL) << "Tried to read from an invalid socket: " << fd;
}
if (activeSockets.find(fd) == activeSockets.end()) {
LOG(INFO) << "Tried to read from a socket that has been closed: " << fd;
return 0;
}
ssize_t readBytes = ::read(fd, buf, count);
if (readBytes == 0) {
// Connection is closed. Instead of closing the socket, set EPIPE.
// In EternalTCP, the server needs to explictly tell the client that
// the session is over.
errno = EPIPE;
return -1;
}
if (readBytes < 0) {
LOG(ERROR) << "Error reading: " << errno << " " << strerror(errno) << endl;
}
return readBytes;
}
ssize_t UnixSocketHandler::write(int fd, const void *buf, size_t count) {
lock_guard<std::recursive_mutex> guard(mutex);
if (fd <= 0) {
LOG(FATAL) << "Tried to write to an invalid socket: " << fd;
}
if (activeSockets.find(fd) == activeSockets.end()) {
LOG(INFO) << "Tried to write to a socket that has been closed: " << fd;
return 0;
}
#ifdef MSG_NOSIGNAL
return ::send(fd, buf, count, MSG_NOSIGNAL);
#else
return ::write(fd, buf, count);
#endif
}
int UnixSocketHandler::connect(const std::string &hostname, int port) {
lock_guard<std::recursive_mutex> guard(mutex);
int sockfd = -1;
addrinfo *results = NULL;
addrinfo *p = NULL;
addrinfo hints;
memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = (AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG);
std::string portname = std::to_string(port);
// (re)initialize the DNS system
::res_init();
int rc = getaddrinfo(hostname.c_str(), portname.c_str(), &hints, &results);
if (rc == EAI_NONAME) {
VLOG_EVERY_N(1, 10) << "Cannot resolve hostname: " << gai_strerror(rc);
if (results) {
freeaddrinfo(results);
}
return -1;
}
if (rc != 0) {
LOG(ERROR) << "Error getting address info for " << hostname << ":"
<< portname << ": " << rc << " (" << gai_strerror(rc) << ")";
if (results) {
freeaddrinfo(results);
}
return -1;
}
// loop through all the results and connect to the first we can
for (p = results; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
LOG(INFO) << "Error creating socket: " << errno
<< " " << strerror(errno);
continue;
}
initSocket(sockfd);
// Set nonblocking just for the connect phase
{
int opts;
opts = fcntl(sockfd, F_GETFL);
FATAL_FAIL(opts);
opts |= O_NONBLOCK;
FATAL_FAIL(fcntl(sockfd, F_SETFL, opts));
}
if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1 &&
errno != EINPROGRESS) {
if (p->ai_canonname) {
LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << errno
<< " " << strerror(errno);
} else {
LOG(INFO) << "Error connecting: " << errno
<< " " << strerror(errno);
}
::close(sockfd);
sockfd = -1;
continue;
}
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
timeval tv;
tv.tv_sec = 3; /* 3 second timeout */
tv.tv_usec = 0;
if (::select(sockfd + 1, NULL, &fdset, NULL, &tv) == 1) {
int so_error;
socklen_t len = sizeof so_error;
FATAL_FAIL(::getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &so_error, &len));
if (so_error == 0) {
if (p->ai_canonname) {
LOG(INFO) << "Connected to server: " << p->ai_canonname << " using fd "
<< sockfd;
} else {
LOG(ERROR) << "Connected to server but canonname is null somehow";
}
// Make sure that socket becomes blocking once it's attached to a
// server.
{
int opts;
opts = fcntl(sockfd, F_GETFL);
FATAL_FAIL(opts);
opts &= (~O_NONBLOCK);
FATAL_FAIL(fcntl(sockfd, F_SETFL, opts));
}
break; // if we get here, we must have connected successfully
} else {
if (p->ai_canonname) {
LOG(INFO) << "Error connecting with " << p->ai_canonname << ": "
<< so_error << " " << strerror(so_error);
} else {
LOG(INFO) << "Error connecting to " << hostname << ": "
<< so_error << " " << strerror(so_error);
}
::close(sockfd);
sockfd = -1;
continue;
}
} else {
if (p->ai_canonname) {
LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << errno
<< " " << strerror(errno);
} else {
LOG(INFO) << "Error connecting to " << hostname << ": " << errno
<< " " << strerror(errno);
}
::close(sockfd);
sockfd = -1;
continue;
}
}
if (sockfd == -1) {
LOG(ERROR) << "ERROR, no host found";
} else {
if (activeSockets.find(sockfd) != activeSockets.end()) {
LOG(FATAL) << "Tried to insert an fd that already exists: " << sockfd;
}
activeSockets.insert(sockfd);
}
freeaddrinfo(results);
return sockfd;
}
int UnixSocketHandler::listen(int port) {
lock_guard<std::recursive_mutex> guard(mutex);
if (serverSockets.empty()) {
addrinfo hints, *servinfo, *p;
int rc;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP address
std::string portname = std::to_string(port);
if ((rc = getaddrinfo(NULL, portname.c_str(), &hints, &servinfo)) != 0) {
LOG(ERROR) << "Error getting address info for " << port << ": " << rc
<< " (" << gai_strerror(rc) << ")";
exit(1);
}
// loop through all the results and bind to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
int sockfd;
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) ==
-1) {
LOG(INFO) << "Error creating socket " << p->ai_family << "/"
<< p->ai_socktype << "/" << p->ai_protocol << ": " << errno
<< " " << strerror(errno);
continue;
}
initSocket(sockfd);
// Also set the accept socket as non-blocking
{
int opts;
opts = fcntl(sockfd, F_GETFL);
FATAL_FAIL(opts);
opts |= O_NONBLOCK;
FATAL_FAIL(fcntl(sockfd, F_SETFL, opts));
}
// Also set the accept socket as reusable
{
int flag = 1;
FATAL_FAIL(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag,
sizeof(int)));
}
if (p->ai_family == AF_INET6) {
// Also ensure that IPV6 sockets only listen on IPV6
// interfaces. We will create another socket object for IPV4
// if it doesn't already exist.
int flag = 1;
FATAL_FAIL(setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&flag,
sizeof(int)));
}
if (::bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
// This most often happens because the port is in use.
LOG(ERROR) << "Error binding " << p->ai_family << "/" << p->ai_socktype
<< "/" << p->ai_protocol << ": " << errno << " "
<< strerror(errno);
cerr << "Error binding " << p->ai_family << "/" << p->ai_socktype << "/"
<< p->ai_protocol << ": " << errno << " " << strerror(errno)
<< flush;
exit(1);
// close(sockfd);
// continue;
}
// Listen
FATAL_FAIL(::listen(sockfd, 32));
LOG(INFO) << "Listening on " << inet_ntoa(((sockaddr_in*)p->ai_addr)->sin_addr) << ":" << port << "/" << p->ai_family << "/" << p->ai_socktype
<< "/" << p->ai_protocol;
// if we get here, we must have connected successfully
serverSockets.push_back(sockfd);
activeSockets.insert(sockfd);
}
if (serverSockets.empty()) {
LOG(FATAL) << "Could not bind to any interface!";
}
}
for (int sockfd : serverSockets) {
sockaddr_in client;
socklen_t c = sizeof(sockaddr_in);
int client_sock = ::accept(sockfd, (sockaddr *)&client, &c);
if (client_sock >= 0) {
initSocket(client_sock);
activeSockets.insert(client_sock);
// Make sure that socket becomes blocking once it's attached to a client.
{
int opts;
opts = fcntl(client_sock, F_GETFL);
FATAL_FAIL(opts);
opts &= (~O_NONBLOCK);
FATAL_FAIL(fcntl(client_sock, F_SETFL, opts));
}
return client_sock;
} else if (errno != EAGAIN && errno != EWOULDBLOCK) {
FATAL_FAIL(-1); // LOG(FATAL) with the error
}
}
return -1;
}
void UnixSocketHandler::stopListening() {
lock_guard<std::recursive_mutex> guard(mutex);
for (int sockfd : serverSockets) {
close(sockfd);
}
}
void UnixSocketHandler::close(int fd) {
lock_guard<std::recursive_mutex> guard(mutex);
if (fd == -1) {
return;
}
if (activeSockets.find(fd) == activeSockets.end()) {
// Connection was already killed.
LOG(ERROR) << "Tried to close a connection that doesn't exist: " << fd;
return;
}
activeSockets.erase(activeSockets.find(fd));
#if 0
// Shutting down connection before closing to prevent the server
// from closing it.
VLOG(1) << "Shutting down connection: " << fd << endl;
int rc = ::shutdown(fd, SHUT_RDWR);
if (rc == -1) {
if (errno == ENOTCONN || errno == EADDRNOTAVAIL) {
// Shutdown is failing on OS/X with errno (49): Can't assign requested address
// Possibly an OS bug but I don't think it's necessary anyways.
// ENOTCONN is harmless
} else {
FATAL_FAIL(rc);
}
}
#endif
VLOG(1) << "Closing connection: " << fd << endl;
FATAL_FAIL(::close(fd));
}
void UnixSocketHandler::initSocket(int fd) {
int flag = 1;
FATAL_FAIL(setsockopt(fd, /* socket affected */
IPPROTO_TCP, /* set option at TCP level */
TCP_NODELAY, /* name of option */
(char *)&flag, /* the cast is historical cruft */
sizeof(int))); /* length of option value */
timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)));
FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv)));
#ifndef MSG_NOSIGNAL
// If we don't have MSG_NOSIGNAL, use SO_NOSIGPIPE
int val = 1;
FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&val, sizeof(val)));
#endif
}
}
<|endoftext|>
|
<commit_before>#include <boost/test/unit_test.hpp>
#include "util.h"
#include "scrypt.h"
BOOST_AUTO_TEST_SUITE(scrypt_tests)
BOOST_AUTO_TEST_CASE(scrypt_hashtest)
{
// Test Scrypt hash with known inputs against expected outputs
#define HASHCOUNT 5
const char* inputhex[HASHCOUNT] = { "020000004c1271c211717198227392b029a64a7971931d351b387bb80db027f270411e398a07046f7d4a08dd815412a8712f874a7ebf0507e3878bd24e20a3b73fd750a667d2f451eac7471b00de6659", "0200000011503ee6a855e900c00cfdd98f5f55fffeaee9b6bf55bea9b852d9de2ce35828e204eef76acfd36949ae56d1fbe81c1ac9c0209e6331ad56414f9072506a77f8c6faf551eac7471b00389d01", "02000000a72c8a177f523946f42f22c3e86b8023221b4105e8007e59e81f6beb013e29aaf635295cb9ac966213fb56e046dc71df5b3f7f67ceaeab24038e743f883aff1aaafaf551eac7471b0166249b", "010000007824bc3a8a1b4628485eee3024abd8626721f7f870f8ad4d2f33a27155167f6a4009d1285049603888fe85a84b6c803a53305a8d497965a5e896e1a00568359589faf551eac7471b0065434e", "0200000050bfd4e4a307a8cb6ef4aef69abc5c0f2d579648bd80d7733e1ccc3fbc90ed664a7f74006cb11bde87785f229ecd366c2d4e44432832580e0608c579e4cb76f383f7f551eac7471b00c36982" };
const char* expected[HASHCOUNT] = { "00000000002bef4107f882f6115e0b01f348d21195dacd3582aa2dabd7985806" , "00000000003a0d11bdd5eb634e08b7feddcfbbf228ed35d250daf19f1c88fc94", "00000000000b40f895f288e13244728a6c2d9d59d8aff29c65f8dd5114a8ca81", "00000000003007005891cd4923031e99d8e8d72f6e8e7edc6a86181897e105fe", "000000000018f0b426a4afc7130ccb47fa02af730d345b4fe7c7724d3800ec8c" };
uint256 scrypthash;
std::vector<unsigned char> inputbytes;
for (int i = 0; i < HASHCOUNT; i++) {
inputbytes = ParseHex(inputhex[i]);
scrypt_1024_1_1_256((const char*)&inputbytes[0], BEGIN(scrypthash));
BOOST_CHECK_EQUAL(scrypthash.ToString().c_str(), expected[i]);
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Litecoin: SSE2 scrypt unit test coverage<commit_after>#include <boost/test/unit_test.hpp>
#include "util.h"
#include "scrypt.h"
BOOST_AUTO_TEST_SUITE(scrypt_tests)
BOOST_AUTO_TEST_CASE(scrypt_hashtest)
{
// Test Scrypt hash with known inputs against expected outputs
#define HASHCOUNT 5
const char* inputhex[HASHCOUNT] = { "020000004c1271c211717198227392b029a64a7971931d351b387bb80db027f270411e398a07046f7d4a08dd815412a8712f874a7ebf0507e3878bd24e20a3b73fd750a667d2f451eac7471b00de6659", "0200000011503ee6a855e900c00cfdd98f5f55fffeaee9b6bf55bea9b852d9de2ce35828e204eef76acfd36949ae56d1fbe81c1ac9c0209e6331ad56414f9072506a77f8c6faf551eac7471b00389d01", "02000000a72c8a177f523946f42f22c3e86b8023221b4105e8007e59e81f6beb013e29aaf635295cb9ac966213fb56e046dc71df5b3f7f67ceaeab24038e743f883aff1aaafaf551eac7471b0166249b", "010000007824bc3a8a1b4628485eee3024abd8626721f7f870f8ad4d2f33a27155167f6a4009d1285049603888fe85a84b6c803a53305a8d497965a5e896e1a00568359589faf551eac7471b0065434e", "0200000050bfd4e4a307a8cb6ef4aef69abc5c0f2d579648bd80d7733e1ccc3fbc90ed664a7f74006cb11bde87785f229ecd366c2d4e44432832580e0608c579e4cb76f383f7f551eac7471b00c36982" };
const char* expected[HASHCOUNT] = { "00000000002bef4107f882f6115e0b01f348d21195dacd3582aa2dabd7985806" , "00000000003a0d11bdd5eb634e08b7feddcfbbf228ed35d250daf19f1c88fc94", "00000000000b40f895f288e13244728a6c2d9d59d8aff29c65f8dd5114a8ca81", "00000000003007005891cd4923031e99d8e8d72f6e8e7edc6a86181897e105fe", "000000000018f0b426a4afc7130ccb47fa02af730d345b4fe7c7724d3800ec8c" };
uint256 scrypthash;
std::vector<unsigned char> inputbytes;
char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
for (int i = 0; i < HASHCOUNT; i++) {
inputbytes = ParseHex(inputhex[i]);
#if defined(USE_SSE2)
// Test SSE2 scrypt
scrypt_1024_1_1_256_sp_sse2((const char*)&inputbytes[0], BEGIN(scrypthash), scratchpad);
#endif
// Test generic scrypt
scrypt_1024_1_1_256_sp_generic((const char*)&inputbytes[0], BEGIN(scrypthash), scratchpad);
BOOST_CHECK_EQUAL(scrypthash.ToString().c_str(), expected[i]);
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: Fragment_test.C,v 1.14 2002/12/12 11:34:40 oliver Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/KERNEL/fragment.h>
#include <BALL/KERNEL/molecule.h>
#include <BALL/CONCEPT/textPersistenceManager.h>
///////////////////////////
START_TEST(Fragment, "$Id: Fragment_test.C,v 1.14 2002/12/12 11:34:40 oliver Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
using namespace std;
String filename;
NEW_TMP_FILE(filename)
Fragment* frag;
CHECK(default constructor)
frag = new Fragment;
TEST_NOT_EQUAL(frag, 0);
RESULT
CHECK(isValid)
TEST_EQUAL(frag->isValid(), true)
RESULT
CHECK(destructor)
delete frag;
frag = new Fragment;
delete frag;
RESULT
CHECK(Fragment(String&))
Fragment* f1 = new Fragment("hello");
TEST_NOT_EQUAL(f1, 0)
if (f1 != 0)
{
TEST_EQUAL(f1->getName(), "hello")
delete f1;
}
RESULT
CHECK(Fragment(Fragment&, bool))
Fragment* f1 = new Fragment;
f1->setName("testname");
Atom a;
a.setName("a");
f1->insert(a);
Fragment* f2 = new Fragment(*f1, true);
TEST_NOT_EQUAL(f2, 0)
if (f2 != 0)
{
TEST_EQUAL(f2->getName(), "testname")
TEST_EQUAL(f2->getAtom(0)->getName(), "a")
delete f2;
}
f2 = new Fragment(*f1, false);
TEST_NOT_EQUAL(f2, 0)
if (f2 != 0)
{
TEST_EQUAL(f2->getName(), "testname")
delete f2;
}
delete f1;
RESULT
CHECK(operator = (Fragment&))
Fragment f1("name1");
Atom a;
f1.insert(a);
Fragment f2;
f2 = f1;
TEST_EQUAL(f2.getName(), "name1");
TEST_EQUAL(f2.countAtoms(), 1);
RESULT
CHECK(dump(ostream&, Size))
Fragment f1;
Fragment f2;
f1.setName("f1");
f2.setName("f2");
f1.append(f2);
Atom a1;
a1.setName("A1");
f2.append(a1);
std::ofstream outfile(filename.c_str(), std::ios::out);
f1.dump(outfile);
outfile.close();
TEST_FILE_REGEXP(filename.c_str(), "data/Fragment_test.txt")
RESULT
TextPersistenceManager pm;
using namespace RTTI;
pm.registerClass(getStreamName<Fragment>(), Fragment::createDefault);
pm.registerClass(getStreamName<Atom>(), Atom::createDefault);
NEW_TMP_FILE(filename)
CHECK(persistentWrite(PersistenceManager&, String, bool))
std::ofstream ofile(filename.c_str(), std::ios::out);
Fragment* f1 = new Fragment("name1");
Atom* f2 = new Atom();
Atom* f3 = new Atom();
f2->setName("name2");
f3->setName("name3");
f1->insert(*f2);
f1->insert(*f3);
pm.setOstream(ofile);
*f1 >> pm;
ofile.close();
delete f1;
RESULT
CHECK(persistentRead(PersistenceManager&))
std::ifstream ifile(filename.c_str());
pm.setIstream(ifile);
PersistentObject* ptr = pm.readObject();
TEST_NOT_EQUAL(ptr, 0)
if (ptr != 0)
{
TEST_EQUAL(isKindOf<Fragment>(*ptr), true)
Fragment* f1 = castTo<Fragment>(*ptr);
TEST_EQUAL(f1->getName(), "name1")
TEST_EQUAL(f1->countAtoms(), 2)
TEST_EQUAL(f1->getAtom(0)->getName(), "name2")
TEST_EQUAL(f1->getAtom(1)->getName(), "name3")
delete f1;
} else {
throw Exception::NullPointer(__FILE__, __LINE__);
}
RESULT
CHECK(operator ==)
Fragment b1;
Fragment b2;
TEST_EQUAL(b1 == b2, false)
b1 = b2;
TEST_EQUAL(b1 == b1, true)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: Fragment_test.C,v 1.15 2003/06/30 13:38:33 amoll Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/KERNEL/fragment.h>
#include <BALL/KERNEL/molecule.h>
#include <BALL/CONCEPT/textPersistenceManager.h>
///////////////////////////
START_TEST(Fragment, "$Id: Fragment_test.C,v 1.15 2003/06/30 13:38:33 amoll Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
using namespace std;
String filename;
NEW_TMP_FILE(filename)
Fragment* frag;
CHECK(Fragment() throw())
frag = new Fragment;
TEST_NOT_EQUAL(frag, 0);
RESULT
CHECK([EXTRA] isValid)
TEST_EQUAL(frag->isValid(), true)
RESULT
CHECK(~Fragment() throw())
delete frag;
frag = new Fragment;
delete frag;
RESULT
CHECK(Fragment(const String& name) throw())
Fragment* f1 = new Fragment("hello");
TEST_NOT_EQUAL(f1, 0)
if (f1 != 0)
{
TEST_EQUAL(f1->getName(), "hello")
delete f1;
}
RESULT
CHECK(Fragment(const Fragment& fragment, bool deep = true) throw())
Fragment* f1 = new Fragment;
f1->setName("testname");
Atom a;
a.setName("a");
f1->insert(a);
Fragment* f2 = new Fragment(*f1, true);
TEST_NOT_EQUAL(f2, 0)
if (f2 != 0)
{
TEST_EQUAL(f2->getName(), "testname")
TEST_EQUAL(f2->getAtom(0)->getName(), "a")
delete f2;
}
f2 = new Fragment(*f1, false);
TEST_NOT_EQUAL(f2, 0)
if (f2 != 0)
{
TEST_EQUAL(f2->getName(), "testname")
delete f2;
}
delete f1;
RESULT
CHECK(Fragment& operator = (const Fragment& fragment) throw())
Fragment f1("name1");
Atom a;
f1.insert(a);
Fragment f2;
f2 = f1;
TEST_EQUAL(f2.getName(), "name1");
TEST_EQUAL(f2.countAtoms(), 1);
RESULT
CHECK(void dump(std::ostream& s = std::cout, Size depth = 0) const throw())
Fragment f1;
Fragment f2;
f1.setName("f1");
f2.setName("f2");
f1.append(f2);
Atom a1;
a1.setName("A1");
f2.append(a1);
std::ofstream outfile(filename.c_str(), std::ios::out);
f1.dump(outfile);
outfile.close();
TEST_FILE_REGEXP(filename.c_str(), "data/Fragment_test.txt")
RESULT
TextPersistenceManager pm;
using namespace RTTI;
pm.registerClass(getStreamName<Fragment>(), Fragment::createDefault);
pm.registerClass(getStreamName<Atom>(), Atom::createDefault);
NEW_TMP_FILE(filename)
CHECK(void persistentWrite(PersistenceManager& pm, const char* name = 0) const throw(Exception::GeneralException))
std::ofstream ofile(filename.c_str(), std::ios::out);
Fragment* f1 = new Fragment("name1");
Atom* f2 = new Atom();
Atom* f3 = new Atom();
f2->setName("name2");
f3->setName("name3");
f1->insert(*f2);
f1->insert(*f3);
pm.setOstream(ofile);
*f1 >> pm;
ofile.close();
delete f1;
RESULT
CHECK(void persistentRead(PersistenceManager& pm) throw(Exception::GeneralException))
std::ifstream ifile(filename.c_str());
pm.setIstream(ifile);
PersistentObject* ptr = pm.readObject();
TEST_NOT_EQUAL(ptr, 0)
if (ptr != 0)
{
TEST_EQUAL(isKindOf<Fragment>(*ptr), true)
Fragment* f1 = castTo<Fragment>(*ptr);
TEST_EQUAL(f1->getName(), "name1")
TEST_EQUAL(f1->countAtoms(), 2)
TEST_EQUAL(f1->getAtom(0)->getName(), "name2")
TEST_EQUAL(f1->getAtom(1)->getName(), "name3")
delete f1;
} else {
throw Exception::NullPointer(__FILE__, __LINE__);
}
RESULT
CHECK(bool operator == (const Fragment& fragment) const throw())
Fragment b1;
Fragment b2;
TEST_EQUAL(b1 == b2, false)
b1 = b2;
TEST_EQUAL(b1 == b1, true)
RESULT
CHECK(bool operator != (const Fragment& fragment) const throw())
Fragment b1;
Fragment b2;
TEST_EQUAL(b1 != b2, true)
b1 = b2;
TEST_EQUAL(b1 != b1, false)
RESULT
CHECK(BALL_CREATE_DEEP(Fragment))
Fragment b1;
b1.setName("asddd");
Atom a;
b1.insert(a);
Fragment* b2 = (Fragment*)b1.create(false, true);
TEST_EQUAL(b2->getName(), "")
TEST_EQUAL(b2->countAtoms(), 0)
delete b2;
b2 = (Fragment*)b1.create(true, false);
TEST_EQUAL(b2->getName(), "asddd")
TEST_EQUAL(b2->countAtoms(), 1)
delete b2;
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>
|
<commit_before>// $Id: MOL2File_test.C,v 1.1 2000/05/15 19:17:06 oliver Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/FORMAT/MOL2File.h>
///////////////////////////
START_TEST(MOL2File, "$Id: MOL2File_test.C,v 1.1 2000/05/15 19:17:06 oliver Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
CHECK(MOL2File::MOL2File())
//BAUSTELLE
RESULT
CHECK(MOL2File::~MOL2File())
//BAUSTELLE
RESULT
CHECK(MOL2File::MOL2File(const String& filename, File::OpenMode open_mode))
//BAUSTELLE
RESULT
CHECK(MOL2File::write(const System& system))
//BAUSTELLE
RESULT
CHECK(MOL2File::read(System& system))
//BAUSTELLE
RESULT
CHECK(MOL2File::MOL2File& operator >> (System& system))
//BAUSTELLE
RESULT
CHECK(MOL2File::MOL2File& operator << (const System& system))
//BAUSTELLE
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>added: first tests<commit_after>// $Id: MOL2File_test.C,v 1.2 2000/05/23 05:43:27 oliver Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/FORMAT/MOL2File.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/system.h>
#include <BALL/KERNEL/molecule.h>
#include <BALL/MATHS/vector3.h>
///////////////////////////
START_TEST(MOL2File, "$Id: MOL2File_test.C,v 1.2 2000/05/23 05:43:27 oliver Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
MOL2File* mf = 0;
CHECK(MOL2File::MOL2File())
mf = new MOL2File;
TEST_NOT_EQUAL(mf, 0)
RESULT
CHECK(MOL2File::~MOL2File())
delete mf;
RESULT
CHECK(MOL2File::MOL2File(const String& filename, File::OpenMode open_mode))
//BAUSTELLE
RESULT
CHECK(MOL2File::read(System& system))
MOL2File f("data/AAG.mol2");
System system;
f.read(system);
TEST_EQUAL(system.countAtoms(), 30)
TEST_EQUAL(system.countResidues(), 3)
Size number_of_bonds = 0;
Atom::BondIterator bond_it;
AtomIterator atom_it;
BALL_FOREACH_BOND(system, atom_it, bond_it)
{
number_of_bonds++;
}
TEST_EQUAL(number_of_bonds, 29)
RESULT
CHECK(MOL2File::write(const System& system))
Molecule* m = new Molecule;
m->setName("MOL");
System S;
S.setName("SYSTEM");
S.insert(*m);
Atom* a1 = new Atom();
Atom* a2 = new Atom();
m->insert(*a1);
m->insert(*a2);
a1->setName("A1");
a1->setElement(PTE[Element::N]);
a1->setCharge(0.5);
a1->setPosition(Vector3(0.1, 0.2, 0.3));
a2->setName("A2");
a2->setElement(PTE[Element::O]);
a2->setCharge(-0.5);
a2->setPosition(Vector3(0.5, 0.6, 0.7));
a1->createBond(*a2);
a1->getBond(*a2)->setOrder(Bond::ORDER__DOUBLE);
String filename;
NEW_TMP_FILE(filename)
MOL2File f(filename, std::ios::out);
f.write(S);
TEST_FILE(filename.c_str(), "data/MOL2File_test.mol2", true)
RESULT
CHECK(MOL2File::MOL2File& operator >> (System& system))
MOL2File f("data/AAG.mol2");
System S;
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 30)
RESULT
CHECK(MOL2File::MOL2File& operator << (const System& system))
//BAUSTELLE
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>
|
<commit_before>// $Id: tutorial2.C,v 1.1 2000/03/09 22:20:46 oliver Exp $
// tutorial example 1
// ------------------
// build two water molecules and write them to a file
// needed for cout
#include <iostream>
// the BALL kernel classes
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/molecule.h>
#include <BALL/KERNEL/system.h>
#include <BALL/KERNEL/PSE.h>
// reading and writing of HyperChem files
#include <BALL/FORMAT/HINFile.h>
// the TranslationProcessor
#include <BALL/STRUCTURE/geometricTransformations.h>
// we use the BALL namespace and the std namespace (for cout and endl)
using namespace BALL;
using namespace std;
int main()
{
// we create a new atom caleld oxygen
// and set its element to oxygen (PSE[Element::O])
Atom* oxygen = new Atom;
oxygen->setElement(PSE[Element::O]);
// now we create two hydrogen atoms...
Atom* hydrogen1 = new Atom;
Atom* hydrogen2 = new Atom;
hydrogen1->setElement(PSE[Element::H]);
hydrogen2->setElement(PSE[Element::H]);
// ...and move them to approximately correct positions
hydrogen1->setPosition(Vector3(-0.95, 0.00, 0.0));
hydrogen2->setPosition(Vector3( 0.25, 0.87, 0.0));
// We create our water molecule...
Molecule* water = new Molecule;
// ...and insert the three atoms into the molecule.
water->insert(*oxygen);
water->insert(*hydrogen1);
water->insert(*hydrogen2);
// Then we build the two O-H bonds
oxygen->createBond(*hydrogen1);
oxygen->createBond(*hydrogen2);
// Some statics: Molecule::countAtoms() writes the number of
// atoms, Atom::countBonds() the number of bonds the atom shares
cout << "# of atoms in water: " << water->countAtoms() << endl;
cout << "# of bonds in O: " << oxygen->countBonds() << endl;
cout << "# of atoms in H1: " << hydrogen1->countBonds() << endl;
cout << "# of atoms in H2: " << hydrogen2->countBonds() << endl;
// bond_vector is a vector and is set to the
// difference of atom positions of oxygen and hydrogen1
Vector3 bond_vector = oxygen->getPosition() - hydrogen1->getPosition();
// Vector3::getLength prints the length of the vector
cout << "bond distance: " << bond_vector.getLength() << endl;
// Now we copy our molecule using a copy constructor.
Molecule* water2 = new Molecule(*water);
// A translation processor moves the second molecule
// 5 Angstrom along the x axis
TranslationProcessor translation(Vector3(5, 0, 0));
water2->apply(translation);
// We insert our two molecules into a system
System S;
S.insert(*water);
S.insert(*water2);
// and write this system to a HyperChem file
HINFile outfile("water.hin", ios::out);
outfile << S;
outfile.close();
// We delete the system. This also deletes the molecules
// and the atoms therein
delete S;
}
<commit_msg>added: added the first lines of the tutorial code<commit_after>// $Id: tutorial2.C,v 1.2 2000/03/09 22:27:19 oliver Exp $
// tutorial example 2
// ------------------
// read BPTI from a PDB file, print its sequence
// (use of PDBFile, ResidueIterator)
// needed for cout
#include <iostream>
// the BALL kernel classes
#include <BALL/KERNEL/residue.h>
#include <BALL/KERNEL/system.h>
// reading and writing of PDB files
#include <BALL/FORMAT/PDBFile.h>
// we use the BALL namespace and the std namespace (for cout and endl)
using namespace BALL;
using namespace std;
int main()
{
// create a PDBFile object
PDBFile infile("bpti.pdb");
// create a system
System S;
// read the contents of bpti.pdb into the system
infile >> S;
// close the file
infile.close();
ResidueIterator res_it;
for (res_it = S.beginResidue();
res_it != S.endResidue();
++res_it)
{
cout << res_it->getName() << endl;
}
}
<|endoftext|>
|
<commit_before>#include "BaseTestCase.h"
#include <cmath>
#include "Maths.h"
#include "SoftwareRenderer.h"
#include "CloudLayerDefinition.h"
#include "NoiseGenerator.h"
#if 0
TEST(Clouds, Density)
{
/* Setup */
double x, y, z;
CloudLayerDefinition layer(NULL);
/* Test default coverage (empty) */
for (x = -10.0; x < 10.0; x += 10.0)
{
for (y = -10.0; y < 10.0; y += 10.0)
{
for (z = -10.0; z < 10.0; z += 10.0)
{
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, y, z)), 0.0);
}
}
}
/* Test coverage by altitude */
layer.base_coverage = 1.0;
layer.lower_altitude = -1.0;
layer.thickness = 2.0;
layer.validate();
layer.base_coverage = 1.0;
layer._coverage_noise->forceValue(1.0);
for (x = -10.0; x < 10.0; x += 10.0)
{
for (z = -10.0; z < 10.0; z += 10.0)
{
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 0.0, z)), 1.0);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 0.5, z)), 0.5);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 1.0, z)), 0.0);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 1.5, z)), 0.0);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, -0.5, z)), 0.5);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, -1.0, z)), 0.0);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, -1.5, z)), 0.0);
}
}
layer.base_coverage = 0.5;
layer._coverage_noise->forceValue(1.0);
for (x = -10.0; x < 10.0; x += 10.0)
{
for (z = -10.0; z < 10.0; z += 10.0)
{
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 0.0, z)), 0.5);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 0.5, z)), 0.25);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 1.0, z)), 0.0);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 1.5, z)), 0.0);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, -0.5, z)), 0.25);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, -1.0, z)), 0.0);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, -1.5, z)), 0.0);
}
}
layer.base_coverage = 1.0;
layer._coverage_noise->forceValue(0.5);
for (x = -10.0; x < 10.0; x += 10.0)
{
for (z = -10.0; z < 10.0; z += 10.0)
{
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 0.0, z)), 0.5);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 0.5, z)), 0.25);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 1.0, z)), 0.0);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, 1.5, z)), 0.0);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, -0.5, z)), 0.25);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, -1.0, z)), 0.0);
ASSERT_DOUBLE_EQ(cloudsGetLayerCoverage(&layer, v3(x, -1.5, z)), 0.0);
}
}
/* TODO Test fake renderer */
/* TODO Test real renderer */
}
TEST(Clouds, WalkingBoundaries)
{
Vector3 start, end;
int result;
CloudLayerDefinition layer(NULL);
layer.base_coverage = 1.0;
layer.lower_altitude = -1.0;
layer.thickness = 2.0;
layer.validate();
/* Basic cases */
start = v3(0.0, -3.0, 0.0);
end = v3(0.0, -2.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 0);
start = v3(0.0, 2.0, 0.0);
end = v3(0.0, 3.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 0);
start = v3(0.0, -2.0, 0.0);
end = v3(0.0, 2.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 1);
ASSERT_VECTOR3_COORDS(start, 0.0, -1.0, 0.0);
ASSERT_VECTOR3_COORDS(end, 0.0, 1.0, 0.0);
start = v3(0.0, 0.0, 0.0);
end = v3(0.0, 2.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 1);
ASSERT_VECTOR3_COORDS(start, 0.0, 0.0, 0.0);
ASSERT_VECTOR3_COORDS(end, 0.0, 1.0, 0.0);
start = v3(0.0, -2.0, 0.0);
end = v3(0.0, 0.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 1);
ASSERT_VECTOR3_COORDS(start, 0.0, -1.0, 0.0);
ASSERT_VECTOR3_COORDS(end, 0.0, 0.0, 0.0);
/* Basic cases (inverted) */
start = v3(0.0, -2.0, 0.0);
end = v3(0.0, -3.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 0);
start = v3(0.0, 3.0, 0.0);
end = v3(0.0, 2.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 0);
start = v3(0.0, 2.0, 0.0);
end = v3(0.0, -2.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 1);
ASSERT_VECTOR3_COORDS(start, 0.0, 1.0, 0.0);
ASSERT_VECTOR3_COORDS(end, 0.0, -1.0, 0.0);
start = v3(0.0, 2.0, 0.0);
end = v3(0.0, 0.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 1);
ASSERT_VECTOR3_COORDS(start, 0.0, 1.0, 0.0);
ASSERT_VECTOR3_COORDS(end, 0.0, 0.0, 0.0);
start = v3(0.0, 0.0, 0.0);
end = v3(0.0, -2.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 1);
ASSERT_VECTOR3_COORDS(start, 0.0, 0.0, 0.0);
ASSERT_VECTOR3_COORDS(end, 0.0, -1.0, 0.0);
/* Horizontal cases */
start = v3(0.0, 2.0, 0.0);
end = v3(10.0, 2.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 0);
start = v3(0.0, 1.00001, 0.0);
end = v3(10.0, 1.00001, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 0);
start = v3(0.0, -1.00001, 0.0);
end = v3(10.0, -1.00001, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 0);
start = v3(0.0, -2.0, 0.0);
end = v3(10.0, -2.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 0);
start = v3(0.0, 0.0, 0.0);
end = v3(10.0, 0.0, 0.0);
result = cloudsOptimizeWalkingBounds(&layer, &start, &end);
ASSERT_EQ(result, 1);
ASSERT_VECTOR3_COORDS(start, 0.0, 0.0, 0.0);
ASSERT_VECTOR3_COORDS(end, 10.0, 0.0, 0.0);
}
static double _getLayerDensitySinX(Renderer*, CloudLayerDefinition*, Vector3 location)
{
double density = sin(location.x * (2.0 * Maths::PI));
return (density > 0.0) ? density : 0.0;
}
static double _getEdgeDensitySquared(Renderer*, CloudLayerDefinition*, Vector3, double edge_density)
{
return edge_density * edge_density;
}
TEST(Clouds, Walking)
{
/* Init */
CloudLayerDefinition layer(NULL);
layer.lower_altitude = -1.0;
layer.thickness = 2.0;
layer.validate();
Renderer* renderer;
renderer = rendererCreate();
renderer->render_quality = 8;
renderer->clouds->getLayerDensity = _getLayerDensitySinX;
CloudsWalker* walker = cloudsCreateWalker(renderer, &layer, v3(-0.4, 0.0, 0.0), v3(1.75, 0.0, 0.0));
CloudWalkerStepInfo* segment;
int result;
/* First step */
cloudsWalkerSetStepSize(walker, 0.3);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_FALSE(segment->refined);
ASSERT_FALSE(segment->subdivided);
ASSERT_DOUBLE_EQ(segment->length, 0.3);
ASSERT_DOUBLE_EQ(segment->start.distance_from_start, 0.0);
ASSERT_VECTOR3_COORDS(segment->start.location, -0.4, 0.0, 0.0);
ASSERT_DOUBLE_EQ(segment->start.global_density, 0.0);
ASSERT_DOUBLE_EQ(segment->end.distance_from_start, 0.3);
ASSERT_VECTOR3_COORDS(segment->end.location, -0.1, 0.0, 0.0);
ASSERT_DOUBLE_EQ(segment->end.global_density, 0.0);
/* Second step */
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_FALSE(segment->refined);
ASSERT_FALSE(segment->subdivided);
ASSERT_DOUBLE_EQ(segment->length, 0.3);
ASSERT_DOUBLE_EQ(segment->start.distance_from_start, 0.3);
ASSERT_VECTOR3_COORDS(segment->start.location, -0.1, 0.0, 0.0);
ASSERT_DOUBLE_EQ(segment->start.global_density, 0.0);
ASSERT_DOUBLE_EQ(segment->end.distance_from_start, 0.6);
ASSERT_VECTOR3_COORDS(segment->end.location, 0.2, 0.0, 0.0);
ASSERT_GT(segment->end.global_density, 0.9);
/* Order to refine second step around the entry point */
cloudsWalkerOrderRefine(walker, 0.01);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_TRUE(segment->refined);
ASSERT_FALSE(segment->subdivided);
ASSERT_DOUBLE_IN_RANGE(segment->length, 0.19, 0.20);
ASSERT_DOUBLE_IN_RANGE(segment->start.distance_from_start, 0.40, 0.41);
ASSERT_DOUBLE_IN_RANGE(segment->start.location.x, 0.0, 0.01);
ASSERT_GT(segment->start.global_density, 0.0);
ASSERT_DOUBLE_EQ(segment->end.distance_from_start, 0.6);
ASSERT_VECTOR3_COORDS(segment->end.location, 0.2, 0.0, 0.0);
ASSERT_GT(segment->end.global_density, 0.9);
/* Third step, change step size */
cloudsWalkerSetStepSize(walker, 0.4);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_FALSE(segment->refined);
ASSERT_FALSE(segment->subdivided);
ASSERT_DOUBLE_EQ(segment->length, 0.4);
ASSERT_DOUBLE_EQ(segment->start.distance_from_start, 0.6);
ASSERT_VECTOR3_COORDS(segment->start.location, 0.2, 0.0, 0.0);
ASSERT_GT(segment->start.global_density, 0.9);
ASSERT_DOUBLE_EQ(segment->end.distance_from_start, 1.0);
ASSERT_VECTOR3_COORDS(segment->end.location, 0.6, 0.0, 0.0);
ASSERT_DOUBLE_EQ(segment->end.global_density, 0.0);
/* Refine exit point */
cloudsWalkerOrderRefine(walker, 0.001);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_TRUE(segment->refined);
ASSERT_FALSE(segment->subdivided);
ASSERT_DOUBLE_IN_RANGE(segment->length, 0.3, 0.301);
ASSERT_DOUBLE_EQ(segment->start.distance_from_start, 0.6);
ASSERT_VECTOR3_COORDS(segment->start.location, 0.2, 0.0, 0.0);
ASSERT_GT(segment->start.global_density, 0.9);
ASSERT_DOUBLE_IN_RANGE(segment->end.distance_from_start, 0.9, 0.901);
ASSERT_DOUBLE_IN_RANGE(segment->end.location.x, 0.5, 0.501);
ASSERT_DOUBLE_EQ(segment->end.global_density, 0.0);
/* Find next entry point by skipping blank */
cloudsWalkerSetVoidSkipping(walker, 1);
cloudsWalkerSetStepSize(walker, 0.2);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_FALSE(segment->refined);
ASSERT_FALSE(segment->subdivided);
ASSERT_DOUBLE_EQ(segment->length, 0.2);
ASSERT_DOUBLE_IN_RANGE(segment->start.distance_from_start, 1.2, 1.4);
ASSERT_DOUBLE_IN_RANGE(segment->start.location.x, 0.8, 1.0);
ASSERT_DOUBLE_EQ(segment->start.global_density, 0.0);
ASSERT_DOUBLE_IN_RANGE(segment->end.distance_from_start, 1.4, 1.6);
ASSERT_DOUBLE_IN_RANGE(segment->end.location.x, 1.0, 1.2);
ASSERT_GT(segment->end.global_density, 0.0);
/* Refine entry point */
cloudsWalkerOrderRefine(walker, 0.01);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_TRUE(segment->refined);
ASSERT_FALSE(segment->subdivided);
ASSERT_DOUBLE_IN_RANGE(segment->length, 0.0, 0.2);
ASSERT_DOUBLE_IN_RANGE(segment->start.distance_from_start, 1.4, 1.41);
ASSERT_DOUBLE_IN_RANGE(segment->start.location.x, 1.0, 1.01);
ASSERT_GT(segment->start.global_density, 0.0);
ASSERT_DOUBLE_IN_RANGE(segment->end.distance_from_start, 1.41, 1.6);
ASSERT_DOUBLE_IN_RANGE(segment->end.location.x, 1.01, 1.2);
ASSERT_GT(segment->end.global_density, 0.0);
/* Subdivide entry for more detail */
CloudWalkerStepInfo parent = *segment;
cloudsWalkerOrderSubdivide(walker, 3);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_FALSE(segment->refined);
ASSERT_TRUE(segment->subdivided);
ASSERT_DOUBLE_EQ(segment->length, parent.length / 3.0);
ASSERT_DOUBLE_EQ(segment->start.distance_from_start, parent.start.distance_from_start);
ASSERT_DOUBLE_EQ(segment->start.location.x, parent.start.location.x);
ASSERT_DOUBLE_EQ(segment->end.distance_from_start, parent.start.distance_from_start + segment->length);
ASSERT_DOUBLE_EQ(segment->end.location.x, parent.start.location.x + segment->length);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_FALSE(segment->refined);
ASSERT_TRUE(segment->subdivided);
ASSERT_DOUBLE_EQ(segment->length, parent.length / 3.0);
ASSERT_DOUBLE_EQ(segment->start.distance_from_start, parent.start.distance_from_start + segment->length);
ASSERT_DOUBLE_EQ(segment->start.location.x, parent.start.location.x + segment->length);
ASSERT_DOUBLE_EQ(segment->end.distance_from_start, parent.start.distance_from_start + 2.0 * segment->length);
ASSERT_DOUBLE_EQ(segment->end.location.x, parent.start.location.x + 2.0 * segment->length);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_FALSE(segment->refined);
ASSERT_TRUE(segment->subdivided);
ASSERT_DOUBLE_EQ(segment->length, parent.length / 3.0);
ASSERT_DOUBLE_EQ(segment->start.distance_from_start, parent.start.distance_from_start + 2.0 * segment->length);
ASSERT_DOUBLE_EQ(segment->start.location.x, parent.start.location.x + 2.0 * segment->length);
ASSERT_DOUBLE_EQ(segment->end.distance_from_start, parent.end.distance_from_start);
ASSERT_DOUBLE_EQ(segment->end.location.x, parent.end.location.x);
/* After subdividing, normal walking resumes */
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_FALSE(segment->refined);
ASSERT_FALSE(segment->subdivided);
ASSERT_DOUBLE_EQ(segment->length, 0.2);
ASSERT_DOUBLE_IN_RANGE(segment->start.distance_from_start, 1.41, 1.6);
ASSERT_DOUBLE_IN_RANGE(segment->start.location.x, 1.01, 1.2);
ASSERT_GT(segment->start.global_density, 0.0);
ASSERT_DOUBLE_IN_RANGE(segment->end.distance_from_start, 1.61, 1.8);
ASSERT_DOUBLE_IN_RANGE(segment->end.location.x, 1.21, 1.4);
ASSERT_GT(segment->end.global_density, 0.0);
/* Exiting cloud again */
cloudsWalkerSetStepSize(walker, 0.3);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_FALSE(segment->refined);
ASSERT_FALSE(segment->subdivided);
ASSERT_DOUBLE_EQ(segment->length, 0.3);
ASSERT_DOUBLE_IN_RANGE(segment->start.distance_from_start, 1.61, 1.8);
ASSERT_DOUBLE_IN_RANGE(segment->start.location.x, 1.21, 1.4);
ASSERT_GT(segment->start.global_density, 0.0);
ASSERT_DOUBLE_IN_RANGE(segment->end.distance_from_start, 1.91, 2.1);
ASSERT_DOUBLE_IN_RANGE(segment->end.location.x, 1.5, 1.7);
ASSERT_DOUBLE_EQ(segment->end.global_density, 0.0);
/* A step in the void without skipping */
cloudsWalkerSetVoidSkipping(walker, 0);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_FALSE(segment->refined);
ASSERT_FALSE(segment->subdivided);
ASSERT_DOUBLE_EQ(segment->length, 0.3);
ASSERT_DOUBLE_IN_RANGE(segment->start.distance_from_start, 1.91, 2.1);
ASSERT_DOUBLE_IN_RANGE(segment->start.location.x, 1.5, 1.7);
ASSERT_DOUBLE_EQ(segment->start.global_density, 0.0);
ASSERT_DOUBLE_IN_RANGE(segment->end.distance_from_start, 2.21, 2.4);
ASSERT_DOUBLE_IN_RANGE(segment->end.location.x, 1.8, 2.0);
ASSERT_DOUBLE_EQ(segment->end.global_density, 0.0);
/* Walker reached the lookup segment's end, it should stop */
result = cloudsWalkerPerformStep(walker);
ASSERT_EQ(result, 0);
/* Clean up */
cloudsDeleteWalker(walker);
rendererDelete(renderer);
}
TEST(Clouds, WalkingLocal)
{
/* Init */
CloudLayerDefinition layer(NULL);
layer.lower_altitude = -1.0;
layer.thickness = 2.0;
layer.validate();
Renderer* renderer;
renderer = rendererCreate();
renderer->render_quality = 8;
renderer->clouds->getLayerDensity = _getLayerDensitySinX;
renderer->clouds->getEdgeDensity = _getEdgeDensitySquared;
CloudsWalker* walker = cloudsCreateWalker(renderer, &layer, v3(0.0, 0.0, 0.0), v3(1.0, 0.0, 0.0));
CloudWalkerStepInfo* segment;
int result;
/* Test that local density is off by default */
cloudsWalkerSetStepSize(walker, 0.3);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_DOUBLE_EQ(segment->length, 0.3);
ASSERT_DOUBLE_EQ(segment->start.global_density, 0.0);
ASSERT_DOUBLE_EQ(segment->start.local_density, 0.0);
ASSERT_DOUBLE_EQ(segment->end.global_density, 0.951056516295);
ASSERT_DOUBLE_EQ(segment->end.local_density, 0.0);
/* Test it's automatically enabled on subdivision */
cloudsWalkerOrderSubdivide(walker, 2);
result = cloudsWalkerPerformStep(walker);
segment = cloudsWalkerGetLastSegment(walker);
ASSERT_EQ(result, 1);
ASSERT_DOUBLE_EQ(segment->length, 0.15);
ASSERT_DOUBLE_EQ(segment->start.global_density, 0.0);
ASSERT_DOUBLE_EQ(segment->start.local_density, 0.0);
ASSERT_DOUBLE_EQ(segment->end.global_density, 0.809016994375);
ASSERT_DOUBLE_EQ(segment->end.local_density, 0.654508497187);
}
#endif
<commit_msg>Removed unused test file<commit_after><|endoftext|>
|
<commit_before>/*!
\file system.cpp
\brief System management implementation
\author Ivan Shynkarenka
\date 06.07.2015
\copyright MIT License
*/
#include "benchmark/system.h"
#if defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <sys/sysctl.h>
#include <math.h>
#include <pthread.h>
#elif defined(unix) || defined(__unix) || defined(__unix__)
#include <pthread.h>
#include <unistd.h>
#include <fstream>
#include <regex>
#endif
#if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
#include <windows.h>
#include <memory>
#endif
namespace CppBenchmark {
//! @cond
namespace Internals {
#if defined(__APPLE__)
uint32_t CeilLog2(uint32_t x)
{
uint32_t result = 0;
--x;
while (x > 0)
{
++result;
x >>= 1;
}
return result;
}
// This function returns the rational number inside the given interval with
// the smallest denominator (and smallest numerator breaks ties; correctness
// proof neglects floating-point errors).
mach_timebase_info_data_t BestFrac(double a, double b)
{
if (floor(a) < floor(b))
{
mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 };
return rv;
}
double m = floor(a);
mach_timebase_info_data_t next = BestFrac(1 / (b - m), 1 / (a - m));
mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer };
return rv;
}
// This is just less than the smallest thing we can multiply numer by without
// overflowing. CeilLog2(numer) = 64 - number of leading zeros of numer
uint64_t GetExpressibleSpan(uint32_t numer, uint32_t denom)
{
uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - CeilLog2(numer))) - 1;
return maxDiffWithoutOverflow * numer / denom;
}
// The clock may run up to 0.1% faster or slower than the "exact" tick count.
// However, although the bound on the error is the same as for the pragmatic
// answer, the error is actually minimized over the given accuracy bound.
uint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb)
{
tb.numer = 0;
tb.denom = 1;
kern_return_t mtiStatus = mach_timebase_info(&tb);
if (mtiStatus != KERN_SUCCESS)
return 0;
double frac = (double)tb.numer / tb.denom;
uint64_t spanTarget = 315360000000000000llu;
if (GetExpressibleSpan(tb.numer, tb.denom) >= spanTarget)
return 0;
for (double errorTarget = 1 / 1024.0; errorTarget > 0.000001;)
{
mach_timebase_info_data_t newFrac = BestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac);
if (GetExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget)
break;
tb = newFrac;
errorTarget = fabs((double)tb.numer / tb.denom - frac) / frac / 8;
}
return mach_absolute_time();
}
#endif
#if defined(_WIN32) || defined(_WIN64)
// Helper function to count set bits in the processor mask
DWORD CountSetBits(ULONG_PTR pBitMask)
{
DWORD dwLeftShift = sizeof(ULONG_PTR) * 8 - 1;
DWORD dwBitSetCount = 0;
ULONG_PTR pBitTest = (ULONG_PTR)1 << dwLeftShift;
for (DWORD i = 0; i <= dwLeftShift; ++i)
{
dwBitSetCount += ((pBitMask & pBitTest) ? 1 : 0);
pBitTest /= 2;
}
return dwBitSetCount;
}
#endif
} // namespace Internals
//! @endcond
std::string System::CpuArchitecture()
{
#if defined(__APPLE__)
char result[1024];
size_t size = sizeof(result);
if (sysctlbyname("machdep.cpu.brand_string", result, &size, nullptr, 0) == 0)
return result;
return "<unknown>";
#elif defined(unix) || defined(__unix) || defined(__unix__)
static std::regex pattern("model name(.*): (.*)");
std::string line;
std::ifstream stream("/proc/cpuinfo");
while (getline(stream, line))
{
std::smatch matches;
if (std::regex_match(line, matches, pattern))
return matches[2];
}
return "<unknown>";
#elif defined(_WIN32) || defined(_WIN64)
HKEY hKeyProcessor;
LONG lError = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKeyProcessor);
if (lError != ERROR_SUCCESS)
return "<unknown>";
// Smart resource deleter pattern
auto clear = [](HKEY hKey) { RegCloseKey(hKey); };
auto key = std::unique_ptr<std::remove_pointer<HKEY>::type, decltype(clear)>(hKeyProcessor, clear);
CHAR pBuffer[_MAX_PATH] = { 0 };
DWORD dwBufferSize = sizeof(pBuffer);
lError = RegQueryValueExA(key.get(), "ProcessorNameString", nullptr, nullptr, (LPBYTE)pBuffer, &dwBufferSize);
if (lError != ERROR_SUCCESS)
return "<unknown>";
return std::string(pBuffer);
#else
#error Unsupported platform
#endif
}
int System::CpuLogicalCores()
{
return CpuTotalCores().first;
}
int System::CpuPhysicalCores()
{
return CpuTotalCores().second;
}
std::pair<int, int> System::CpuTotalCores()
{
#if defined(__APPLE__)
int logical = 0;
size_t logical_size = sizeof(logical);
if (sysctlbyname("hw.logicalcpu", &logical, &logical_size, nullptr, 0) != 0)
logical = -1;
int physical = 0;
size_t physical_size = sizeof(physical);
if (sysctlbyname("hw.physicalcpu", &physical, &physical_size, nullptr, 0) != 0)
physical = -1;
return std::make_pair(logical, physical);
#elif defined(unix) || defined(__unix) || defined(__unix__)
long processors = sysconf(_SC_NPROCESSORS_ONLN);
return std::make_pair(processors, processors);
#elif defined(_WIN32) || defined(_WIN64)
BOOL allocated = FALSE;
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pBuffer = nullptr;
DWORD dwLength = 0;
while (!allocated)
{
DWORD dwResult = GetLogicalProcessorInformation(pBuffer, &dwLength);
if (dwResult == FALSE)
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
if (pBuffer != nullptr)
free(pBuffer);
pBuffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(dwLength);
if (pBuffer == nullptr)
return std::make_pair(-1, -1);
}
else
return std::make_pair(-1, -1);
}
else
allocated = TRUE;
}
std::pair<int, int> result(0, 0);
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pCurrent = pBuffer;
DWORD dwOffset = 0;
while (dwOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= dwLength)
{
switch (pCurrent->Relationship)
{
case RelationProcessorCore:
result.first += Internals::CountSetBits(pCurrent->ProcessorMask);
result.second += 1;
break;
case RelationNumaNode:
case RelationCache:
case RelationProcessorPackage:
break;
default:
return std::make_pair(-1, -1);
}
dwOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
pCurrent++;
}
free(pBuffer);
return result;
#else
#error Unsupported platform
#endif
}
int64_t System::CpuClockSpeed()
{
#if defined(__APPLE__)
uint64_t frequency = 0;
size_t size = sizeof(frequency);
if (sysctlbyname("hw.cpufrequency", &frequency, &size, nullptr, 0) == 0)
return frequency;
return -1;
#elif defined(unix) || defined(__unix) || defined(__unix__)
static std::regex pattern("cpu MHz(.*): (.*)");
std::string line;
std::ifstream stream("/proc/cpuinfo");
while (getline(stream, line))
{
std::smatch matches;
if (std::regex_match(line, matches, pattern))
return (int64_t)(atof(matches[2].str().c_str()) * 1000 * 1000);
}
return -1;
#elif defined(_WIN32) || defined(_WIN64)
HKEY hKeyProcessor;
long lError = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKeyProcessor);
if (lError != ERROR_SUCCESS)
return -1;
// Smart resource deleter pattern
auto clear = [](HKEY hKey) { RegCloseKey(hKey); };
auto key = std::unique_ptr<std::remove_pointer<HKEY>::type, decltype(clear)>(hKeyProcessor, clear);
DWORD dwMHz = 0;
DWORD dwBufferSize = sizeof(DWORD);
lError = RegQueryValueExA(key.get(), "~MHz", nullptr, nullptr, (LPBYTE)&dwMHz, &dwBufferSize);
if (lError != ERROR_SUCCESS)
return -1;
return dwMHz * 1000 * 1000;
#else
#error Unsupported platform
#endif
}
bool System::CpuHyperThreading()
{
std::pair<int, int> cores = CpuTotalCores();
return (cores.first != cores.second);
}
int64_t System::RamTotal()
{
#if defined(__APPLE__)
int64_t memsize = 0;
size_t size = sizeof(memsize);
if (sysctlbyname("hw.memsize", &memsize, &size, nullptr, 0) == 0)
return memsize;
return -1;
#elif defined(linux) || defined(__linux) || defined(__linux__)
int64_t pages = sysconf(_SC_PHYS_PAGES);
int64_t page_size = sysconf(_SC_PAGESIZE);
if ((pages > 0) && (page_size > 0))
return pages * page_size;
return -1;
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
return status.ullTotalPhys;
#else
#error Unsupported platform
#endif
}
int64_t System::RamFree()
{
#if defined(__APPLE__)
mach_port_t host_port = mach_host_self();
if (host_port == MACH_PORT_NULL)
return -1;
vm_size_t page_size = 0;
host_page_size(host_port, &page_size);
vm_statistics_data_t vmstat;
mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat, &count);
if (kernReturn != KERN_SUCCESS)
return -1;
int64_t used_mem = (vmstat.active_count + vmstat.inactive_count + vmstat.wire_count) * page_size;
int64_t free_mem = vmstat.free_count * page_size;
return free_mem;
#elif defined(linux) || defined(__linux) || defined(__linux__)
int64_t pages = sysconf(_SC_AVPHYS_PAGES);
int64_t page_size = sysconf(_SC_PAGESIZE);
if ((pages > 0) && (page_size > 0))
return pages * page_size;
return -1;
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
return status.ullAvailPhys;
#else
#error Unsupported platform
#endif
}
uint64_t System::CurrentThreadId()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
return (uint64_t)pthread_self();
#elif defined(_WIN32) || defined(_WIN64)
return GetCurrentThreadId();
#else
#error Unsupported platform
#endif
}
uint64_t System::Timestamp()
{
#if defined(__APPLE__)
static mach_timebase_info_data_t info;
static uint64_t bias = Internals::PrepareTimebaseInfo(info);
return (mach_absolute_time() - bias) * info.numer / info.denom;
#elif defined(unix) || defined(__unix) || defined(__unix__)
struct timespec timestamp = { 0 };
clock_gettime(CLOCK_MONOTONIC, ×tamp);
return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec;
#elif defined(_WIN32) || defined(_WIN64)
static uint64_t offset = 0;
static LARGE_INTEGER first = { 0 };
static LARGE_INTEGER frequency = { 0 };
static bool initialized = false;
static bool qpc = true;
if (!initialized)
{
// Calculate timestamp offset
FILETIME timestamp;
GetSystemTimePreciseAsFileTime(×tamp);
ULARGE_INTEGER result;
result.LowPart = timestamp.dwLowDateTime;
result.HighPart = timestamp.dwHighDateTime;
// Convert 01.01.1601 to 01.01.1970
result.QuadPart -= 116444736000000000ll;
offset = result.QuadPart * 100;
// Setup performance counter
qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first);
initialized = true;
}
if (qpc)
{
LARGE_INTEGER timestamp = { 0 };
QueryPerformanceCounter(×tamp);
timestamp.QuadPart -= first.QuadPart;
return offset + ((timestamp.QuadPart * 1000 * 1000 * 1000) / frequency.QuadPart);
}
else
return offset;
#else
#error Unsupported platform
#endif
}
} // namespace CppBenchmark
<commit_msg>Cygwing<commit_after>/*!
\file system.cpp
\brief System management implementation
\author Ivan Shynkarenka
\date 06.07.2015
\copyright MIT License
*/
#include "benchmark/system.h"
#if defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <sys/sysctl.h>
#include <math.h>
#include <pthread.h>
#elif defined(unix) || defined(__unix) || defined(__unix__)
#include <pthread.h>
#include <unistd.h>
#include <fstream>
#include <regex>
#endif
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#include <memory>
#endif
namespace CppBenchmark {
//! @cond
namespace Internals {
#if defined(__APPLE__)
uint32_t CeilLog2(uint32_t x)
{
uint32_t result = 0;
--x;
while (x > 0)
{
++result;
x >>= 1;
}
return result;
}
// This function returns the rational number inside the given interval with
// the smallest denominator (and smallest numerator breaks ties; correctness
// proof neglects floating-point errors).
mach_timebase_info_data_t BestFrac(double a, double b)
{
if (floor(a) < floor(b))
{
mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 };
return rv;
}
double m = floor(a);
mach_timebase_info_data_t next = BestFrac(1 / (b - m), 1 / (a - m));
mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer };
return rv;
}
// This is just less than the smallest thing we can multiply numer by without
// overflowing. CeilLog2(numer) = 64 - number of leading zeros of numer
uint64_t GetExpressibleSpan(uint32_t numer, uint32_t denom)
{
uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - CeilLog2(numer))) - 1;
return maxDiffWithoutOverflow * numer / denom;
}
// The clock may run up to 0.1% faster or slower than the "exact" tick count.
// However, although the bound on the error is the same as for the pragmatic
// answer, the error is actually minimized over the given accuracy bound.
uint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb)
{
tb.numer = 0;
tb.denom = 1;
kern_return_t mtiStatus = mach_timebase_info(&tb);
if (mtiStatus != KERN_SUCCESS)
return 0;
double frac = (double)tb.numer / tb.denom;
uint64_t spanTarget = 315360000000000000llu;
if (GetExpressibleSpan(tb.numer, tb.denom) >= spanTarget)
return 0;
for (double errorTarget = 1 / 1024.0; errorTarget > 0.000001;)
{
mach_timebase_info_data_t newFrac = BestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac);
if (GetExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget)
break;
tb = newFrac;
errorTarget = fabs((double)tb.numer / tb.denom - frac) / frac / 8;
}
return mach_absolute_time();
}
#endif
#if defined(_WIN32) || defined(_WIN64)
// Helper function to count set bits in the processor mask
DWORD CountSetBits(ULONG_PTR pBitMask)
{
DWORD dwLeftShift = sizeof(ULONG_PTR) * 8 - 1;
DWORD dwBitSetCount = 0;
ULONG_PTR pBitTest = (ULONG_PTR)1 << dwLeftShift;
for (DWORD i = 0; i <= dwLeftShift; ++i)
{
dwBitSetCount += ((pBitMask & pBitTest) ? 1 : 0);
pBitTest /= 2;
}
return dwBitSetCount;
}
#endif
} // namespace Internals
//! @endcond
std::string System::CpuArchitecture()
{
#if defined(__APPLE__)
char result[1024];
size_t size = sizeof(result);
if (sysctlbyname("machdep.cpu.brand_string", result, &size, nullptr, 0) == 0)
return result;
return "<unknown>";
#elif defined(unix) || defined(__unix) || defined(__unix__)
static std::regex pattern("model name(.*): (.*)");
std::string line;
std::ifstream stream("/proc/cpuinfo");
while (getline(stream, line))
{
std::smatch matches;
if (std::regex_match(line, matches, pattern))
return matches[2];
}
return "<unknown>";
#elif defined(_WIN32) || defined(_WIN64)
HKEY hKeyProcessor;
LONG lError = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKeyProcessor);
if (lError != ERROR_SUCCESS)
return "<unknown>";
// Smart resource deleter pattern
auto clear = [](HKEY hKey) { RegCloseKey(hKey); };
auto key = std::unique_ptr<std::remove_pointer<HKEY>::type, decltype(clear)>(hKeyProcessor, clear);
CHAR pBuffer[_MAX_PATH] = { 0 };
DWORD dwBufferSize = sizeof(pBuffer);
lError = RegQueryValueExA(key.get(), "ProcessorNameString", nullptr, nullptr, (LPBYTE)pBuffer, &dwBufferSize);
if (lError != ERROR_SUCCESS)
return "<unknown>";
return std::string(pBuffer);
#else
#error Unsupported platform
#endif
}
int System::CpuLogicalCores()
{
return CpuTotalCores().first;
}
int System::CpuPhysicalCores()
{
return CpuTotalCores().second;
}
std::pair<int, int> System::CpuTotalCores()
{
#if defined(__APPLE__)
int logical = 0;
size_t logical_size = sizeof(logical);
if (sysctlbyname("hw.logicalcpu", &logical, &logical_size, nullptr, 0) != 0)
logical = -1;
int physical = 0;
size_t physical_size = sizeof(physical);
if (sysctlbyname("hw.physicalcpu", &physical, &physical_size, nullptr, 0) != 0)
physical = -1;
return std::make_pair(logical, physical);
#elif defined(unix) || defined(__unix) || defined(__unix__)
long processors = sysconf(_SC_NPROCESSORS_ONLN);
return std::make_pair(processors, processors);
#elif defined(_WIN32) || defined(_WIN64)
BOOL allocated = FALSE;
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pBuffer = nullptr;
DWORD dwLength = 0;
while (!allocated)
{
DWORD dwResult = GetLogicalProcessorInformation(pBuffer, &dwLength);
if (dwResult == FALSE)
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
if (pBuffer != nullptr)
free(pBuffer);
pBuffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(dwLength);
if (pBuffer == nullptr)
return std::make_pair(-1, -1);
}
else
return std::make_pair(-1, -1);
}
else
allocated = TRUE;
}
std::pair<int, int> result(0, 0);
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pCurrent = pBuffer;
DWORD dwOffset = 0;
while (dwOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= dwLength)
{
switch (pCurrent->Relationship)
{
case RelationProcessorCore:
result.first += Internals::CountSetBits(pCurrent->ProcessorMask);
result.second += 1;
break;
case RelationNumaNode:
case RelationCache:
case RelationProcessorPackage:
break;
default:
return std::make_pair(-1, -1);
}
dwOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
pCurrent++;
}
free(pBuffer);
return result;
#else
#error Unsupported platform
#endif
}
int64_t System::CpuClockSpeed()
{
#if defined(__APPLE__)
uint64_t frequency = 0;
size_t size = sizeof(frequency);
if (sysctlbyname("hw.cpufrequency", &frequency, &size, nullptr, 0) == 0)
return frequency;
return -1;
#elif defined(unix) || defined(__unix) || defined(__unix__)
static std::regex pattern("cpu MHz(.*): (.*)");
std::string line;
std::ifstream stream("/proc/cpuinfo");
while (getline(stream, line))
{
std::smatch matches;
if (std::regex_match(line, matches, pattern))
return (int64_t)(atof(matches[2].str().c_str()) * 1000 * 1000);
}
return -1;
#elif defined(_WIN32) || defined(_WIN64)
HKEY hKeyProcessor;
long lError = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKeyProcessor);
if (lError != ERROR_SUCCESS)
return -1;
// Smart resource deleter pattern
auto clear = [](HKEY hKey) { RegCloseKey(hKey); };
auto key = std::unique_ptr<std::remove_pointer<HKEY>::type, decltype(clear)>(hKeyProcessor, clear);
DWORD dwMHz = 0;
DWORD dwBufferSize = sizeof(DWORD);
lError = RegQueryValueExA(key.get(), "~MHz", nullptr, nullptr, (LPBYTE)&dwMHz, &dwBufferSize);
if (lError != ERROR_SUCCESS)
return -1;
return dwMHz * 1000 * 1000;
#else
#error Unsupported platform
#endif
}
bool System::CpuHyperThreading()
{
std::pair<int, int> cores = CpuTotalCores();
return (cores.first != cores.second);
}
int64_t System::RamTotal()
{
#if defined(__APPLE__)
int64_t memsize = 0;
size_t size = sizeof(memsize);
if (sysctlbyname("hw.memsize", &memsize, &size, nullptr, 0) == 0)
return memsize;
return -1;
#elif defined(unix) || defined(__unix) || defined(__unix__)
int64_t pages = sysconf(_SC_PHYS_PAGES);
int64_t page_size = sysconf(_SC_PAGESIZE);
if ((pages > 0) && (page_size > 0))
return pages * page_size;
return -1;
#elif defined(_WIN32) || defined(_WIN64)
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
return status.ullTotalPhys;
#else
#error Unsupported platform
#endif
}
int64_t System::RamFree()
{
#if defined(__APPLE__)
mach_port_t host_port = mach_host_self();
if (host_port == MACH_PORT_NULL)
return -1;
vm_size_t page_size = 0;
host_page_size(host_port, &page_size);
vm_statistics_data_t vmstat;
mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat, &count);
if (kernReturn != KERN_SUCCESS)
return -1;
int64_t used_mem = (vmstat.active_count + vmstat.inactive_count + vmstat.wire_count) * page_size;
int64_t free_mem = vmstat.free_count * page_size;
return free_mem;
#elif defined(unix) || defined(__unix) || defined(__unix__)
int64_t pages = sysconf(_SC_AVPHYS_PAGES);
int64_t page_size = sysconf(_SC_PAGESIZE);
if ((pages > 0) && (page_size > 0))
return pages * page_size;
return -1;
#elif defined(_WIN32) || defined(_WIN64)
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
return status.ullAvailPhys;
#else
#error Unsupported platform
#endif
}
uint64_t System::CurrentThreadId()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
return (uint64_t)pthread_self();
#elif defined(_WIN32) || defined(_WIN64)
return GetCurrentThreadId();
#else
#error Unsupported platform
#endif
}
uint64_t System::Timestamp()
{
#if defined(__APPLE__)
static mach_timebase_info_data_t info;
static uint64_t bias = Internals::PrepareTimebaseInfo(info);
return (mach_absolute_time() - bias) * info.numer / info.denom;
#elif defined(unix) || defined(__unix) || defined(__unix__)
struct timespec timestamp = { 0 };
clock_gettime(CLOCK_MONOTONIC, ×tamp);
return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec;
#elif defined(_WIN32) || defined(_WIN64)
static uint64_t offset = 0;
static LARGE_INTEGER first = { 0 };
static LARGE_INTEGER frequency = { 0 };
static bool initialized = false;
static bool qpc = true;
if (!initialized)
{
// Calculate timestamp offset
FILETIME timestamp;
GetSystemTimePreciseAsFileTime(×tamp);
ULARGE_INTEGER result;
result.LowPart = timestamp.dwLowDateTime;
result.HighPart = timestamp.dwHighDateTime;
// Convert 01.01.1601 to 01.01.1970
result.QuadPart -= 116444736000000000ll;
offset = result.QuadPart * 100;
// Setup performance counter
qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first);
initialized = true;
}
if (qpc)
{
LARGE_INTEGER timestamp = { 0 };
QueryPerformanceCounter(×tamp);
timestamp.QuadPart -= first.QuadPart;
return offset + ((timestamp.QuadPart * 1000 * 1000 * 1000) / frequency.QuadPart);
}
else
return offset;
#else
#error Unsupported platform
#endif
}
} // namespace CppBenchmark
<|endoftext|>
|
<commit_before>#include "thumbnail_manager.hpp"
#include <algorithm> // find
#include "algorithm.hpp"
thumbnail_manager::thumbnail_manager(x_connection & c,
const layout_t * layout,
const thumbnail_t::factory * factory)
: m_c(c), m_layout(layout), m_factory(factory)
{
m_c.attach(0, XCB_PROPERTY_NOTIFY, this);
m_c.attach(20, XCB_CONFIGURE_NOTIFY, this);
m_c.update_input(m_c.root_window(), XCB_EVENT_MASK_PROPERTY_CHANGE);
}
thumbnail_manager::~thumbnail_manager(void)
{
m_c.detach(XCB_PROPERTY_NOTIFY, this);
m_c.detach(XCB_CONFIGURE_NOTIFY, this);
}
void
thumbnail_manager::show(void)
{
m_active = true;
update();
m_cyclic_iterator = window_cyclic_iterator(&m_windows);
m_next_window = *(m_cyclic_iterator + 1);
m_current_window = *m_cyclic_iterator;
for (auto & item : m_thumbnails) {
item.second->show().update();
}
}
void
thumbnail_manager::hide(void)
{
m_active = false;
for (auto & item : m_thumbnails) {
item.second->hide();
}
}
void
thumbnail_manager::next(void) { next_or_prev(true); }
void
thumbnail_manager::prev(void) { next_or_prev(false); }
void
thumbnail_manager::select(const xcb_window_t & window)
{
if (window == XCB_NONE) {
try {
m_thumbnails.at(*m_cyclic_iterator)->select();
} catch (...) {}
} else {
for (auto & item : m_thumbnails) {
if (item.second->id() == window) {
item.second->select();
break;
}
}
}
}
void
thumbnail_manager::highlight(const unsigned int & window)
{
for (auto & item : m_thumbnails) {
if (item.second->id() == window) {
try {
m_thumbnails.at(m_current_window)->highlight(false).update();
item.second->highlight(true).update();
while (*m_cyclic_iterator != item.first) ++m_cyclic_iterator;
m_next_window = *(m_cyclic_iterator + 1);
m_current_window = *m_cyclic_iterator;
} catch (...) {}
break;
}
}
}
void
thumbnail_manager::east(void)
{
xcb_window_t tid = nearest_thumbnail(
std::bind(&thumbnail_manager::is_east, this, std::placeholders::_1));
if (tid != XCB_NONE) highlight(tid);
}
void
thumbnail_manager::west(void)
{
xcb_window_t tid = nearest_thumbnail(
std::bind(&thumbnail_manager::is_west, this, std::placeholders::_1));
if (tid != XCB_NONE) highlight(tid);
}
void
thumbnail_manager::north(void)
{
xcb_window_t tid = nearest_thumbnail(
std::bind(&thumbnail_manager::is_north, this, std::placeholders::_1));
if (tid != XCB_NONE) highlight(tid);
}
void
thumbnail_manager::south(void)
{
xcb_window_t tid = nearest_thumbnail(
std::bind(&thumbnail_manager::is_south, this, std::placeholders::_1));
if (tid != XCB_NONE) highlight(tid);
}
bool
thumbnail_manager::handle(xcb_generic_event_t * ge)
{
if (XCB_PROPERTY_NOTIFY == (ge->response_type & ~0x80)) {
xcb_property_notify_event_t * e = (xcb_property_notify_event_t *)ge;
if (m_active
&& e->window == m_c.root_window()
&& e->atom == m_c.intern_atom("_NET_CLIENT_LIST_STACKING"))
{
update();
reset();
try {
m_thumbnails.at(*m_cyclic_iterator)->highlight(true).update();
} catch (...) {}
}
return true;
} else if (XCB_CONFIGURE_NOTIFY == (ge->response_type & ~0x80)) {
if (m_active) {
auto rects = m_layout->arrange(query_current_screen(), m_windows.size());
for (size_t i = 0; i < m_windows.size(); ++i) {
m_thumbnails.at(m_windows[i])->update(rects[i]).update();
}
}
return true;
}
return false;
}
inline
thumbnail_manager &
thumbnail_manager::reset(void)
{
bool found = false;
m_cyclic_iterator = window_cyclic_iterator(&m_windows);
// search for current thumbnail
for (std::size_t i = 0; i < m_windows.size(); ++i) {
if (*m_cyclic_iterator == m_current_window) {
found = true;
break;
} else {
++m_cyclic_iterator;
}
}
// search for next thumbnail if current was not found
if (! found) {
m_cyclic_iterator = window_cyclic_iterator(&m_windows);
for (std::size_t i = 0; i < m_windows.size(); ++i) {
if (*m_cyclic_iterator == m_next_window) {
break;
} else {
++m_cyclic_iterator;
}
}
}
m_next_window = *(m_cyclic_iterator + 1);
m_current_window = *m_cyclic_iterator;
return *this;
}
inline
thumbnail_manager &
thumbnail_manager::update(void)
{
auto windows = m_c.net_client_list_stacking();
m_windows = window_list_t(windows.begin(), windows.end());
auto rects = m_layout->arrange(query_current_screen(), m_windows.size());
for (auto item = m_thumbnails.begin(); item != m_thumbnails.end(); ) {
auto result = std::find(m_windows.begin(), m_windows.end(), item->first);
if (result == m_windows.end()) {
item = m_thumbnails.erase(item);
} else {
++item;
}
}
for (size_t i = 0; i < m_windows.size(); ++i) {
auto result = m_thumbnails.find(m_windows[i]);
if (result == m_thumbnails.end()) {
m_thumbnails[m_windows[i]] = m_factory->make(m_windows[i], rects[i]);
if (m_active) {
m_thumbnails[m_windows[i]]->show().update();
}
} else {
result->second->highlight(false).update(rects[i]).update();
}
}
return *this;
}
thumbnail_manager &
thumbnail_manager::next_or_prev(bool next)
{
try {
m_thumbnails.at(*m_cyclic_iterator)->highlight(false).update();
next ? ++m_cyclic_iterator : --m_cyclic_iterator;
m_thumbnails.at(*m_cyclic_iterator)->highlight(true).update();
} catch (...) {}
m_next_window = *(m_cyclic_iterator + 1);
m_current_window = *m_cyclic_iterator;
return *this;
}
inline xcb_window_t
thumbnail_manager::
nearest_thumbnail(const std::function<bool(double)> & direction)
{
xcb_window_t thumbnail_id = XCB_NONE;
try {
auto & current = m_thumbnails.at(m_current_window);
auto & r1 = current->rect();
// in X (x,y) coordinates are actually flipped on the x axis
// this means that (0,0) is in the top left corner, not in bottom left
auto p1 = std::make_tuple( r1.x() + (r1.width() / 2),
-(r1.y() + (r1.height() / 2)));
double min_distance = 0xffffffff;
for (auto & item : m_thumbnails) {
if (item.second->id() == current->id()) {
continue;
} else {
auto & r2 = item.second->rect();
// in X (x,y) coordinates are actually flipped on the x axis
// this means that (0,0) is in the top left corner, not in bottom left
auto p2 = std::make_tuple( r2.x() + (r2.width() / 2),
-(r2.y() + (r2.height() / 2)));
if (direction(algorithm::angle()(p1, p2))) {
double distance = algorithm::distance()(p1, p2);
if (distance < min_distance) {
min_distance = distance;
thumbnail_id = item.second->id();
}
}
}
}
} catch (...) {}
return thumbnail_id;
}
// 2*M_PI ^= 360°
// 2*M_PI - M_PI/4 ^= 315°
// 2*M_PI - M_PI/2 ^= 270°
// M_PI + M_PI/4 ^= 225°
// M_PI ^= 180°
// M_PI - M_PI/4 ^= 135°
// M_PI/2 ^= 90°
// M_PI/4 ^= 45°
inline bool
thumbnail_manager::is_east(double angle)
{
// (>=0° && <=45°) || >= 315°
return (angle >= 0 && angle <= M_PI/4) || angle >= 7*M_PI/4;
}
inline bool
thumbnail_manager::is_west(double angle)
{
// >=135° && <=225°
return angle >= 3*M_PI/4 && angle <= 5*M_PI/4;
}
inline bool
thumbnail_manager::is_north(double angle)
{
// >=45° && <=135°
return angle >= M_PI/4 && angle <= 3*M_PI/4;
}
inline bool
thumbnail_manager::is_south(double angle)
{
// >=225° && <= 315°
return angle >= 5*M_PI/4 && angle <= 7*M_PI/4;
}
rectangle
thumbnail_manager::query_current_screen(void)
{
rectangle screen = { 0, 0, 800, 600 };
try {
auto pos = m_c.query_pointer();
screen = m_c.current_screen(pos.first);
} catch (...) {}
return screen;
}
<commit_msg>This can be already done in the event handler<commit_after>#include "thumbnail_manager.hpp"
#include <algorithm> // find
#include "algorithm.hpp"
thumbnail_manager::thumbnail_manager(x_connection & c,
const layout_t * layout,
const thumbnail_t::factory * factory)
: m_c(c), m_layout(layout), m_factory(factory)
{
m_c.attach(0, XCB_PROPERTY_NOTIFY, this);
m_c.attach(20, XCB_CONFIGURE_NOTIFY, this);
m_c.update_input(m_c.root_window(), XCB_EVENT_MASK_PROPERTY_CHANGE);
}
thumbnail_manager::~thumbnail_manager(void)
{
m_c.detach(XCB_PROPERTY_NOTIFY, this);
m_c.detach(XCB_CONFIGURE_NOTIFY, this);
}
void
thumbnail_manager::show(void)
{
m_active = true;
update();
m_cyclic_iterator = window_cyclic_iterator(&m_windows);
m_next_window = *(m_cyclic_iterator + 1);
m_current_window = *m_cyclic_iterator;
for (auto & item : m_thumbnails) {
item.second->show().update();
}
}
void
thumbnail_manager::hide(void)
{
m_active = false;
for (auto & item : m_thumbnails) {
item.second->hide();
}
}
void
thumbnail_manager::next(void) { next_or_prev(true); }
void
thumbnail_manager::prev(void) { next_or_prev(false); }
void
thumbnail_manager::select(const xcb_window_t & window)
{
if (window == XCB_NONE) {
try {
m_thumbnails.at(*m_cyclic_iterator)->select();
} catch (...) {}
} else {
for (auto & item : m_thumbnails) {
if (item.second->id() == window) {
item.second->select();
break;
}
}
}
}
void
thumbnail_manager::highlight(const unsigned int & window)
{
for (auto & item : m_thumbnails) {
if (item.second->id() == window) {
try {
m_thumbnails.at(m_current_window)->highlight(false).update();
item.second->highlight(true).update();
while (*m_cyclic_iterator != item.first) ++m_cyclic_iterator;
m_next_window = *(m_cyclic_iterator + 1);
m_current_window = *m_cyclic_iterator;
} catch (...) {}
break;
}
}
}
void
thumbnail_manager::east(void)
{
xcb_window_t tid = nearest_thumbnail(
std::bind(&thumbnail_manager::is_east, this, std::placeholders::_1));
if (tid != XCB_NONE) highlight(tid);
}
void
thumbnail_manager::west(void)
{
xcb_window_t tid = nearest_thumbnail(
std::bind(&thumbnail_manager::is_west, this, std::placeholders::_1));
if (tid != XCB_NONE) highlight(tid);
}
void
thumbnail_manager::north(void)
{
xcb_window_t tid = nearest_thumbnail(
std::bind(&thumbnail_manager::is_north, this, std::placeholders::_1));
if (tid != XCB_NONE) highlight(tid);
}
void
thumbnail_manager::south(void)
{
xcb_window_t tid = nearest_thumbnail(
std::bind(&thumbnail_manager::is_south, this, std::placeholders::_1));
if (tid != XCB_NONE) highlight(tid);
}
bool
thumbnail_manager::handle(xcb_generic_event_t * ge)
{
if (XCB_PROPERTY_NOTIFY == (ge->response_type & ~0x80)) {
xcb_property_notify_event_t * e = (xcb_property_notify_event_t *)ge;
if (m_active
&& e->window == m_c.root_window()
&& e->atom == m_c.intern_atom("_NET_CLIENT_LIST_STACKING"))
{
update();
reset();
try {
m_thumbnails.at(*m_cyclic_iterator)->highlight(true).update();
} catch (...) {}
}
return true;
} else if (XCB_CONFIGURE_NOTIFY == (ge->response_type & ~0x80)) {
if (m_active) {
auto rects = m_layout->arrange(query_current_screen(), m_windows.size());
for (size_t i = 0; i < m_windows.size(); ++i) {
m_thumbnails.at(m_windows[i])->update(rects[i]).update();
}
}
return true;
}
return false;
}
inline
thumbnail_manager &
thumbnail_manager::reset(void)
{
bool found = false;
m_cyclic_iterator = window_cyclic_iterator(&m_windows);
// search for current thumbnail
for (std::size_t i = 0; i < m_windows.size(); ++i) {
if (*m_cyclic_iterator == m_current_window) {
found = true;
break;
} else {
++m_cyclic_iterator;
}
}
// search for next thumbnail if current was not found
if (! found) {
m_cyclic_iterator = window_cyclic_iterator(&m_windows);
for (std::size_t i = 0; i < m_windows.size(); ++i) {
if (*m_cyclic_iterator == m_next_window) {
break;
} else {
++m_cyclic_iterator;
}
}
}
m_next_window = *(m_cyclic_iterator + 1);
m_current_window = *m_cyclic_iterator;
return *this;
}
inline
thumbnail_manager &
thumbnail_manager::update(void)
{
auto windows = m_c.net_client_list_stacking();
m_windows = window_list_t(windows.begin(), windows.end());
auto rects = m_layout->arrange(query_current_screen(), m_windows.size());
for (auto item = m_thumbnails.begin(); item != m_thumbnails.end(); ) {
auto result = std::find(m_windows.begin(), m_windows.end(), item->first);
if (result == m_windows.end()) {
item = m_thumbnails.erase(item);
} else {
++item;
}
}
for (size_t i = 0; i < m_windows.size(); ++i) {
auto result = m_thumbnails.find(m_windows[i]);
if (result == m_thumbnails.end()) {
m_thumbnails[m_windows[i]] = m_factory->make(m_windows[i], rects[i]);
} else {
result->second->update(rects[i]);
}
}
return *this;
}
thumbnail_manager &
thumbnail_manager::next_or_prev(bool next)
{
try {
m_thumbnails.at(*m_cyclic_iterator)->highlight(false).update();
next ? ++m_cyclic_iterator : --m_cyclic_iterator;
m_thumbnails.at(*m_cyclic_iterator)->highlight(true).update();
} catch (...) {}
m_next_window = *(m_cyclic_iterator + 1);
m_current_window = *m_cyclic_iterator;
return *this;
}
inline xcb_window_t
thumbnail_manager::
nearest_thumbnail(const std::function<bool(double)> & direction)
{
xcb_window_t thumbnail_id = XCB_NONE;
try {
auto & current = m_thumbnails.at(m_current_window);
auto & r1 = current->rect();
// in X (x,y) coordinates are actually flipped on the x axis
// this means that (0,0) is in the top left corner, not in bottom left
auto p1 = std::make_tuple( r1.x() + (r1.width() / 2),
-(r1.y() + (r1.height() / 2)));
double min_distance = 0xffffffff;
for (auto & item : m_thumbnails) {
if (item.second->id() == current->id()) {
continue;
} else {
auto & r2 = item.second->rect();
// in X (x,y) coordinates are actually flipped on the x axis
// this means that (0,0) is in the top left corner, not in bottom left
auto p2 = std::make_tuple( r2.x() + (r2.width() / 2),
-(r2.y() + (r2.height() / 2)));
if (direction(algorithm::angle()(p1, p2))) {
double distance = algorithm::distance()(p1, p2);
if (distance < min_distance) {
min_distance = distance;
thumbnail_id = item.second->id();
}
}
}
}
} catch (...) {}
return thumbnail_id;
}
// 2*M_PI ^= 360°
// 2*M_PI - M_PI/4 ^= 315°
// 2*M_PI - M_PI/2 ^= 270°
// M_PI + M_PI/4 ^= 225°
// M_PI ^= 180°
// M_PI - M_PI/4 ^= 135°
// M_PI/2 ^= 90°
// M_PI/4 ^= 45°
inline bool
thumbnail_manager::is_east(double angle)
{
// (>=0° && <=45°) || >= 315°
return (angle >= 0 && angle <= M_PI/4) || angle >= 7*M_PI/4;
}
inline bool
thumbnail_manager::is_west(double angle)
{
// >=135° && <=225°
return angle >= 3*M_PI/4 && angle <= 5*M_PI/4;
}
inline bool
thumbnail_manager::is_north(double angle)
{
// >=45° && <=135°
return angle >= M_PI/4 && angle <= 3*M_PI/4;
}
inline bool
thumbnail_manager::is_south(double angle)
{
// >=225° && <= 315°
return angle >= 5*M_PI/4 && angle <= 7*M_PI/4;
}
rectangle
thumbnail_manager::query_current_screen(void)
{
rectangle screen = { 0, 0, 800, 600 };
try {
auto pos = m_c.query_pointer();
screen = m_c.current_screen(pos.first);
} catch (...) {}
return screen;
}
<|endoftext|>
|
<commit_before>#line 2 "togo/task_manager.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <togo/config.hpp>
#include <togo/utility.hpp>
#include <togo/assert.hpp>
#include <togo/log.hpp>
#include <togo/array.hpp>
#include <togo/priority_queue.hpp>
#include <togo/thread.hpp>
#include <togo/mutex.hpp>
#include <togo/condvar.hpp>
#include <togo/task_manager.hpp>
#include <cstring>
#include <cstdio>
namespace togo {
#undef TOGO_TEST_LOG_ENABLE
#if defined(TOGO_TEST_TASK_MANAGER)
#define TOGO_TEST_LOG_ENABLE
#endif
#include <togo/log_test.hpp>
namespace {
static constexpr TaskID const ID_NULL{0};
inline bool operator==(TaskID const& x, TaskID const& y) {
return x._value == y._value;
}
inline bool operator!=(TaskID const& x, TaskID const& y) {
return x._value != y._value;
}
inline unsigned task_sort_key(Task const& task) {
// Sort by num_incomplete, then by priority
return (~unsigned{task.num_incomplete} << 16 & 0xFFFF0000) | unsigned{task.priority};
}
bool task_less(Task* const& x, Task* const& y) {
return task_sort_key(*x) < task_sort_key(*y);
}
enum : unsigned {
// 128 tasks
ID_SHIFT = 7,
NUM_TASKS = 1 << ID_SHIFT,
ID_ADD = 1 << ID_SHIFT,
INDEX_MASK = NUM_TASKS - 1,
FLAG_SHUTDOWN = 1 << 0,
};
inline Task& get_task(TaskManager& tm, TaskID const id) {
return tm._tasks[id._value & INDEX_MASK].task;
}
inline bool is_complete(Task const& task, TaskID const expected_id) {
return task.id != expected_id || task.num_incomplete == 0;
}
inline bool is_ready(Task const& task) {
return task.num_incomplete <= 1;
}
inline void free_slot(TaskManager& tm, Task& task) {
TaskSlot& slot = *reinterpret_cast<TaskSlot*>(&task);
unsigned index = slot.id._value & INDEX_MASK;
slot.hole.next = nullptr;
while (index--) {
TaskSlot& slot_before = tm._tasks[index];
if (slot_before.id == ID_NULL) {
slot.hole.next = slot_before.hole.next;
slot_before.hole.next = &slot;
break;
}
}
if (!slot.hole.next) {
// No hole between slot and head
slot.hole.next = tm._first_hole;
tm._first_hole = &slot;
}
slot.id = ID_NULL;
}
inline Task& add_task(
TaskManager& tm,
TaskWork const& work,
u16 const priority
) {
TOGO_ASSERT(tm._num_tasks != NUM_TASKS, "cannot add task to full task manager");
TOGO_DEBUG_ASSERTE(tm._first_hole != nullptr);
TaskSlot& slot = *tm._first_hole;
tm._first_hole = slot.hole.next;
std::memset(&slot.task, 0, sizeof(Task));
slot.task.id._value = tm._id_gen | (&slot - tm._tasks);
slot.task.work = work;
slot.task.priority = priority;
slot.task.num_incomplete = 1;
tm._id_gen = max(tm._id_gen + ID_ADD, u32{ID_ADD});
return slot.task;
}
inline void queue_task(TaskManager& tm, Task& task) {
/*TOGO_TEST_LOG_DEBUGF(
"queue_task: push: %04u %03u @ %04hu / %04hu\n",
task.id._value >> ID_SHIFT,
task.id._value & INDEX_MASK,
task.num_incomplete,
task.priority
);*/
priority_queue::push(tm._queue, &task);
/*#if defined(TOGO_TEST_TASK_MANAGER)
Task* const front = priority_queue::front(tm._queue);
TOGO_TEST_LOG_DEBUGF(
"queue_task: front: %04u %03u @ %04hu / %04hu\n",
front->id._value >> ID_SHIFT,
front->id._value & INDEX_MASK,
front->num_incomplete,
front->priority
);
#endif*/
condvar::signal(tm._work_signal, tm._mutex);
}
inline void complete_task(TaskManager& tm, Task& task) {
// TODO: Reorder each parent in the priority queue
TOGO_TEST_LOG_DEBUGF(
"complete_task : %-32s: %04u %03u @ %04hu / %04hu\n",
thread::name(),
task.id._value >> ID_SHIFT,
task.id._value & INDEX_MASK,
task.num_incomplete,
task.priority
);
task.num_incomplete = 0;
TaskID parent_id = task.parent;
while (parent_id != ID_NULL) {
Task& parent = get_task(tm, parent_id);
--parent.num_incomplete;
parent_id = parent.num_incomplete ? parent.parent : ID_NULL;
}
free_slot(tm, task);
condvar::signal_all(tm._work_signal, tm._mutex);
}
void execute_pending(TaskManager& tm, TaskID const wait_id) {
Task* task = nullptr;
Task const* wait_task = nullptr;
if (wait_id != ID_NULL) {
wait_task = &get_task(tm, wait_id);
}
MutexLock lock{tm._mutex};
while (true) {
if (task) {
complete_task(tm, *task);
task = nullptr;
}
if (wait_task && is_complete(*wait_task, wait_id)) {
return;
} else if (tm._flags & FLAG_SHUTDOWN) {
return;
} else if (
priority_queue::any(tm._queue) &&
is_ready(*priority_queue::front(tm._queue))
) {
task = priority_queue::front(tm._queue);
priority_queue::pop(tm._queue);
TOGO_TEST_LOG_DEBUGF(
"execute_pending: %-32s: %04u %03u @ %04hu / %04hu [take]\n",
thread::name(),
task->id._value >> ID_SHIFT,
task->id._value & INDEX_MASK,
task->num_incomplete,
task->priority
);
// If !task->work.func, the task is empty
if (task->work.func) {
// task->id and task->work should not be modified
// after adding and the task should not be destroyed
// by any other function, so this is free of race
// conditions.
mutex::unlock(tm._mutex);
task->work.func(task->id, task->work.data);
mutex::lock(tm._mutex);
}
continue;
}
condvar::wait(tm._work_signal, lock);
}
}
void* worker_func(void* const tm_void) {
TaskManager& tm = *static_cast<TaskManager*>(tm_void);
TOGO_TEST_LOG_DEBUGF("worker_func: start: %s\n", thread::name());
execute_pending(tm, ID_NULL);
TOGO_TEST_LOG_DEBUGF("worker_func: shutdown: %s\n", thread::name());
return nullptr;
}
} // anonymous namespace
static_assert(
NUM_TASKS == array_extent(&TaskManager::_tasks),
"ID_SHIFT does not fit with the size of TaskManager::_tasks"
);
// class TaskManager implementation
TaskManager::~TaskManager() {
{
MutexLock lock{_mutex};
_flags |= FLAG_SHUTDOWN;
condvar::signal_all(_work_signal, lock);
}
for (Thread* const worker_thread : _workers) {
thread::join(worker_thread);
}
}
TaskManager::TaskManager(unsigned num_workers, Allocator& allocator)
: _tasks()
, _queue(task_less, allocator)
, _workers(allocator)
, _mutex(MutexType::normal)
, _work_signal()
, _first_hole(_tasks)
, _num_tasks(0)
, _flags(0)
, _id_gen(ID_ADD)
{
TaskSlot* const last = _tasks + (NUM_TASKS - 1);
for (TaskSlot* slot = _tasks; slot != last; ++slot) {
slot->hole.next = slot + 1;
}
last->hole.next = nullptr;
priority_queue::reserve(_queue, NUM_TASKS);
if (num_workers) {
array::reserve(_workers, num_workers);
char name[32];
while (num_workers--) {
std::snprintf(name, sizeof(name), "tm-%8p-worker-%u", this, num_workers);
array::push_back(_workers, thread::create(name, this, worker_func, allocator));
}
}
}
// interface task_manager implementation
TaskID task_manager::add(
TaskManager& tm,
TaskWork const& work,
u16 const priority
) {
MutexLock lock{tm._mutex};
Task& task = add_task(tm, work, priority);
queue_task(tm, task);
return task.id;
}
TaskID task_manager::add_hold(
TaskManager& tm,
TaskWork const& work,
u16 const priority
) {
MutexLock lock{tm._mutex};
return add_task(tm, work, priority).id;
}
void task_manager::set_parent(
TaskManager& tm,
TaskID const child_id,
TaskID const parent_id
) {
TOGO_ASSERT(child_id != parent_id, "cannot make task a child of itself");
MutexLock lock{tm._mutex};
Task& child = get_task(tm, child_id);
if (child.id != child_id) {
TOGO_TEST_LOG_DEBUGF(
"set_parent: child does not exist or has completed: %04u %03u\n",
child_id._value >> ID_SHIFT,
child_id._value & INDEX_MASK
);
return;
}
TOGO_ASSERT(child.parent == ID_NULL, "child task already has a parent");
TOGO_ASSERT(parent_id != ID_NULL, "parent ID is invalid");
Task& parent = get_task(tm, parent_id);
TOGO_ASSERT(parent.id == parent_id, "parent task does not exist");
++parent.num_incomplete;
child.parent = parent_id;
}
void task_manager::end_hold(TaskManager& tm, TaskID const id) {
MutexLock lock{tm._mutex};
Task& task = get_task(tm, id);
TOGO_ASSERT(task.id == id, "id is not valid");
queue_task(tm, task);
}
void task_manager::wait(TaskManager& tm, TaskID const id) {
TOGO_DEBUG_ASSERT(id != ID_NULL, "attempted to wait on null ID");
execute_pending(tm, id);
}
} // namespace togo
<commit_msg>task_manager: moved log_test inclusion out of namespace.<commit_after>#line 2 "togo/task_manager.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <togo/config.hpp>
#include <togo/utility.hpp>
#include <togo/assert.hpp>
#include <togo/log.hpp>
#include <togo/array.hpp>
#include <togo/priority_queue.hpp>
#include <togo/thread.hpp>
#include <togo/mutex.hpp>
#include <togo/condvar.hpp>
#include <togo/task_manager.hpp>
#include <cstring>
#include <cstdio>
#undef TOGO_TEST_LOG_ENABLE
#if defined(TOGO_TEST_TASK_MANAGER)
#define TOGO_TEST_LOG_ENABLE
#endif
#include <togo/log_test.hpp>
namespace togo {
namespace {
static constexpr TaskID const ID_NULL{0};
inline bool operator==(TaskID const& x, TaskID const& y) {
return x._value == y._value;
}
inline bool operator!=(TaskID const& x, TaskID const& y) {
return x._value != y._value;
}
inline unsigned task_sort_key(Task const& task) {
// Sort by num_incomplete, then by priority
return (~unsigned{task.num_incomplete} << 16 & 0xFFFF0000) | unsigned{task.priority};
}
bool task_less(Task* const& x, Task* const& y) {
return task_sort_key(*x) < task_sort_key(*y);
}
enum : unsigned {
// 128 tasks
ID_SHIFT = 7,
NUM_TASKS = 1 << ID_SHIFT,
ID_ADD = 1 << ID_SHIFT,
INDEX_MASK = NUM_TASKS - 1,
FLAG_SHUTDOWN = 1 << 0,
};
inline Task& get_task(TaskManager& tm, TaskID const id) {
return tm._tasks[id._value & INDEX_MASK].task;
}
inline bool is_complete(Task const& task, TaskID const expected_id) {
return task.id != expected_id || task.num_incomplete == 0;
}
inline bool is_ready(Task const& task) {
return task.num_incomplete <= 1;
}
inline void free_slot(TaskManager& tm, Task& task) {
TaskSlot& slot = *reinterpret_cast<TaskSlot*>(&task);
unsigned index = slot.id._value & INDEX_MASK;
slot.hole.next = nullptr;
while (index--) {
TaskSlot& slot_before = tm._tasks[index];
if (slot_before.id == ID_NULL) {
slot.hole.next = slot_before.hole.next;
slot_before.hole.next = &slot;
break;
}
}
if (!slot.hole.next) {
// No hole between slot and head
slot.hole.next = tm._first_hole;
tm._first_hole = &slot;
}
slot.id = ID_NULL;
}
inline Task& add_task(
TaskManager& tm,
TaskWork const& work,
u16 const priority
) {
TOGO_ASSERT(tm._num_tasks != NUM_TASKS, "cannot add task to full task manager");
TOGO_DEBUG_ASSERTE(tm._first_hole != nullptr);
TaskSlot& slot = *tm._first_hole;
tm._first_hole = slot.hole.next;
std::memset(&slot.task, 0, sizeof(Task));
slot.task.id._value = tm._id_gen | (&slot - tm._tasks);
slot.task.work = work;
slot.task.priority = priority;
slot.task.num_incomplete = 1;
tm._id_gen = max(tm._id_gen + ID_ADD, u32{ID_ADD});
return slot.task;
}
inline void queue_task(TaskManager& tm, Task& task) {
/*TOGO_TEST_LOG_DEBUGF(
"queue_task: push: %04u %03u @ %04hu / %04hu\n",
task.id._value >> ID_SHIFT,
task.id._value & INDEX_MASK,
task.num_incomplete,
task.priority
);*/
priority_queue::push(tm._queue, &task);
/*#if defined(TOGO_TEST_TASK_MANAGER)
Task* const front = priority_queue::front(tm._queue);
TOGO_TEST_LOG_DEBUGF(
"queue_task: front: %04u %03u @ %04hu / %04hu\n",
front->id._value >> ID_SHIFT,
front->id._value & INDEX_MASK,
front->num_incomplete,
front->priority
);
#endif*/
condvar::signal(tm._work_signal, tm._mutex);
}
inline void complete_task(TaskManager& tm, Task& task) {
// TODO: Reorder each parent in the priority queue
TOGO_TEST_LOG_DEBUGF(
"complete_task : %-32s: %04u %03u @ %04hu / %04hu\n",
thread::name(),
task.id._value >> ID_SHIFT,
task.id._value & INDEX_MASK,
task.num_incomplete,
task.priority
);
task.num_incomplete = 0;
TaskID parent_id = task.parent;
while (parent_id != ID_NULL) {
Task& parent = get_task(tm, parent_id);
--parent.num_incomplete;
parent_id = parent.num_incomplete ? parent.parent : ID_NULL;
}
free_slot(tm, task);
condvar::signal_all(tm._work_signal, tm._mutex);
}
void execute_pending(TaskManager& tm, TaskID const wait_id) {
Task* task = nullptr;
Task const* wait_task = nullptr;
if (wait_id != ID_NULL) {
wait_task = &get_task(tm, wait_id);
}
MutexLock lock{tm._mutex};
while (true) {
if (task) {
complete_task(tm, *task);
task = nullptr;
}
if (wait_task && is_complete(*wait_task, wait_id)) {
return;
} else if (tm._flags & FLAG_SHUTDOWN) {
return;
} else if (
priority_queue::any(tm._queue) &&
is_ready(*priority_queue::front(tm._queue))
) {
task = priority_queue::front(tm._queue);
priority_queue::pop(tm._queue);
TOGO_TEST_LOG_DEBUGF(
"execute_pending: %-32s: %04u %03u @ %04hu / %04hu [take]\n",
thread::name(),
task->id._value >> ID_SHIFT,
task->id._value & INDEX_MASK,
task->num_incomplete,
task->priority
);
// If !task->work.func, the task is empty
if (task->work.func) {
// task->id and task->work should not be modified
// after adding and the task should not be destroyed
// by any other function, so this is free of race
// conditions.
mutex::unlock(tm._mutex);
task->work.func(task->id, task->work.data);
mutex::lock(tm._mutex);
}
continue;
}
condvar::wait(tm._work_signal, lock);
}
}
void* worker_func(void* const tm_void) {
TaskManager& tm = *static_cast<TaskManager*>(tm_void);
TOGO_TEST_LOG_DEBUGF("worker_func: start: %s\n", thread::name());
execute_pending(tm, ID_NULL);
TOGO_TEST_LOG_DEBUGF("worker_func: shutdown: %s\n", thread::name());
return nullptr;
}
} // anonymous namespace
static_assert(
NUM_TASKS == array_extent(&TaskManager::_tasks),
"ID_SHIFT does not fit with the size of TaskManager::_tasks"
);
// class TaskManager implementation
TaskManager::~TaskManager() {
{
MutexLock lock{_mutex};
_flags |= FLAG_SHUTDOWN;
condvar::signal_all(_work_signal, lock);
}
for (Thread* const worker_thread : _workers) {
thread::join(worker_thread);
}
}
TaskManager::TaskManager(unsigned num_workers, Allocator& allocator)
: _tasks()
, _queue(task_less, allocator)
, _workers(allocator)
, _mutex(MutexType::normal)
, _work_signal()
, _first_hole(_tasks)
, _num_tasks(0)
, _flags(0)
, _id_gen(ID_ADD)
{
TaskSlot* const last = _tasks + (NUM_TASKS - 1);
for (TaskSlot* slot = _tasks; slot != last; ++slot) {
slot->hole.next = slot + 1;
}
last->hole.next = nullptr;
priority_queue::reserve(_queue, NUM_TASKS);
if (num_workers) {
array::reserve(_workers, num_workers);
char name[32];
while (num_workers--) {
std::snprintf(name, sizeof(name), "tm-%8p-worker-%u", this, num_workers);
array::push_back(_workers, thread::create(name, this, worker_func, allocator));
}
}
}
// interface task_manager implementation
TaskID task_manager::add(
TaskManager& tm,
TaskWork const& work,
u16 const priority
) {
MutexLock lock{tm._mutex};
Task& task = add_task(tm, work, priority);
queue_task(tm, task);
return task.id;
}
TaskID task_manager::add_hold(
TaskManager& tm,
TaskWork const& work,
u16 const priority
) {
MutexLock lock{tm._mutex};
return add_task(tm, work, priority).id;
}
void task_manager::set_parent(
TaskManager& tm,
TaskID const child_id,
TaskID const parent_id
) {
TOGO_ASSERT(child_id != parent_id, "cannot make task a child of itself");
MutexLock lock{tm._mutex};
Task& child = get_task(tm, child_id);
if (child.id != child_id) {
TOGO_TEST_LOG_DEBUGF(
"set_parent: child does not exist or has completed: %04u %03u\n",
child_id._value >> ID_SHIFT,
child_id._value & INDEX_MASK
);
return;
}
TOGO_ASSERT(child.parent == ID_NULL, "child task already has a parent");
TOGO_ASSERT(parent_id != ID_NULL, "parent ID is invalid");
Task& parent = get_task(tm, parent_id);
TOGO_ASSERT(parent.id == parent_id, "parent task does not exist");
++parent.num_incomplete;
child.parent = parent_id;
}
void task_manager::end_hold(TaskManager& tm, TaskID const id) {
MutexLock lock{tm._mutex};
Task& task = get_task(tm, id);
TOGO_ASSERT(task.id == id, "id is not valid");
queue_task(tm, task);
}
void task_manager::wait(TaskManager& tm, TaskID const id) {
TOGO_DEBUG_ASSERT(id != ID_NULL, "attempted to wait on null ID");
execute_pending(tm, id);
}
} // namespace togo
<|endoftext|>
|
<commit_before>/*
* Copyright 2009 The VOTCA Development Team (http://www.votca.org)
*
* 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 <votca/tools/cubicspline.h>
#include <votca/tools/table.h>
#include <votca/tools/tokenizer.h>
#include <boost/program_options.hpp>
#include <iostream>
#include "version.h"
using namespace std;
namespace po = boost::program_options;
using namespace votca::csg;
using namespace votca::tools;
void help_text()
{
votca::csg::HelpTextHeader("csg_resample");
cout << "Change grid + interval of any sort of table files.\n"
"Mainly called internally by inverse script, can also be\n"
"used to manually prepare input files for coarse-grained\n"
"simulations.\n\n";
}
void check_option(po::options_description &desc, po::variables_map &vm, const string &option)
{
if(!vm.count(option)) {
cout << "csg_resample \n\n";
cout << desc << endl << "parameter " << option << " is not specified\n";
exit(1);
}
}
int main(int argc, char** argv)
{
string in_file, out_file, grid, spfit, comment, boundaries;
CubicSpline spline;
Table in, out, der;
// program options
po::options_description desc("Allowed options");
desc.add_options()
("in", po::value<string>(&in_file), "table to read")
("out", po::value<string>(&out_file), "table to write")
("derivative", po::value<string>(), "table to write")
("grid", po::value<string>(&grid), "new grid spacing (min:step:max)")
("spfit", po::value<string>(&spfit), "specify spline fit grid. if option is not specified, normal spline interpolation is performed")
//("bc", po::)
("comment", po::value<string>(&comment), "store a comment in the output table")
("boundaries", po::value<string>(&boundaries), "(natural|periodic|derivativezero) sets boundary conditions")
("help", "options file for coarse graining");
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
}
catch(po::error err) {
cout << "error parsing command line: " << err.what() << endl;
return -1;
}
// does the user want help?
if (vm.count("help")) {
help_text();
cout << desc << endl;
return 0;
}
check_option(desc, vm, "in");
check_option(desc, vm, "out");
check_option(desc, vm, "grid");
double min, max, step;
{
Tokenizer tok(grid, ":");
vector<string> toks;
tok.ToVector(toks);
if(toks.size()!=3) {
cout << "wrong range format, use min:step:max\n";
return 1;
}
min = boost::lexical_cast<double>(toks[0]);
step = boost::lexical_cast<double>(toks[1]);
max = boost::lexical_cast<double>(toks[2]);
}
in.Load(in_file);
if (vm.count("boundaries")){
if (boundaries=="periodic"){
spline.setBC(CubicSpline::splinePeriodic);
}
else if (boundaries=="derivativezero"){
spline.setBC(CubicSpline::splineDerivativeZero);
}
//default: normal
}
if (vm.count("spfit")) {
Tokenizer tok(spfit, ":");
vector<string> toks;
tok.ToVector(toks);
if(toks.size()!=3) {
cout << "wrong range format in spfit, use min:step:max\n";
return 1;
}
double sp_min, sp_max, sp_step;
sp_min = boost::lexical_cast<double>(toks[0]);
sp_step = boost::lexical_cast<double>(toks[1]);
sp_max = boost::lexical_cast<double>(toks[2]);
cout << "doing spline fit " << sp_min << ":" << sp_step << ":" << sp_max << endl;
spline.GenerateGrid(sp_min, sp_max, sp_step);
spline.Fit(in.x(), in.y());
} else {
spline.Interpolate(in.x(), in.y());
}
out.GenerateGridSpacing(min, max, step);
spline.Calculate(out.x(), out.y());
//store a comment line
if (vm.count("comment")){
out.set_comment(comment);
}
out.y() = out.y();
out.flags() = ub::scalar_vector<double>(out.flags().size(), 'o');
int i=0;
for(i=0; out.x(i) < in.x(0) && i<out.size(); ++i);
int j=0;
for(;i < out.size(); ++i) {
for(; j < in.size(); ++j)
if(in.x(j) >= out.x(i))
break;
if(in.size() == j) break;
out.flags(i) = in.flags(j);
}
out.Save(out_file);
if (vm.count("derivative")) {
der.GenerateGridSpacing(min, max, step);
der.flags() = ub::scalar_vector<double>(der.flags().size(), 'o');
spline.CalculateDerivative(der.x(), der.y());
der.Save(vm["derivative"].as<string>());
}
return 0;
}
<commit_msg>Fixes issue 21<commit_after>/*
* Copyright 2009 The VOTCA Development Team (http://www.votca.org)
*
* 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 <votca/tools/cubicspline.h>
#include <votca/tools/table.h>
#include <votca/tools/tokenizer.h>
#include <boost/program_options.hpp>
#include <iostream>
#include "version.h"
using namespace std;
namespace po = boost::program_options;
using namespace votca::csg;
using namespace votca::tools;
void help_text()
{
votca::csg::HelpTextHeader("csg_resample");
cout << "Change grid + interval of any sort of table files.\n"
"Mainly called internally by inverse script, can also be\n"
"used to manually prepare input files for coarse-grained\n"
"simulations.\n\n";
}
void check_option(po::options_description &desc, po::variables_map &vm, const string &option)
{
if(!vm.count(option)) {
cout << "csg_resample \n\n";
cout << desc << endl << "parameter " << option << " is not specified\n";
exit(1);
}
}
int main(int argc, char** argv)
{
string in_file, out_file, grid, spfit, comment, boundaries;
CubicSpline spline;
Table in, out, der;
// program options
po::options_description desc("Allowed options");
desc.add_options()
("in", po::value<string>(&in_file), "table to read")
("out", po::value<string>(&out_file), "table to write")
("derivative", po::value<string>(), "table to write")
("grid", po::value<string>(&grid), "new grid spacing (min:step:max)")
("spfit", po::value<string>(&spfit), "specify spline fit grid. if option is not specified, normal spline interpolation is performed")
//("bc", po::)
("comment", po::value<string>(&comment), "store a comment in the output table")
("boundaries", po::value<string>(&boundaries), "(natural|periodic|derivativezero) sets boundary conditions")
("help", "options file for coarse graining");
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
}
catch(po::error err) {
cout << "error parsing command line: " << err.what() << endl;
return -1;
}
// does the user want help?
if (vm.count("help")) {
help_text();
cout << desc << endl;
return 0;
}
check_option(desc, vm, "in");
check_option(desc, vm, "out");
check_option(desc, vm, "grid");
double min, max, step;
{
Tokenizer tok(grid, ":");
vector<string> toks;
tok.ToVector(toks);
if(toks.size()!=3) {
cout << "wrong range format, use min:step:max\n";
return 1;
}
min = boost::lexical_cast<double>(toks[0]);
step = boost::lexical_cast<double>(toks[1]);
max = boost::lexical_cast<double>(toks[2]);
}
in.Load(in_file);
if (vm.count("boundaries")){
if (boundaries=="periodic"){
spline.setBC(CubicSpline::splinePeriodic);
}
else if (boundaries=="derivativezero"){
spline.setBC(CubicSpline::splineDerivativeZero);
}
//default: normal
}
if (vm.count("spfit")) {
Tokenizer tok(spfit, ":");
vector<string> toks;
tok.ToVector(toks);
if(toks.size()!=3) {
cout << "wrong range format in spfit, use min:step:max\n";
return 1;
}
double sp_min, sp_max, sp_step;
sp_min = boost::lexical_cast<double>(toks[0]);
sp_step = boost::lexical_cast<double>(toks[1]);
sp_max = boost::lexical_cast<double>(toks[2]);
cout << "doing spline fit " << sp_min << ":" << sp_step << ":" << sp_max << endl;
spline.GenerateGrid(sp_min, sp_max, sp_step);
spline.Fit(in.x(), in.y());
} else {
spline.Interpolate(in.x(), in.y());
}
out.GenerateGridSpacing(min, max, step);
spline.Calculate(out.x(), out.y());
//store a comment line
if (vm.count("comment")){
out.set_comment(comment);
}
out.y() = out.y();
out.flags() = ub::scalar_vector<double>(out.flags().size(), 'o');
int i=0;
for(i=0; out.x(i) < in.x(0) && i<out.size(); ++i);
int j=0;
for(;i < out.size(); ++i) {
for(; j < in.size(); ++j)
if(in.x(j) >= out.x(i) || fabs(in.x(j)-out.x(i) ) < 1e-12) // fix for precison errors
break;
if(in.size() == j) break;
out.flags(i) = in.flags(j);
}
out.Save(out_file);
if (vm.count("derivative")) {
der.GenerateGridSpacing(min, max, step);
der.flags() = ub::scalar_vector<double>(der.flags().size(), 'o');
spline.CalculateDerivative(der.x(), der.y());
der.Save(vm["derivative"].as<string>());
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "LoadingState.h"
#include "Input.h"
#include "Qor.h"
#include "TileMap.h"
#include "Sprite.h"
#include "kit/log/log.h"
#include <glm/glm.hpp>
#include <cstdlib>
#include "Light.h"
using namespace std;
using namespace glm;
LoadingState :: LoadingState(Qor* qor):
m_pQor(qor),
m_pWindow(qor->window()),
m_pInput(qor->input()),
m_pRoot(std::make_shared<Node>()),
m_pCamera(make_shared<Camera>(qor->resources(), qor->window())),
m_pPipeline(qor->pipeline())
{
m_bFade = m_pQor->args().value_or("no_loading_fade", "").empty();
string bg = m_pQor->args().value_or("loading_bg", "");
string shader = m_pQor->args().value_or("loading_shader", "");
if(not shader.empty()){
m_Shader = m_pPipeline->load_shaders({shader});
m_pPipeline->override_shader(PassType::NORMAL, m_Shader);
}
if(not bg.empty()){
m_BG = Color(bg);
m_bFade = false;
}else{
if(m_bFade)
m_BG = Color::white();
else
m_BG = Color::black();
}
m_pRoot->add(m_pCamera);
vec2 win = vec2(m_pWindow->size().x, m_pWindow->size().y);
const float icon_size = win.x / 24.0f;
const float half_icon_size = icon_size / 2.0f;
float sw = m_pQor->window()->size().x;
float sh = m_pQor->window()->size().y;
if(m_pQor->exists("loading.png"))
{
auto bg = make_shared<Mesh>(
make_shared<MeshGeometry>(Prefab::quad(
vec2(0.0f, 0.0f),
vec2(sw, sh)
)),
vector<shared_ptr<IMeshModifier>>{
make_shared<Wrap>(Prefab::quad_wrap())
},
make_shared<MeshMaterial>(
m_pQor->resources()->cache_cast<ITexture>("loading.png")
)
);
bg->position(vec3(0.0f,0.0f,-1.0f));
m_pRoot->add(bg);
}
if(m_pQor->exists("logo.png"))
{
m_pLogo = make_shared<Mesh>(
make_shared<MeshGeometry>(Prefab::quad(
-vec2(m_pWindow->size().y, m_pWindow->size().y)/4.0f,
vec2(m_pWindow->size().y, m_pWindow->size().y)/4.0f
)),
vector<shared_ptr<IMeshModifier>>{
make_shared<Wrap>(Prefab::quad_wrap())
},
make_shared<MeshMaterial>(
m_pQor->resources()->cache_cast<ITexture>("logo.png")
)
);
m_pLogo->move(vec3(
m_pWindow->center().x,
m_pWindow->center().y,
0.0f
));
m_pRoot->add(m_pLogo);
}
//bg->position(vec3(0.0f,0.0f,-2.0f));
//m_pLogo->add_modifier(make_shared<Wrap>(Prefab::quad_wrap()));
//m_pLogo->material(make_shared<MeshMaterial>(
// m_pQor->resources()->cache_cast<ITexture>(
// "logo.png"
// )
//));
m_pWaitIcon = make_shared<Mesh>(
make_shared<MeshGeometry>(
Prefab::quad(
vec2(-half_icon_size),
vec2(half_icon_size)
)
)
);
m_pWaitIcon->position(vec3(
//win.x - icon_size,
//icon_size,
m_pWindow->center().x,
m_pWindow->size().y * 1.0f/8.0f,
0.0f
));
m_pWaitIcon->add_modifier(make_shared<Wrap>(Prefab::quad_wrap()));
m_pWaitIcon->material(make_shared<MeshMaterial>(
m_pQor->resources()->cache_cast<ITexture>(
"load-c.png"
)
));
m_pRoot->add(m_pWaitIcon);
// loading screen style
if(m_bFade)
m_pPipeline->bg_color(m_BG);
else
m_pPipeline->bg_color(m_BG);
//fade_to(Color::white(), m_FadeTime);
m_Fade.frame(Frame<Color>(
Color::white(),
Freq::Time::seconds(0.5f),
INTERPOLATE(out_sine<Color>)
));
//m_Fade.frame(Frame<Color>(
// Color::white(), // wait a while
// Freq::Time::seconds(1.0f),
// INTERPOLATE(Color, out_sine)
//));
#ifndef QOR_NO_AUDIO
try{
Log::Silencer ls;
m_pMusic = make_shared<Sound>("loading.ogg", m_pQor->resources());
m_pRoot->add(m_pMusic);
m_pMusic->play();
}catch(...){}
#endif
}
LoadingState :: ~LoadingState()
{
m_pPipeline->override_shader(PassType::NORMAL, (unsigned)PassType::NONE);
}
//void LoadingState :: fade_to(const Color& c, float t)
//{
// //m_Fade.set(Freq::Time::seconds(t), ~c, c);
//}
void LoadingState :: logic(Freq::Time t)
{
Actuation::logic(t);
m_pCamera->ortho(true);
m_pPipeline->winding(false);
m_pPipeline->blend(false);
if(m_pInput->escape())
m_pQor->quit();
m_Fade.logic(t);
m_pRoot->logic(t);
if(not Headless::enabled())
{
m_pPipeline->shader(1)->use();
int fade = m_pPipeline->shader(1)->uniform("Brightness");
if(fade >= 0)
m_pPipeline->shader(1)->uniform(
fade,
m_Fade.get().vec3()
);
}
m_pQor->do_tasks();
// Loading screen fade style?
if(m_pLogo)
if(m_bFade){
m_pPipeline->bg_color(m_Fade.get());
m_pLogo->reset_orientation();
m_pLogo->scale(m_Fade.get().r());
m_pLogo->pend();
}
#ifndef QOR_NO_AUDIO
if(m_pMusic && m_pMusic->source()) {
//m_pMusic->source()->gain = m_Fade.get().r();
//m_pMusic->source()->refresh();
}
#endif
*m_pWaitIcon->matrix() *= rotate(
t.s() * float(K_TAU),
vec3(0.0f, 0.0f, -1.0f)
);
m_pWaitIcon->position(vec3(
m_pWaitIcon->position().x,
(m_pWindow->size().y * 1.0f/8.0f) * m_Fade.get().r(),
m_pWaitIcon->position().z
));
m_pWaitIcon->pend();
if(m_pQor->state(1)->finished_loading()) {
if(m_Fade.elapsed()) {
if(m_Fade.get() == Color::white())
{
m_Fade.frame(Frame<Color>(
Color::black(),
Freq::Time::seconds(0.5f),
INTERPOLATE(out_sine<Color>)
));
}
else
{
if(not Headless::enabled())
{
m_pPipeline->shader(1)->use();
int u = m_pPipeline->shader(1)->uniform("Brightness");
if(u >= 0)
m_pPipeline->shader(1)->uniform(
u, Color::white().vec3()
);
}
m_pQor->pop_state();
}
}
}
}
void LoadingState :: render() const
{
m_pPipeline->render(m_pRoot.get(), m_pCamera.get());
}
<commit_msg>loading screens w/o fade no longer fade brightness uniform<commit_after>#include "LoadingState.h"
#include "Input.h"
#include "Qor.h"
#include "TileMap.h"
#include "Sprite.h"
#include "kit/log/log.h"
#include <glm/glm.hpp>
#include <cstdlib>
#include "Light.h"
using namespace std;
using namespace glm;
LoadingState :: LoadingState(Qor* qor):
m_pQor(qor),
m_pWindow(qor->window()),
m_pInput(qor->input()),
m_pRoot(std::make_shared<Node>()),
m_pCamera(make_shared<Camera>(qor->resources(), qor->window())),
m_pPipeline(qor->pipeline())
{
m_bFade = m_pQor->args().value_or("no_loading_fade", "").empty();
string bg = m_pQor->args().value_or("loading_bg", "");
string shader = m_pQor->args().value_or("loading_shader", "");
if(not shader.empty()){
m_Shader = m_pPipeline->load_shaders({shader});
m_pPipeline->override_shader(PassType::NORMAL, m_Shader);
}
if(not bg.empty()){
m_BG = Color(bg);
m_bFade = false;
}else{
if(m_bFade)
m_BG = Color::white();
else
m_BG = Color::black();
}
if(!m_bFade)
{
m_pPipeline->shader(1)->use();
int fade = m_pPipeline->shader(1)->uniform("Brightness");
m_pPipeline->shader(1)->uniform(
fade, Color::white().vec3()
);
}
m_pRoot->add(m_pCamera);
vec2 win = vec2(m_pWindow->size().x, m_pWindow->size().y);
const float icon_size = win.x / 24.0f;
const float half_icon_size = icon_size / 2.0f;
float sw = m_pQor->window()->size().x;
float sh = m_pQor->window()->size().y;
if(m_pQor->exists("loading.png"))
{
auto bg = make_shared<Mesh>(
make_shared<MeshGeometry>(Prefab::quad(
vec2(0.0f, 0.0f),
vec2(sw, sh)
)),
vector<shared_ptr<IMeshModifier>>{
make_shared<Wrap>(Prefab::quad_wrap())
},
make_shared<MeshMaterial>(
m_pQor->resources()->cache_cast<ITexture>("loading.png")
)
);
bg->position(vec3(0.0f,0.0f,-1.0f));
m_pRoot->add(bg);
}
if(m_pQor->exists("logo.png"))
{
m_pLogo = make_shared<Mesh>(
make_shared<MeshGeometry>(Prefab::quad(
-vec2(m_pWindow->size().y, m_pWindow->size().y)/4.0f,
vec2(m_pWindow->size().y, m_pWindow->size().y)/4.0f
)),
vector<shared_ptr<IMeshModifier>>{
make_shared<Wrap>(Prefab::quad_wrap())
},
make_shared<MeshMaterial>(
m_pQor->resources()->cache_cast<ITexture>("logo.png")
)
);
m_pLogo->move(vec3(
m_pWindow->center().x,
m_pWindow->center().y,
0.0f
));
m_pRoot->add(m_pLogo);
}
//bg->position(vec3(0.0f,0.0f,-2.0f));
//m_pLogo->add_modifier(make_shared<Wrap>(Prefab::quad_wrap()));
//m_pLogo->material(make_shared<MeshMaterial>(
// m_pQor->resources()->cache_cast<ITexture>(
// "logo.png"
// )
//));
m_pWaitIcon = make_shared<Mesh>(
make_shared<MeshGeometry>(
Prefab::quad(
vec2(-half_icon_size),
vec2(half_icon_size)
)
)
);
m_pWaitIcon->position(vec3(
//win.x - icon_size,
//icon_size,
m_pWindow->center().x,
m_pWindow->size().y * 1.0f/8.0f,
0.0f
));
m_pWaitIcon->add_modifier(make_shared<Wrap>(Prefab::quad_wrap()));
m_pWaitIcon->material(make_shared<MeshMaterial>(
m_pQor->resources()->cache_cast<ITexture>(
"load-c.png"
)
));
m_pRoot->add(m_pWaitIcon);
// loading screen style
if(m_bFade)
m_pPipeline->bg_color(m_BG);
else
m_pPipeline->bg_color(m_BG);
//fade_to(Color::white(), m_FadeTime);
m_Fade.frame(Frame<Color>(
Color::white(),
Freq::Time::seconds(0.5f),
INTERPOLATE(out_sine<Color>)
));
//m_Fade.frame(Frame<Color>(
// Color::white(), // wait a while
// Freq::Time::seconds(1.0f),
// INTERPOLATE(Color, out_sine)
//));
#ifndef QOR_NO_AUDIO
try{
Log::Silencer ls;
m_pMusic = make_shared<Sound>("loading.ogg", m_pQor->resources());
m_pRoot->add(m_pMusic);
m_pMusic->play();
}catch(...){}
#endif
}
LoadingState :: ~LoadingState()
{
m_pPipeline->override_shader(PassType::NORMAL, (unsigned)PassType::NONE);
}
//void LoadingState :: fade_to(const Color& c, float t)
//{
// //m_Fade.set(Freq::Time::seconds(t), ~c, c);
//}
void LoadingState :: logic(Freq::Time t)
{
Actuation::logic(t);
m_pCamera->ortho(true);
m_pPipeline->winding(false);
m_pPipeline->blend(false);
if(m_pInput->escape())
m_pQor->quit();
m_Fade.logic(t);
m_pRoot->logic(t);
if(not Headless::enabled())
{
if(m_bFade)
{
m_pPipeline->shader(1)->use();
int fade = m_pPipeline->shader(1)->uniform("Brightness");
if(fade >= 0)
m_pPipeline->shader(1)->uniform(
fade,
m_Fade.get().vec3()
);
}
}
m_pQor->do_tasks();
// Loading screen fade style?
if(m_pLogo)
if(m_bFade){
m_pPipeline->bg_color(m_Fade.get());
m_pLogo->reset_orientation();
m_pLogo->scale(m_Fade.get().r());
m_pLogo->pend();
}
#ifndef QOR_NO_AUDIO
if(m_pMusic && m_pMusic->source()) {
//m_pMusic->source()->gain = m_Fade.get().r();
//m_pMusic->source()->refresh();
}
#endif
*m_pWaitIcon->matrix() *= rotate(
t.s() * float(K_TAU),
vec3(0.0f, 0.0f, -1.0f)
);
m_pWaitIcon->position(vec3(
m_pWaitIcon->position().x,
(m_pWindow->size().y * 1.0f/8.0f) * m_Fade.get().r(),
m_pWaitIcon->position().z
));
m_pWaitIcon->pend();
if(m_pQor->state(1)->finished_loading()) {
if(m_Fade.elapsed()) {
if(m_Fade.get() == Color::white())
{
m_Fade.frame(Frame<Color>(
Color::black(),
Freq::Time::seconds(0.5f),
INTERPOLATE(out_sine<Color>)
));
}
else
{
if(not Headless::enabled())
{
if(m_bFade)
{
m_pPipeline->shader(1)->use();
int u = m_pPipeline->shader(1)->uniform("Brightness");
if(u >= 0)
m_pPipeline->shader(1)->uniform(
u, Color::white().vec3()
);
}
}
m_pQor->pop_state();
}
}
}
}
void LoadingState :: render() const
{
m_pPipeline->render(m_pRoot.get(), m_pCamera.get());
}
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////
// = NMatrix
//
// A linear algebra library for scientific computation in Ruby.
// NMatrix is part of SciRuby.
//
// NMatrix was originally inspired by and derived from NArray, by
// Masahiro Tanaka: http://narray.rubyforge.org
//
// == Copyright Information
//
// SciRuby is Copyright (c) 2010 - 2012, Ruby Science Foundation
// NMatrix is Copyright (c) 2012, Ruby Science Foundation
//
// Please see LICENSE.txt for additional copyright notices.
//
// == Contributing
//
// By contributing source code to SciRuby, you agree to be bound by
// our Contributor Agreement:
//
// * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement
//
// == dense_templates.cpp
//
// Templates for dense n-dimensional matrix storage.
/*
* Standard Includes
*/
/*
* Project Includes
*/
#include "data/data.h"
#include "dense.h"
/*
* Macros
*/
/*
* Global Variables
*/
/*
* Forward Declarations
*/
template <typename DType, typename NewDType>
DENSE_STORAGE* dense_storage_cast_copy_template(const DENSE_STORAGE* rhs, dtype_t new_dtype);
template <typename LDType, typename RDType>
bool dense_storage_eqeq_template(const DENSE_STORAGE* left, const DENSE_STORAGE* right);
template <typename DType>
bool dense_storage_is_hermitian_template(const DENSE_STORAGE* mat, int lda);
template <typename DType>
bool dense_storage_is_symmetric_template(const DENSE_STORAGE* mat, int lda);
/*
* Functions
*/
/////////////////////////
// C Wrapper Functions //
/////////////////////////
extern "C" {
///////////
// Tests //
///////////
/*
* Do these two dense matrices have the same contents?
*/
bool dense_storage_eqeq(const DENSE_STORAGE* left, const DENSE_STORAGE* right) {
LR_DTYPE_TEMPLATE_TABLE(dense_storage_eqeq_template, bool, const DENSE_STORAGE*, const DENSE_STORAGE*);
return ttable[left->dtype][right->dtype](left, right);
}
/*
* Test to see if the matrix is Hermitian. If the matrix does not have a
* dtype of Complex64 or Complex128 this is the same as testing for symmetry.
*/
bool dense_storage_is_hermitian(const DENSE_STORAGE* mat, int lda) {
if (mat->dtype == COMPLEX64) {
return dense_storage_is_hermitian_template<Complex64>(mat, lda);
} else if (mat->dtype == COMPLEX128) {
return dense_storage_is_hermitian_template<Complex128>(mat, lda);
} else {
return dense_storage_is_symmetric(mat, lda);
}
}
/*
* Is this dense matrix symmetric about the diagonal?
*/
bool dense_storage_is_symmetric(const DENSE_STORAGE* mat, int lda) {
DTYPE_TEMPLATE_TABLE(dense_storage_is_symmetric_template, bool, const DENSE_STORAGE*, int);
return ttable[mat->dtype](mat, lda);
}
/////////////////////////
// Casting and Copying //
/////////////////////////
/*
* Documentation goes here.
*/
DENSE_STORAGE* dense_storage_cast_copy(const DENSE_STORAGE* rhs, dtype_t new_dtype) {
LR_DTYPE_TEMPLATE_TABLE(dense_storage_cast_copy_template, DENSE_STORAGE*, const DENSE_STORAGE*, dtype_t);
return ttable[new_dtype][rhs->dtype](rhs, new_dtype);
}
}
/////////////////////////
// Templated Functions //
/////////////////////////
template <typename DType, typename NewDType>
DENSE_STORAGE* dense_storage_cast_copy_template(const DENSE_STORAGE* rhs, dtype_t new_dtype) {
size_t count = storage_count_max_elements(rhs->rank, rhs->shape), p;
size_t* shape = ALLOC_N(size_t, rhs->rank);
DType* rhs_els = (DType*)rhs->elements;
NewDType* lhs_els;
DENSE_STORAGE* lhs;
if (!shape) {
return NULL;
}
// Copy shape array.
for (p = rhs->rank; p-- > 0;) {
shape[p] = rhs->shape[p];
}
lhs = dense_storage_create(new_dtype, shape, rhs->rank, NULL, 0);
lhs_els = (NewDType*)lhs->elements;
// Ensure that allocation worked before copying.
if (lhs && count) {
if (lhs->dtype == rhs->dtype) {
memcpy(lhs->elements, rhs->elements, DTYPE_SIZES[rhs->dtype] * count);
} else {
while (count-- > 0) {
lhs_els[count] = rhs_els[count];
}
}
}
return lhs;
}
template <typename LDType, typename RDType>
bool dense_storage_eqeq_template(const DENSE_STORAGE* left, const DENSE_STORAGE* right) {
int index;
LDType* left_els = (LDType*)left->elements;
RDType* right_els = (RDType*)right->elements;
for (index = storage_count_max_elements(left->rank, left->shape); index-- > 0;) {
if (left_els[index] != right_els[index]) {
return false;
}
}
return true;
}
template <typename DType>
bool dense_storage_is_hermitian_template(const DENSE_STORAGE* mat, int lda) {
unsigned int i, j;
register DType complex_conj;
const DType* els = (DType*) mat->elements;
for (i = mat->shape[0]; i-- > 0;) {
for (j = i + 1; j < mat->shape[1]; ++j) {
complex_conj = els[j*lda + 1];
complex_conj.i = -complex_conj.i;
if (els[i*lda+j] != complex_conj) {
return false;
}
}
}
return true;
}
template <typename DType>
bool dense_storage_is_symmetric_template(const DENSE_STORAGE* mat, int lda) {
unsigned int i, j;
const DType* els = (DType*) mat->elements;
for (i = mat->shape[0]; i-- > 0;) {
for (j = i + 1; j < mat->shape[1]; ++j) {
if (els[i*lda+j] != els[j*lda+i]) {
return false;
}
}
}
return true;
}
<commit_msg>Added some TODO notes to dense_templates.<commit_after>/////////////////////////////////////////////////////////////////////
// = NMatrix
//
// A linear algebra library for scientific computation in Ruby.
// NMatrix is part of SciRuby.
//
// NMatrix was originally inspired by and derived from NArray, by
// Masahiro Tanaka: http://narray.rubyforge.org
//
// == Copyright Information
//
// SciRuby is Copyright (c) 2010 - 2012, Ruby Science Foundation
// NMatrix is Copyright (c) 2012, Ruby Science Foundation
//
// Please see LICENSE.txt for additional copyright notices.
//
// == Contributing
//
// By contributing source code to SciRuby, you agree to be bound by
// our Contributor Agreement:
//
// * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement
//
// == dense_templates.cpp
//
// Templates for dense n-dimensional matrix storage.
/*
* Standard Includes
*/
/*
* Project Includes
*/
#include "data/data.h"
#include "dense.h"
/*
* Macros
*/
/*
* Global Variables
*/
/*
* Forward Declarations
*/
template <typename DType, typename NewDType>
DENSE_STORAGE* dense_storage_cast_copy_template(const DENSE_STORAGE* rhs, dtype_t new_dtype);
template <typename LDType, typename RDType>
bool dense_storage_eqeq_template(const DENSE_STORAGE* left, const DENSE_STORAGE* right);
template <typename DType>
bool dense_storage_is_hermitian_template(const DENSE_STORAGE* mat, int lda);
template <typename DType>
bool dense_storage_is_symmetric_template(const DENSE_STORAGE* mat, int lda);
/*
* Functions
*/
/////////////////////////
// C Wrapper Functions //
/////////////////////////
extern "C" {
///////////
// Tests //
///////////
/*
* Do these two dense matrices have the same contents?
*
* TODO: Test the shape of the two matrices.
* TODO: See if using memcmp is faster when the left- and right-hand matrices
* have the same dtype.
*/
bool dense_storage_eqeq(const DENSE_STORAGE* left, const DENSE_STORAGE* right) {
LR_DTYPE_TEMPLATE_TABLE(dense_storage_eqeq_template, bool, const DENSE_STORAGE*, const DENSE_STORAGE*);
return ttable[left->dtype][right->dtype](left, right);
}
/*
* Test to see if the matrix is Hermitian. If the matrix does not have a
* dtype of Complex64 or Complex128 this is the same as testing for symmetry.
*/
bool dense_storage_is_hermitian(const DENSE_STORAGE* mat, int lda) {
if (mat->dtype == COMPLEX64) {
return dense_storage_is_hermitian_template<Complex64>(mat, lda);
} else if (mat->dtype == COMPLEX128) {
return dense_storage_is_hermitian_template<Complex128>(mat, lda);
} else {
return dense_storage_is_symmetric(mat, lda);
}
}
/*
* Is this dense matrix symmetric about the diagonal?
*/
bool dense_storage_is_symmetric(const DENSE_STORAGE* mat, int lda) {
DTYPE_TEMPLATE_TABLE(dense_storage_is_symmetric_template, bool, const DENSE_STORAGE*, int);
return ttable[mat->dtype](mat, lda);
}
/////////////////////////
// Casting and Copying //
/////////////////////////
/*
* Documentation goes here.
*/
DENSE_STORAGE* dense_storage_cast_copy(const DENSE_STORAGE* rhs, dtype_t new_dtype) {
LR_DTYPE_TEMPLATE_TABLE(dense_storage_cast_copy_template, DENSE_STORAGE*, const DENSE_STORAGE*, dtype_t);
return ttable[new_dtype][rhs->dtype](rhs, new_dtype);
}
}
/////////////////////////
// Templated Functions //
/////////////////////////
template <typename DType, typename NewDType>
DENSE_STORAGE* dense_storage_cast_copy_template(const DENSE_STORAGE* rhs, dtype_t new_dtype) {
size_t count = storage_count_max_elements(rhs->rank, rhs->shape), p;
size_t* shape = ALLOC_N(size_t, rhs->rank);
DType* rhs_els = (DType*)rhs->elements;
NewDType* lhs_els;
DENSE_STORAGE* lhs;
if (!shape) {
return NULL;
}
// Copy shape array.
for (p = rhs->rank; p-- > 0;) {
shape[p] = rhs->shape[p];
}
lhs = dense_storage_create(new_dtype, shape, rhs->rank, NULL, 0);
lhs_els = (NewDType*)lhs->elements;
// Ensure that allocation worked before copying.
if (lhs && count) {
if (lhs->dtype == rhs->dtype) {
memcpy(lhs->elements, rhs->elements, DTYPE_SIZES[rhs->dtype] * count);
} else {
while (count-- > 0) {
lhs_els[count] = rhs_els[count];
}
}
}
return lhs;
}
template <typename LDType, typename RDType>
bool dense_storage_eqeq_template(const DENSE_STORAGE* left, const DENSE_STORAGE* right) {
int index;
LDType* left_els = (LDType*)left->elements;
RDType* right_els = (RDType*)right->elements;
for (index = storage_count_max_elements(left->rank, left->shape); index-- > 0;) {
if (left_els[index] != right_els[index]) {
return false;
}
}
return true;
}
template <typename DType>
bool dense_storage_is_hermitian_template(const DENSE_STORAGE* mat, int lda) {
unsigned int i, j;
register DType complex_conj;
const DType* els = (DType*) mat->elements;
for (i = mat->shape[0]; i-- > 0;) {
for (j = i + 1; j < mat->shape[1]; ++j) {
complex_conj = els[j*lda + 1];
complex_conj.i = -complex_conj.i;
if (els[i*lda+j] != complex_conj) {
return false;
}
}
}
return true;
}
template <typename DType>
bool dense_storage_is_symmetric_template(const DENSE_STORAGE* mat, int lda) {
unsigned int i, j;
const DType* els = (DType*) mat->elements;
for (i = mat->shape[0]; i-- > 0;) {
for (j = i + 1; j < mat->shape[1]; ++j) {
if (els[i*lda+j] != els[j*lda+i]) {
return false;
}
}
}
return true;
}
<|endoftext|>
|
<commit_before>// Copyright 2018 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "XcbSurfaceKHR.hpp"
#include "libXCB.hpp"
#include "Vulkan/VkDeviceMemory.hpp"
#include "Vulkan/VkImage.hpp"
#include <memory>
namespace vk {
bool getWindowSizeAndDepth(xcb_connection_t *connection, xcb_window_t window, VkExtent2D *windowExtent, int *depth)
{
auto cookie = libXCB->xcb_get_geometry(connection, window);
if(auto *geom = libXCB->xcb_get_geometry_reply(connection, cookie, nullptr))
{
windowExtent->width = static_cast<uint32_t>(geom->width);
windowExtent->height = static_cast<uint32_t>(geom->height);
*depth = static_cast<int>(geom->depth);
free(geom);
return true;
}
return false;
}
bool XcbSurfaceKHR::isSupported()
{
return libXCB.isPresent();
}
XcbSurfaceKHR::XcbSurfaceKHR(const VkXcbSurfaceCreateInfoKHR *pCreateInfo, void *mem)
: connection(pCreateInfo->connection)
, window(pCreateInfo->window)
{
ASSERT(isSupported());
}
void XcbSurfaceKHR::destroySurface(const VkAllocationCallbacks *pAllocator)
{
}
size_t XcbSurfaceKHR::ComputeRequiredAllocationSize(const VkXcbSurfaceCreateInfoKHR *pCreateInfo)
{
return 0;
}
VkResult XcbSurfaceKHR::getSurfaceCapabilities(VkSurfaceCapabilitiesKHR *pSurfaceCapabilities) const
{
setCommonSurfaceCapabilities(pSurfaceCapabilities);
VkExtent2D extent;
int depth;
if(!getWindowSizeAndDepth(connection, window, &extent, &depth))
{
return VK_ERROR_SURFACE_LOST_KHR;
}
pSurfaceCapabilities->currentExtent = extent;
pSurfaceCapabilities->minImageExtent = extent;
pSurfaceCapabilities->maxImageExtent = extent;
return VK_SUCCESS;
}
void XcbSurfaceKHR::attachImage(PresentImage *image)
{
auto gc = libXCB->xcb_generate_id(connection);
uint32_t values[2] = { 0, 0xffffffff };
libXCB->xcb_create_gc(connection, gc, window, XCB_GC_FOREGROUND | XCB_GC_BACKGROUND, values);
graphicsContexts[image] = gc;
}
void XcbSurfaceKHR::detachImage(PresentImage *image)
{
auto it = graphicsContexts.find(image);
if(it != graphicsContexts.end())
{
libXCB->xcb_free_gc(connection, it->second);
graphicsContexts.erase(it);
}
}
VkResult XcbSurfaceKHR::present(PresentImage *image)
{
auto it = graphicsContexts.find(image);
if(it != graphicsContexts.end())
{
VkExtent2D windowExtent;
int depth;
if(!getWindowSizeAndDepth(connection, window, &windowExtent, &depth))
{
return VK_ERROR_SURFACE_LOST_KHR;
}
const VkExtent3D &extent = image->getImage()->getExtent();
if(windowExtent.width != extent.width || windowExtent.height != extent.height)
{
return VK_ERROR_OUT_OF_DATE_KHR;
}
// TODO: Convert image if not RGB888.
int stride = image->getImage()->rowPitchBytes(VK_IMAGE_ASPECT_COLOR_BIT, 0);
auto buffer = reinterpret_cast<uint8_t *>(image->getImageMemory()->getOffsetPointer(0));
size_t bufferSize = extent.height * stride;
libXCB->xcb_put_image(
connection,
XCB_IMAGE_FORMAT_Z_PIXMAP,
window,
it->second,
extent.width,
extent.height,
0, 0, // dst x, y
0, // left_pad
depth,
bufferSize, // data_len
buffer // data
);
libXCB->xcb_flush(connection);
}
return VK_SUCCESS;
}
} // namespace vk<commit_msg>Fix using XCB with odd width<commit_after>// Copyright 2018 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "XcbSurfaceKHR.hpp"
#include "libXCB.hpp"
#include "Vulkan/VkDeviceMemory.hpp"
#include "Vulkan/VkImage.hpp"
#include <memory>
namespace vk {
bool getWindowSizeAndDepth(xcb_connection_t *connection, xcb_window_t window, VkExtent2D *windowExtent, int *depth)
{
auto cookie = libXCB->xcb_get_geometry(connection, window);
if(auto *geom = libXCB->xcb_get_geometry_reply(connection, cookie, nullptr))
{
windowExtent->width = static_cast<uint32_t>(geom->width);
windowExtent->height = static_cast<uint32_t>(geom->height);
*depth = static_cast<int>(geom->depth);
free(geom);
return true;
}
return false;
}
bool XcbSurfaceKHR::isSupported()
{
return libXCB.isPresent();
}
XcbSurfaceKHR::XcbSurfaceKHR(const VkXcbSurfaceCreateInfoKHR *pCreateInfo, void *mem)
: connection(pCreateInfo->connection)
, window(pCreateInfo->window)
{
ASSERT(isSupported());
}
void XcbSurfaceKHR::destroySurface(const VkAllocationCallbacks *pAllocator)
{
}
size_t XcbSurfaceKHR::ComputeRequiredAllocationSize(const VkXcbSurfaceCreateInfoKHR *pCreateInfo)
{
return 0;
}
VkResult XcbSurfaceKHR::getSurfaceCapabilities(VkSurfaceCapabilitiesKHR *pSurfaceCapabilities) const
{
setCommonSurfaceCapabilities(pSurfaceCapabilities);
VkExtent2D extent;
int depth;
if(!getWindowSizeAndDepth(connection, window, &extent, &depth))
{
return VK_ERROR_SURFACE_LOST_KHR;
}
pSurfaceCapabilities->currentExtent = extent;
pSurfaceCapabilities->minImageExtent = extent;
pSurfaceCapabilities->maxImageExtent = extent;
return VK_SUCCESS;
}
void XcbSurfaceKHR::attachImage(PresentImage *image)
{
auto gc = libXCB->xcb_generate_id(connection);
uint32_t values[2] = { 0, 0xffffffff };
libXCB->xcb_create_gc(connection, gc, window, XCB_GC_FOREGROUND | XCB_GC_BACKGROUND, values);
graphicsContexts[image] = gc;
}
void XcbSurfaceKHR::detachImage(PresentImage *image)
{
auto it = graphicsContexts.find(image);
if(it != graphicsContexts.end())
{
libXCB->xcb_free_gc(connection, it->second);
graphicsContexts.erase(it);
}
}
VkResult XcbSurfaceKHR::present(PresentImage *image)
{
auto it = graphicsContexts.find(image);
if(it != graphicsContexts.end())
{
VkExtent2D windowExtent;
int depth;
if(!getWindowSizeAndDepth(connection, window, &windowExtent, &depth))
{
return VK_ERROR_SURFACE_LOST_KHR;
}
const VkExtent3D &extent = image->getImage()->getExtent();
if(windowExtent.width != extent.width || windowExtent.height != extent.height)
{
return VK_ERROR_OUT_OF_DATE_KHR;
}
// TODO: Convert image if not RGB888.
int stride = image->getImage()->rowPitchBytes(VK_IMAGE_ASPECT_COLOR_BIT, 0);
int bytesPerPixel = static_cast<int>(image->getImage()->getFormat(VK_IMAGE_ASPECT_COLOR_BIT).bytes());
int width = stride / bytesPerPixel;
auto buffer = reinterpret_cast<uint8_t *>(image->getImageMemory()->getOffsetPointer(0));
size_t bufferSize = extent.height * stride;
libXCB->xcb_put_image(
connection,
XCB_IMAGE_FORMAT_Z_PIXMAP,
window,
it->second,
width,
extent.height,
0, 0, // dst x, y
0, // left_pad
depth,
bufferSize, // data_len
buffer // data
);
libXCB->xcb_flush(connection);
}
return VK_SUCCESS;
}
} // namespace vk<|endoftext|>
|
<commit_before>/******************************************************************************
** Copyright (c) 2013-2015, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. Redistributions in binary form must reproduce the above copyright **
** notice, this list of conditions and the following disclaimer in the **
** documentation and/or other materials provided with the distribution. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **
******************************************************************************/
/* Hans Pabst (Intel Corp.)
******************************************************************************/
#include <libxsmm.h>
#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(push,target(mic))
#endif
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <vector>
#include <cmath>
#if defined(_OPENMP)
# include <omp.h>
#endif
#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(pop)
#endif
#if (0 < (LIBXSMM_ALIGNED_STORES))
# define SMM_ALIGNMENT LIBXSMM_ALIGNED_STORES
#else
# define SMM_ALIGNMENT LIBXSMM_ALIGNMENT
#endif
// make sure that stacksize is covering the problem size
#define SMM_MAX_PROBLEM_SIZE (5 * LIBXSMM_MAX_MNK)
#define SMM_SCHEDULE dynamic
#define SMM_CHECK
template<typename T>
LIBXSMM_TARGET(mic) void nrand(T& a)
{
static const double scale = 1.0 / RAND_MAX;
a = static_cast<T>(scale * (2 * std::rand() - RAND_MAX));
}
template<typename T>
LIBXSMM_TARGET(mic) void add(T *LIBXSMM_RESTRICT dst, const T *LIBXSMM_RESTRICT c, int m, int n, int ldc)
{
#if (0 < LIBXSMM_ALIGNED_STORES)
LIBXSMM_ASSUME_ALIGNED(c, SMM_ALIGNMENT);
#endif
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
#if (0 != LIBXSMM_ROW_MAJOR)
const T value = c[i*ldc+j];
#else
const T value = c[j*ldc+i];
#endif
#if defined(_OPENMP)
# pragma omp atomic
#endif
#if (0 != LIBXSMM_ROW_MAJOR)
dst[i*n+j] += value;
#else
dst[j*m+i] += value;
#endif
}
}
}
template<typename T>
LIBXSMM_TARGET(mic) double max_diff(const T *LIBXSMM_RESTRICT result, const T *LIBXSMM_RESTRICT expect, int m, int n, int ldc)
{
double diff = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
#if (0 != LIBXSMM_ROW_MAJOR)
const int k = i * ldc + j;
#else
const int k = j * ldc + i;
#endif
diff = std::max(diff, std::abs(static_cast<double>(result[k]) - static_cast<double>(expect[k])));
}
}
return diff;
}
int main(int argc, char* argv[])
{
try {
typedef double T;
const int default_psize = 30000, default_batch = 1000;
const int m = 1 < argc ? std::atoi(argv[1]) : 23;
const int s = 2 < argc ? (0 < std::atoi(argv[2]) ? std::atoi(argv[2]) : ('+' == *argv[2]
? (default_psize << std::strlen(argv[2]))
: (default_psize >> std::strlen(argv[2])))) : default_psize;
const int t = 3 < argc ? (0 < std::atoi(argv[3]) ? std::atoi(argv[3]) : ('+' == *argv[3]
? (default_batch << std::strlen(argv[3]))
: (default_batch >> std::strlen(argv[3])))) : default_batch;
const int n = 4 < argc ? std::atoi(argv[4]) : m;
const int k = 5 < argc ? std::atoi(argv[5]) : m;
#if (0 != LIBXSMM_ROW_MAJOR)
# if (0 < LIBXSMM_ALIGNED_STORES)
const int ldc = LIBXSMM_ALIGN_VALUE(int, T, n, LIBXSMM_ALIGNED_STORES);
# else
const int ldc = n;
# endif
const int csize = m * ldc;
#else
# if (0 < LIBXSMM_ALIGNED_STORES)
const int ldc = LIBXSMM_ALIGN_VALUE(int, T, m, LIBXSMM_ALIGNED_STORES);
# else
const int ldc = m;
# endif
const int csize = n * ldc;
#endif
const int asize = m * k, bsize = k * n;
std::vector<T> va(s * asize), vb(s * bsize), vc(csize);
std::for_each(va.begin(), va.end(), nrand<T>);
std::for_each(vb.begin(), vb.end(), nrand<T>);
const T *const a = &va[0], *const b = &vb[0];
T */*const*/ c = &vc[0];
#if defined(LIBXSMM_OFFLOAD)
# pragma offload target(mic) in(a: length(s * asize)) in(b: length(s * bsize)) out(c: length(csize))
#endif
{
const double mbytes = 1.0 * s * (asize + bsize) * sizeof(T) / (1024 * 1024);
#if defined(_OPENMP)
const double nbytes = 1.0 * s * (csize) * sizeof(T) / (1024 * 1024);
const double gflops = 2.0 * s * m * n * k * 1E-9;
#endif
#if defined(SMM_CHECK)
std::vector<T> expect(csize);
#endif
fprintf(stdout, "m=%i n=%i k=%i ldc=%i size=%i batch=%i memory=%.1f MB\n", m, n, k, ldc, s, t, mbytes);
{ // LAPACK/BLAS3 (fallback)
fprintf(stdout, "LAPACK/BLAS...\n");
std::fill_n(c, csize, 0);
#if defined(_OPENMP)
const double start = omp_get_wtime();
# pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
for (int i = 0; i < s; i += t) {
LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
libxsmm_blasmm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
}
add(c, tmp, m, n, ldc); // atomic
}
#if defined(_OPENMP)
const double duration = omp_get_wtime() - start;
if (0 < duration) {
fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
}
fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
std::copy(c, c + csize, expect.begin());
#endif
}
{ // inline an optimized implementation
fprintf(stdout, "Inlined...\n");
std::fill_n(c, csize, 0);
#if defined(_OPENMP)
const double start = omp_get_wtime();
# pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
for (int i = 0; i < s; i += t) {
LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
libxsmm_imm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
}
add(c, tmp, m, n, ldc); // atomic
}
#if defined(_OPENMP)
const double duration = omp_get_wtime() - start;
if (0 < duration) {
fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
}
fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
}
{ // auto-dispatched
fprintf(stdout, "Dispatched...\n");
std::fill_n(c, csize, 0);
#if defined(_OPENMP)
const double start = omp_get_wtime();
# pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
for (int i = 0; i < s; i += t) {
LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
libxsmm_mm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
}
add(c, tmp, m, n, ldc); // atomic
}
#if defined(_OPENMP)
const double duration = omp_get_wtime() - start;
if (0 < duration) {
fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
}
fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
}
const libxsmm_mm_dispatch<T> xmm(m, n, k);
if (xmm) { // specialized routine
fprintf(stdout, "Specialized...\n");
std::fill_n(c, csize, 0);
#if defined(_OPENMP)
const double start = omp_get_wtime();
# pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
for (int i = 0; i < s; i += t) {
LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
xmm(&a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
}
add(c, tmp, m, n, ldc); // atomic
}
#if defined(_OPENMP)
const double duration = omp_get_wtime() - start;
if (0 < duration) {
fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
}
fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
}
fprintf(stdout, "Finished\n");
}
}
catch(const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
catch(...) {
fprintf(stderr, "Error: unknown exception caught!\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Lowered stacksize requirements; implemented error check against max. problem size. Adjusted source code standard compliance.<commit_after>/******************************************************************************
** Copyright (c) 2013-2015, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. Redistributions in binary form must reproduce the above copyright **
** notice, this list of conditions and the following disclaimer in the **
** documentation and/or other materials provided with the distribution. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **
******************************************************************************/
/* Hans Pabst (Intel Corp.)
******************************************************************************/
#include <libxsmm.h>
#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(push,target(mic))
#endif
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <vector>
#include <cmath>
#if defined(_OPENMP)
# include <omp.h>
#endif
#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(pop)
#endif
#if (0 < (LIBXSMM_ALIGNED_STORES))
# define SMM_ALIGNMENT LIBXSMM_ALIGNED_STORES
#else
# define SMM_ALIGNMENT LIBXSMM_ALIGNMENT
#endif
// make sure that stacksize is covering the problem size
#define SMM_MAX_PROBLEM_SIZE (1 * LIBXSMM_MAX_MNK)
#define SMM_SCHEDULE dynamic
#define SMM_CHECK
template<typename T>
LIBXSMM_TARGET(mic) void nrand(T& a)
{
static const double scale = 1.0 / RAND_MAX;
a = static_cast<T>(scale * (2 * std::rand() - RAND_MAX));
}
template<typename T>
LIBXSMM_TARGET(mic) void add(T *LIBXSMM_RESTRICT dst, const T *LIBXSMM_RESTRICT c, int m, int n, int ldc)
{
#if (0 < LIBXSMM_ALIGNED_STORES)
LIBXSMM_ASSUME_ALIGNED(c, SMM_ALIGNMENT);
#endif
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
#if (0 != LIBXSMM_ROW_MAJOR)
const T value = c[i*ldc+j];
#else
const T value = c[j*ldc+i];
#endif
#if defined(_OPENMP)
# pragma omp atomic
#endif
#if (0 != LIBXSMM_ROW_MAJOR)
dst[i*n+j] += value;
#else
dst[j*m+i] += value;
#endif
}
}
}
template<typename T>
LIBXSMM_TARGET(mic) double max_diff(const T *LIBXSMM_RESTRICT result, const T *LIBXSMM_RESTRICT expect, int m, int n, int ldc)
{
double diff = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
#if (0 != LIBXSMM_ROW_MAJOR)
const int k = i * ldc + j;
#else
const int k = j * ldc + i;
#endif
diff = std::max(diff, std::abs(static_cast<double>(result[k]) - static_cast<double>(expect[k])));
}
}
return diff;
}
int main(int argc, char* argv[])
{
try {
typedef double T;
const int default_psize = 30000, default_batch = 1000;
const int m = 1 < argc ? std::atoi(argv[1]) : 23;
const int s = 2 < argc ? (0 < std::atoi(argv[2]) ? std::atoi(argv[2]) : ('+' == *argv[2]
? (default_psize << std::strlen(argv[2]))
: (default_psize >> std::strlen(argv[2])))) : default_psize;
const int t = 3 < argc ? (0 < std::atoi(argv[3]) ? std::atoi(argv[3]) : ('+' == *argv[3]
? (default_batch << std::strlen(argv[3]))
: (default_batch >> std::strlen(argv[3])))) : default_batch;
const int n = 4 < argc ? std::atoi(argv[4]) : m;
const int k = 5 < argc ? std::atoi(argv[5]) : m;
if ((SMM_MAX_PROBLEM_SIZE) < (m * n * k)) {
throw std::runtime_error("The size M x N x K is exceeding SMM_MAX_PROBLEM_SIZE!");
}
#if (0 != LIBXSMM_ROW_MAJOR)
# if (0 < LIBXSMM_ALIGNED_STORES)
const int ldc = LIBXSMM_ALIGN_VALUE(int, T, n, LIBXSMM_ALIGNED_STORES);
# else
const int ldc = n;
# endif
const int csize = m * ldc;
#else
# if (0 < LIBXSMM_ALIGNED_STORES)
const int ldc = LIBXSMM_ALIGN_VALUE(int, T, m, LIBXSMM_ALIGNED_STORES);
# else
const int ldc = m;
# endif
const int csize = n * ldc;
#endif
const int asize = m * k, bsize = k * n;
std::vector<T> va(s * asize), vb(s * bsize), vc(csize);
std::for_each(va.begin(), va.end(), nrand<T>);
std::for_each(vb.begin(), vb.end(), nrand<T>);
const T *const a = &va[0], *const b = &vb[0];
T * /*const*/ c = &vc[0];
#if defined(LIBXSMM_OFFLOAD)
# pragma offload target(mic) in(a: length(s * asize)) in(b: length(s * bsize)) out(c: length(csize))
#endif
{
const double mbytes = 1.0 * s * (asize + bsize) * sizeof(T) / (1024 * 1024);
#if defined(_OPENMP)
const double nbytes = 1.0 * s * (csize) * sizeof(T) / (1024 * 1024);
const double gflops = 2.0 * s * m * n * k * 1E-9;
#endif
#if defined(SMM_CHECK)
std::vector<T> expect(csize);
#endif
fprintf(stdout, "m=%i n=%i k=%i ldc=%i size=%i batch=%i memory=%.1f MB\n", m, n, k, ldc, s, t, mbytes);
{ // LAPACK/BLAS3 (fallback)
fprintf(stdout, "LAPACK/BLAS...\n");
std::fill_n(c, csize, 0);
#if defined(_OPENMP)
const double start = omp_get_wtime();
# pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
for (int i = 0; i < s; i += t) {
LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
libxsmm_blasmm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
}
add(c, tmp, m, n, ldc); // atomic
}
#if defined(_OPENMP)
const double duration = omp_get_wtime() - start;
if (0 < duration) {
fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
}
fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
std::copy(c, c + csize, expect.begin());
#endif
}
{ // inline an optimized implementation
fprintf(stdout, "Inlined...\n");
std::fill_n(c, csize, 0);
#if defined(_OPENMP)
const double start = omp_get_wtime();
# pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
for (int i = 0; i < s; i += t) {
LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
libxsmm_imm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
}
add(c, tmp, m, n, ldc); // atomic
}
#if defined(_OPENMP)
const double duration = omp_get_wtime() - start;
if (0 < duration) {
fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
}
fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
}
{ // auto-dispatched
fprintf(stdout, "Dispatched...\n");
std::fill_n(c, csize, 0);
#if defined(_OPENMP)
const double start = omp_get_wtime();
# pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
for (int i = 0; i < s; i += t) {
LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
libxsmm_mm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
}
add(c, tmp, m, n, ldc); // atomic
}
#if defined(_OPENMP)
const double duration = omp_get_wtime() - start;
if (0 < duration) {
fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
}
fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
}
const libxsmm_mm_dispatch<T> xmm(m, n, k);
if (xmm) { // specialized routine
fprintf(stdout, "Specialized...\n");
std::fill_n(c, csize, 0);
#if defined(_OPENMP)
const double start = omp_get_wtime();
# pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
for (int i = 0; i < s; i += t) {
LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
xmm(&a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
}
add(c, tmp, m, n, ldc); // atomic
}
#if defined(_OPENMP)
const double duration = omp_get_wtime() - start;
if (0 < duration) {
fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
}
fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
}
fprintf(stdout, "Finished\n");
}
}
catch(const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
catch(...) {
fprintf(stderr, "Error: unknown exception caught!\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "client.h"
#include <boost/assert.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/xpressive/xpressive.hpp>
#include <iostream>
#include <string.h>
#include "random.h"
#define DEFAULT_ASSET_TIMEOUT 4000
using namespace std;
namespace asio = boost::asio;
namespace xpressive = boost::xpressive;
using namespace bithorde;
Client::Client(asio::io_service& ioSvc, string myName) :
_ioSvc(ioSvc),
_connection(),
_myName(myName),
_handleAllocator(1),
_rpcIdAllocator(1),
_protoVersion(0)
{
}
void Client::connect(Connection::Pointer newConn) {
BOOST_ASSERT(!_connection);
_rpcIdAllocator.reset();
_connection = newConn;
_messageConnection = _connection->message.connect(Connection::MessageSignal::slot_type(&Client::onIncomingMessage, this, _1, _2));
_writableConnection = _connection->writable.connect(writable);
_disconnectedConnection = _connection->disconnected.connect(Connection::VoidSignal::slot_type(&Client::onDisconnected, this));
sayHello();
}
void Client::connect(asio::ip::tcp::endpoint& ep) {
connect(Connection::create(_ioSvc, ep));
}
void Client::connect(asio::local::stream_protocol::endpoint& ep) {
connect(Connection::create(_ioSvc, ep));
}
void Client::connect(string spec) {
xpressive::sregex host_port_regex = xpressive::sregex::compile("(\\w+):(\\d+)");
xpressive::smatch res;
if (spec[0] == '/') {
asio::local::stream_protocol::endpoint ep(spec);
connect(ep);
} else if (xpressive::regex_match(spec, res, host_port_regex)) {
asio::ip::tcp::resolver resolver(_ioSvc);
asio::ip::tcp::resolver::query q(res[1], res[2]);
asio::ip::tcp::resolver::iterator iter = resolver.resolve(q);
if (iter != asio::ip::tcp::resolver::iterator()) {
asio::ip::tcp::endpoint ep(iter->endpoint());
connect(ep);
}
} else {
throw string("Failed to parse: " + spec);
}
}
void Client::onDisconnected() {
_connection.reset();
for (auto iter=_assetMap.begin(); iter != _assetMap.end(); iter++) {
ReadAsset* asset = dynamic_cast<ReadAsset*>(iter->second);
if (asset) {
bithorde::AssetStatus s;
s.set_status(bithorde::DISCONNECTED);
asset->statusUpdate(s);
} else {
_handleAllocator.free(iter->first);
_assetMap.erase(iter);
}
}
disconnected();
}
bool Client::isConnected()
{
return _connection;
}
const std::string& Client::peerName()
{
return _peerName;
}
bool Client::sendMessage(Connection::MessageType type, const::google::protobuf::Message &msg)
{
BOOST_ASSERT(_connection);
return _connection->sendMessage(type, msg);
}
void Client::sayHello() {
bithorde::HandShake h;
h.set_protoversion(2);
h.set_name(_myName);
sendMessage(Connection::HandShake, h);
}
void Client::onIncomingMessage(Connection::MessageType type, ::google::protobuf::Message& msg)
{
switch (type) {
case Connection::HandShake: return onMessage((bithorde::HandShake&) msg);
case Connection::BindRead: return onMessage((bithorde::BindRead&) msg);
case Connection::AssetStatus: return onMessage((bithorde::AssetStatus&) msg);
case Connection::ReadRequest: return onMessage((bithorde::Read::Request&) msg);
case Connection::ReadResponse: return onMessage((bithorde::Read::Response&) msg);
case Connection::BindWrite: return onMessage((bithorde::BindWrite&) msg);
case Connection::DataSegment: return onMessage((bithorde::DataSegment&) msg);
case Connection::HandShakeConfirmed: return onMessage((bithorde::HandShakeConfirmed&) msg);
case Connection::Ping: return onMessage((bithorde::Ping&) msg);
}
}
void Client::onMessage(const bithorde::HandShake &msg)
{
if (msg.protoversion() >= 2) {
_protoVersion = 2;
} else {
cerr << "Only Protocol-version 2 or higer supported" << endl;
_connection->close();
_connection.reset();
return;
}
_peerName = msg.name();
if (msg.has_challenge()) {
cerr << "Challenge required" << endl;
// Setup encryption
} else {
for (auto iter = _assetMap.begin(); iter != _assetMap.end(); iter++) {
ReadAsset* asset = dynamic_cast<ReadAsset*>(iter->second);
BOOST_ASSERT(iter->second);
informBound(*asset, rand64());
}
authenticated(_peerName);
}
}
void Client::onMessage(bithorde::BindRead & msg) {
cerr << "unsupported: handling BindRead" << endl;
bithorde::AssetStatus resp;
resp.set_handle(msg.handle());
resp.set_status(ERROR);
sendMessage(bithorde::Connection::AssetStatus, resp);
}
void Client::onMessage(const bithorde::AssetStatus & msg) {
if (!msg.has_handle())
return;
Asset::Handle handle = msg.handle();
if (_assetMap.count(handle)) {
Asset* a = _assetMap[handle];
if (a) {
a->handleMessage(msg);
} else if (msg.status() != bithorde::Status::SUCCESS) {
_assetMap.erase(handle);
_handleAllocator.free(handle);
} else {
cerr << "WARNING: Status OK recieved for Asset supposedly closed or re-written." << endl;
}
} else {
cerr << "WARNING: AssetStatus " << bithorde::Status_Name(msg.status()) << " for unmapped handle" << endl;
}
}
void Client::onMessage(const bithorde::Read::Request & msg) {
cerr << "unsupported: handling Read-Requests" << endl;
bithorde::Read::Response resp;
resp.set_reqid(msg.reqid());
resp.set_status(ERROR);
sendMessage(bithorde::Connection::ReadResponse, resp);
}
void Client::onMessage(const bithorde::Read::Response & msg) {
Asset::Handle assetHandle = _requestIdMap[msg.reqid()];
if (_assetMap.count(assetHandle)) {
Asset* a = _assetMap[assetHandle];
a->handleMessage(msg);
} else {
cerr << "WARNING: ReadResponse " << msg.reqid() << msg.has_reqid() << " for unmapped handle" << endl;
}
}
void Client::onMessage(const bithorde::BindWrite & msg) {
cerr << "unsupported: handling BindWrite" << endl;
bithorde::AssetStatus resp;
resp.set_handle(msg.handle());
resp.set_status(ERROR);
sendMessage(bithorde::Connection::AssetStatus, resp);
}
void Client::onMessage(const bithorde::DataSegment & msg) {
cerr << "unsupported: handling DataSegment-pushes" << endl;
_connection->close();
}
void Client::onMessage(const bithorde::HandShakeConfirmed & msg) {
cerr << "unsupported: challenge-response handshakes" << endl;
_connection->close();
}
void Client::onMessage(const bithorde::Ping & msg) {
bithorde::Ping reply;
_connection->sendMessage(Connection::Ping, reply);
}
bool Client::bind(ReadAsset &asset) {
return bind(asset, rand64());
}
bool Client::bind(ReadAsset &asset, uint64_t uuid) {
if (!asset.isBound()) {
BOOST_ASSERT(asset._handle < 0);
BOOST_ASSERT(asset.requestIds().size() > 0);
asset._handle = _handleAllocator.allocate();
BOOST_ASSERT(asset._handle > 0);
BOOST_ASSERT(_assetMap.count(asset._handle) == 0);
_assetMap[asset._handle] = &asset;
}
return informBound(asset, uuid);
}
bool Client::bind(UploadAsset & asset)
{
BOOST_ASSERT(asset._client.get() == this);
BOOST_ASSERT(asset._handle < 0);
BOOST_ASSERT(asset.size() > 0);
asset._handle = _handleAllocator.allocate();
_assetMap[asset._handle] = &asset;
bithorde::BindWrite msg;
msg.set_handle(asset._handle);
msg.set_size(asset.size());
const auto& link = asset.link();
if (!link.empty())
msg.set_linkpath(link.string());
return _connection->sendMessage(Connection::BindWrite, msg);
}
bool Client::release(Asset & asset)
{
BOOST_ASSERT(asset.isBound());
bithorde::BindRead msg;
msg.set_handle(asset._handle);
msg.set_timeout(DEFAULT_ASSET_TIMEOUT);
msg.set_uuid(rand64());
// Leave handle dangling, so it won't be reused until confirmation has been received from the other side.
_assetMap[asset._handle] = NULL;
asset._handle = -1;
return _connection->sendMessage(Connection::BindRead, msg);
}
bool Client::informBound(const ReadAsset& asset, uint64_t uuid)
{
BOOST_ASSERT(_connection);
BOOST_ASSERT(asset._handle >= 0);
if (!_connection)
return false;
bithorde::BindRead msg;
msg.set_handle(asset._handle);
msg.mutable_ids()->CopyFrom(asset.requestIds());
msg.set_timeout(DEFAULT_ASSET_TIMEOUT);
msg.set_uuid(uuid);
return _connection->sendMessage(Connection::BindRead, msg);
}
int Client::allocRPCRequest(Asset::Handle asset)
{
int res = _rpcIdAllocator.allocate();
_requestIdMap[res] = asset;
return res;
}
void Client::releaseRPCRequest(int reqId)
{
_requestIdMap.erase(reqId);
_rpcIdAllocator.free(reqId);
}
<commit_msg>[lib/client]Check connection before trying to send message.<commit_after>#include "client.h"
#include <boost/assert.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/xpressive/xpressive.hpp>
#include <iostream>
#include <string.h>
#include "random.h"
#define DEFAULT_ASSET_TIMEOUT 4000
using namespace std;
namespace asio = boost::asio;
namespace xpressive = boost::xpressive;
using namespace bithorde;
Client::Client(asio::io_service& ioSvc, string myName) :
_ioSvc(ioSvc),
_connection(),
_myName(myName),
_handleAllocator(1),
_rpcIdAllocator(1),
_protoVersion(0)
{
}
void Client::connect(Connection::Pointer newConn) {
BOOST_ASSERT(!_connection);
_rpcIdAllocator.reset();
_connection = newConn;
_messageConnection = _connection->message.connect(Connection::MessageSignal::slot_type(&Client::onIncomingMessage, this, _1, _2));
_writableConnection = _connection->writable.connect(writable);
_disconnectedConnection = _connection->disconnected.connect(Connection::VoidSignal::slot_type(&Client::onDisconnected, this));
sayHello();
}
void Client::connect(asio::ip::tcp::endpoint& ep) {
connect(Connection::create(_ioSvc, ep));
}
void Client::connect(asio::local::stream_protocol::endpoint& ep) {
connect(Connection::create(_ioSvc, ep));
}
void Client::connect(string spec) {
xpressive::sregex host_port_regex = xpressive::sregex::compile("(\\w+):(\\d+)");
xpressive::smatch res;
if (spec[0] == '/') {
asio::local::stream_protocol::endpoint ep(spec);
connect(ep);
} else if (xpressive::regex_match(spec, res, host_port_regex)) {
asio::ip::tcp::resolver resolver(_ioSvc);
asio::ip::tcp::resolver::query q(res[1], res[2]);
asio::ip::tcp::resolver::iterator iter = resolver.resolve(q);
if (iter != asio::ip::tcp::resolver::iterator()) {
asio::ip::tcp::endpoint ep(iter->endpoint());
connect(ep);
}
} else {
throw string("Failed to parse: " + spec);
}
}
void Client::onDisconnected() {
_connection.reset();
for (auto iter=_assetMap.begin(); iter != _assetMap.end(); iter++) {
ReadAsset* asset = dynamic_cast<ReadAsset*>(iter->second);
if (asset) {
bithorde::AssetStatus s;
s.set_status(bithorde::DISCONNECTED);
asset->statusUpdate(s);
} else {
_handleAllocator.free(iter->first);
_assetMap.erase(iter);
}
}
disconnected();
}
bool Client::isConnected()
{
return _connection;
}
const std::string& Client::peerName()
{
return _peerName;
}
bool Client::sendMessage(Connection::MessageType type, const::google::protobuf::Message &msg)
{
BOOST_ASSERT(_connection);
return _connection->sendMessage(type, msg);
}
void Client::sayHello() {
bithorde::HandShake h;
h.set_protoversion(2);
h.set_name(_myName);
sendMessage(Connection::HandShake, h);
}
void Client::onIncomingMessage(Connection::MessageType type, ::google::protobuf::Message& msg)
{
switch (type) {
case Connection::HandShake: return onMessage((bithorde::HandShake&) msg);
case Connection::BindRead: return onMessage((bithorde::BindRead&) msg);
case Connection::AssetStatus: return onMessage((bithorde::AssetStatus&) msg);
case Connection::ReadRequest: return onMessage((bithorde::Read::Request&) msg);
case Connection::ReadResponse: return onMessage((bithorde::Read::Response&) msg);
case Connection::BindWrite: return onMessage((bithorde::BindWrite&) msg);
case Connection::DataSegment: return onMessage((bithorde::DataSegment&) msg);
case Connection::HandShakeConfirmed: return onMessage((bithorde::HandShakeConfirmed&) msg);
case Connection::Ping: return onMessage((bithorde::Ping&) msg);
}
}
void Client::onMessage(const bithorde::HandShake &msg)
{
if (msg.protoversion() >= 2) {
_protoVersion = 2;
} else {
cerr << "Only Protocol-version 2 or higer supported" << endl;
_connection->close();
_connection.reset();
return;
}
_peerName = msg.name();
if (msg.has_challenge()) {
cerr << "Challenge required" << endl;
// Setup encryption
} else {
for (auto iter = _assetMap.begin(); iter != _assetMap.end(); iter++) {
ReadAsset* asset = dynamic_cast<ReadAsset*>(iter->second);
BOOST_ASSERT(iter->second);
informBound(*asset, rand64());
}
authenticated(_peerName);
}
}
void Client::onMessage(bithorde::BindRead & msg) {
cerr << "unsupported: handling BindRead" << endl;
bithorde::AssetStatus resp;
resp.set_handle(msg.handle());
resp.set_status(ERROR);
sendMessage(bithorde::Connection::AssetStatus, resp);
}
void Client::onMessage(const bithorde::AssetStatus & msg) {
if (!msg.has_handle())
return;
Asset::Handle handle = msg.handle();
if (_assetMap.count(handle)) {
Asset* a = _assetMap[handle];
if (a) {
a->handleMessage(msg);
} else if (msg.status() != bithorde::Status::SUCCESS) {
_assetMap.erase(handle);
_handleAllocator.free(handle);
} else {
cerr << "WARNING: Status OK recieved for Asset supposedly closed or re-written." << endl;
}
} else {
cerr << "WARNING: AssetStatus " << bithorde::Status_Name(msg.status()) << " for unmapped handle" << endl;
}
}
void Client::onMessage(const bithorde::Read::Request & msg) {
cerr << "unsupported: handling Read-Requests" << endl;
bithorde::Read::Response resp;
resp.set_reqid(msg.reqid());
resp.set_status(ERROR);
sendMessage(bithorde::Connection::ReadResponse, resp);
}
void Client::onMessage(const bithorde::Read::Response & msg) {
Asset::Handle assetHandle = _requestIdMap[msg.reqid()];
if (_assetMap.count(assetHandle)) {
Asset* a = _assetMap[assetHandle];
a->handleMessage(msg);
} else {
cerr << "WARNING: ReadResponse " << msg.reqid() << msg.has_reqid() << " for unmapped handle" << endl;
}
}
void Client::onMessage(const bithorde::BindWrite & msg) {
cerr << "unsupported: handling BindWrite" << endl;
bithorde::AssetStatus resp;
resp.set_handle(msg.handle());
resp.set_status(ERROR);
sendMessage(bithorde::Connection::AssetStatus, resp);
}
void Client::onMessage(const bithorde::DataSegment & msg) {
cerr << "unsupported: handling DataSegment-pushes" << endl;
_connection->close();
}
void Client::onMessage(const bithorde::HandShakeConfirmed & msg) {
cerr << "unsupported: challenge-response handshakes" << endl;
_connection->close();
}
void Client::onMessage(const bithorde::Ping & msg) {
bithorde::Ping reply;
_connection->sendMessage(Connection::Ping, reply);
}
bool Client::bind(ReadAsset &asset) {
return bind(asset, rand64());
}
bool Client::bind(ReadAsset &asset, uint64_t uuid) {
if (!asset.isBound()) {
BOOST_ASSERT(asset._handle < 0);
BOOST_ASSERT(asset.requestIds().size() > 0);
asset._handle = _handleAllocator.allocate();
BOOST_ASSERT(asset._handle > 0);
BOOST_ASSERT(_assetMap.count(asset._handle) == 0);
_assetMap[asset._handle] = &asset;
}
return informBound(asset, uuid);
}
bool Client::bind(UploadAsset & asset)
{
BOOST_ASSERT(asset._client.get() == this);
BOOST_ASSERT(asset._handle < 0);
BOOST_ASSERT(asset.size() > 0);
asset._handle = _handleAllocator.allocate();
_assetMap[asset._handle] = &asset;
bithorde::BindWrite msg;
msg.set_handle(asset._handle);
msg.set_size(asset.size());
const auto& link = asset.link();
if (!link.empty())
msg.set_linkpath(link.string());
return _connection->sendMessage(Connection::BindWrite, msg);
}
bool Client::release(Asset & asset)
{
BOOST_ASSERT(asset.isBound());
bithorde::BindRead msg;
msg.set_handle(asset._handle);
msg.set_timeout(DEFAULT_ASSET_TIMEOUT);
msg.set_uuid(rand64());
// Leave handle dangling, so it won't be reused until confirmation has been received from the other side.
_assetMap[asset._handle] = NULL;
asset._handle = -1;
if (_connection)
return _connection->sendMessage(Connection::BindRead, msg);
else
return true; // Since connection is down, other side should not have the bound state as it is.
}
bool Client::informBound(const ReadAsset& asset, uint64_t uuid)
{
BOOST_ASSERT(_connection);
BOOST_ASSERT(asset._handle >= 0);
if (!_connection)
return false;
bithorde::BindRead msg;
msg.set_handle(asset._handle);
msg.mutable_ids()->CopyFrom(asset.requestIds());
msg.set_timeout(DEFAULT_ASSET_TIMEOUT);
msg.set_uuid(uuid);
return _connection->sendMessage(Connection::BindRead, msg);
}
int Client::allocRPCRequest(Asset::Handle asset)
{
int res = _rpcIdAllocator.allocate();
_requestIdMap[res] = asset;
return res;
}
void Client::releaseRPCRequest(int reqId)
{
_requestIdMap.erase(reqId);
_rpcIdAllocator.free(reqId);
}
<|endoftext|>
|
<commit_before>/** \file crf_analyzer.cpp
* Implementation of class CRF_Analyzer.
*
* \author Jun Jiang
* \version 0.1
* \date Mar 2, 2009
*/
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include "jma_analyzer.h"
#include "jma_knowledge.h"
#include "tokenizer.h"
namespace jma
{
/**
* Whether the two MorphemeLists is the same
* \param list1 the MorphemeList 1
* \param list2 the MorphemeList 2
*/
inline bool isSameMorphemeList( const MorphemeList* list1, const MorphemeList* list2, bool printPOS )
{
// if one is zero pointer, return null
if( !list1 || !list2 )
{
return false;
}
if( list1->size() != list2->size() )
return false;
//compare one by one
size_t N = list1->size();
if( printPOS )
{
for( size_t i = 0; i < N; ++i )
{
const Morpheme& m1 = (*list1)[i];
const Morpheme& m2 = (*list2)[i];
if( m1.lexicon_ != m2.lexicon_ || m1.posCode_ != m2.posCode_
|| m1.posStr_ != m2.posStr_ )
{
return false;
}
}
}
else
{
for( size_t i = 0; i < N; ++i )
{
if( (*list1)[i].lexicon_ != (*list2)[i].lexicon_ )
return false;
}
}
//all the elements are the same
return true;
}
JMA_Analyzer::JMA_Analyzer()
: knowledge_(0), tagger_(0)
{
}
JMA_Analyzer::~JMA_Analyzer()
{
}
void JMA_Analyzer::setKnowledge(Knowledge* pKnowledge)
{
assert(pKnowledge);
knowledge_ = dynamic_cast<JMA_Knowledge*>(pKnowledge);
assert(knowledge_);
tagger_ = knowledge_->getTagger();
// if runWith*() would be called, tagger_ should not be NULL,
// if only splitSentence() would be called, tagger_ could be NULL as no dictionary needs to be loaded.
if(tagger_)
{
tagger_->set_lattice_level(1);
}
maxPosCateOffset_ = knowledge_->getPOSCatNum() - 1;
}
int JMA_Analyzer::runWithSentence(Sentence& sentence)
{
if(tagger_ == 0)
{
cerr << "MeCab::Tagger is not created, please insure that dictionary files are loaded successfully." << endl;
return 0;
}
bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;
int N = (int)getOption(Analyzer::OPTION_TYPE_NBEST);
//one best
if(N <= 1)
{
const MeCab::Node* bosNode = tagger_->parseToNode( sentence.getString() );
MorphemeList list;
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next)
{
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
list.push_back(Morpheme());
Morpheme& morp = list.back();
morp.lexicon_ = seg;
if(printPOS)
{
morp.posCode_ = (int)node->posid;
morp.posStr_ = string(node->feature, getPOSOffset(node->feature));
}
}
sentence.addList(list, 1.0);
}
// N-best
else
{
double totalScore = 0;
if( !tagger_->parseNBestInit( sentence.getString() ) )
{
cerr << "[Error] Cannot parseNBestInit on the " << sentence.getString() << endl;
return 0;
}
long base = 0;
int i = 0;
for ( ; i < N; )
{
const MeCab::Node* bosNode = tagger_->nextNode();
if( !bosNode )
break;
MorphemeList list;
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next)
{
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
list.push_back(Morpheme());
Morpheme& morp = list.back();
morp.lexicon_ = seg;
if(printPOS)
{
morp.posCode_ = (int)node->posid;
morp.posStr_ = string(node->feature, getPOSOffset(node->feature));
}
}
bool isDupl = false;
//check the current result with exits results
for( int listOffset = sentence.getListSize() - 1 ; listOffset >= 0; --listOffset )
{
if( isSameMorphemeList( sentence.getMorphemeList(listOffset), &list, printPOS ) )
{
isDupl = true;
break;
}
}
//ignore the duplicate results
if( isDupl )
continue;
long score = tagger_->nextScore();
if( i == 0 )
base = score > BASE_NBEST_SCORE ? score - BASE_NBEST_SCORE : 0;
double dScore = 1.0 / (score - base );
totalScore += dScore;
sentence.addList( list, dScore );
++i;
}
for ( int j = 0; j < i; ++j )
{
sentence.setScore(j, sentence.getScore(j) / totalScore );
}
}
return 1;
}
const char* JMA_Analyzer::runWithString(const char* inStr)
{
if(tagger_ == 0)
{
cerr << "MeCab::Tagger is not created, please insure that dictionary files are loaded successfully." << endl;
return 0;
}
bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;
const MeCab::Node* bosNode = tagger_->parseToNode( inStr );
strBuf_.clear();
if (printPOS) {
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
strBuf_.append(node->surface, node->length).append(posDelimiter_).
append(node->feature, getPOSOffset(node->feature) ).append(wordDelimiter_);
}
} else {
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
strBuf_.append(node->surface, node->length).append(wordDelimiter_);
}
}
return strBuf_.c_str();
}
int JMA_Analyzer::runWithStream(const char* inFileName, const char* outFileName)
{
assert(inFileName);
assert(outFileName);
if(tagger_ == 0)
{
cerr << "MeCab::Tagger is not created, please insure that dictionary files are loaded successfully." << endl;
return 0;
}
bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;
ifstream in(inFileName);
if(!in)
{
cerr<<"[Error] The input file "<<inFileName<<" not exists!"<<endl;
return 0;
}
ofstream out(outFileName);
string line;
bool remains = !in.eof();
while (remains) {
getline(in, line);
remains = !in.eof();
if (!line.length()) {
if( remains )
out << endl;
continue;
}
const MeCab::Node* bosNode = tagger_->parseToNode( line.c_str() );
if (printPOS) {
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
out.write(node->surface, node->length) << posDelimiter_;
out.write(node->feature, getPOSOffset(node->feature) ) << wordDelimiter_;
}
if (remains)
out << endl;
else
break;
} else {
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
out.write(node->surface, node->length) << wordDelimiter_;
}
if (remains)
out << endl;
else
break;
}
}
in.close();
out.close();
return 1;
}
void JMA_Analyzer::splitSentence(const char* paragraph, std::vector<Sentence>& sentences)
{
if(! paragraph)
return;
Sentence result;
string sentenceStr;
CTypeTokenizer tokenizer( knowledge_->getCType() );
tokenizer.assign(paragraph);
for(const char* p=tokenizer.next(); p; p=tokenizer.next())
{
if( knowledge_->isSentenceSeparator(p) )
{
sentenceStr += p;
result.setString(sentenceStr.c_str());
sentences.push_back(result);
sentenceStr.clear();
}
/*// white-space characters are also used as sentence separator,
// but they are ignored in the sentence result
else if(ctype_->isSpace(p))
{
if(! sentenceStr.empty())
{
result.setString(sentenceStr.c_str());
sentences.push_back(result);
sentenceStr.clear();
}
}*/
else
{
sentenceStr += p;
}
}
// in case the last character is not space or sentence separator
if(! sentenceStr.empty())
{
result.setString(sentenceStr.c_str());
sentences.push_back(result);
sentenceStr.clear();
}
}
int JMA_Analyzer::getPOSOffset(const char* feature){
if( knowledge_->isOutputFullPOS() )
{
// count for the index of the fourth offset
int offset = 0;
int commaCount = 0;
for( ; feature[offset]; ++offset )
{
if(feature[offset] == ',')
{
++commaCount;
if( commaCount > maxPosCateOffset_ )
break;
}
}
return offset;
}
//count for the index of the comma that after non-star pos sections
int offset = 0;
int commaCount = 0;
for( ; feature[offset]; ++offset )
{
if(feature[offset] == ',')
{
++commaCount;
if( commaCount > maxPosCateOffset_ )
break;
}
else if(feature[offset] == '*')
{
//if offset is 0, contains nothing
return offset ? offset - 1 : 0 ;
}
}
return offset;
}
} // namespace jma
<commit_msg>check whether output file exists in JMA_Analyzer::runWithStream()<commit_after>/** \file crf_analyzer.cpp
* Implementation of class CRF_Analyzer.
*
* \author Jun Jiang
* \version 0.1
* \date Mar 2, 2009
*/
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include "jma_analyzer.h"
#include "jma_knowledge.h"
#include "tokenizer.h"
namespace jma
{
/**
* Whether the two MorphemeLists is the same
* \param list1 the MorphemeList 1
* \param list2 the MorphemeList 2
*/
inline bool isSameMorphemeList( const MorphemeList* list1, const MorphemeList* list2, bool printPOS )
{
// if one is zero pointer, return null
if( !list1 || !list2 )
{
return false;
}
if( list1->size() != list2->size() )
return false;
//compare one by one
size_t N = list1->size();
if( printPOS )
{
for( size_t i = 0; i < N; ++i )
{
const Morpheme& m1 = (*list1)[i];
const Morpheme& m2 = (*list2)[i];
if( m1.lexicon_ != m2.lexicon_ || m1.posCode_ != m2.posCode_
|| m1.posStr_ != m2.posStr_ )
{
return false;
}
}
}
else
{
for( size_t i = 0; i < N; ++i )
{
if( (*list1)[i].lexicon_ != (*list2)[i].lexicon_ )
return false;
}
}
//all the elements are the same
return true;
}
JMA_Analyzer::JMA_Analyzer()
: knowledge_(0), tagger_(0)
{
}
JMA_Analyzer::~JMA_Analyzer()
{
}
void JMA_Analyzer::setKnowledge(Knowledge* pKnowledge)
{
assert(pKnowledge);
knowledge_ = dynamic_cast<JMA_Knowledge*>(pKnowledge);
assert(knowledge_);
tagger_ = knowledge_->getTagger();
// if runWith*() would be called, tagger_ should not be NULL,
// if only splitSentence() would be called, tagger_ could be NULL as no dictionary needs to be loaded.
if(tagger_)
{
tagger_->set_lattice_level(1);
}
maxPosCateOffset_ = knowledge_->getPOSCatNum() - 1;
}
int JMA_Analyzer::runWithSentence(Sentence& sentence)
{
if(tagger_ == 0)
{
cerr << "MeCab::Tagger is not created, please insure that dictionary files are loaded successfully." << endl;
return 0;
}
bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;
int N = (int)getOption(Analyzer::OPTION_TYPE_NBEST);
//one best
if(N <= 1)
{
const MeCab::Node* bosNode = tagger_->parseToNode( sentence.getString() );
MorphemeList list;
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next)
{
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
list.push_back(Morpheme());
Morpheme& morp = list.back();
morp.lexicon_ = seg;
if(printPOS)
{
morp.posCode_ = (int)node->posid;
morp.posStr_ = string(node->feature, getPOSOffset(node->feature));
}
}
sentence.addList(list, 1.0);
}
// N-best
else
{
double totalScore = 0;
if( !tagger_->parseNBestInit( sentence.getString() ) )
{
cerr << "[Error] Cannot parseNBestInit on the " << sentence.getString() << endl;
return 0;
}
long base = 0;
int i = 0;
for ( ; i < N; )
{
const MeCab::Node* bosNode = tagger_->nextNode();
if( !bosNode )
break;
MorphemeList list;
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next)
{
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
list.push_back(Morpheme());
Morpheme& morp = list.back();
morp.lexicon_ = seg;
if(printPOS)
{
morp.posCode_ = (int)node->posid;
morp.posStr_ = string(node->feature, getPOSOffset(node->feature));
}
}
bool isDupl = false;
//check the current result with exits results
for( int listOffset = sentence.getListSize() - 1 ; listOffset >= 0; --listOffset )
{
if( isSameMorphemeList( sentence.getMorphemeList(listOffset), &list, printPOS ) )
{
isDupl = true;
break;
}
}
//ignore the duplicate results
if( isDupl )
continue;
long score = tagger_->nextScore();
if( i == 0 )
base = score > BASE_NBEST_SCORE ? score - BASE_NBEST_SCORE : 0;
double dScore = 1.0 / (score - base );
totalScore += dScore;
sentence.addList( list, dScore );
++i;
}
for ( int j = 0; j < i; ++j )
{
sentence.setScore(j, sentence.getScore(j) / totalScore );
}
}
return 1;
}
const char* JMA_Analyzer::runWithString(const char* inStr)
{
if(tagger_ == 0)
{
cerr << "MeCab::Tagger is not created, please insure that dictionary files are loaded successfully." << endl;
return 0;
}
bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;
const MeCab::Node* bosNode = tagger_->parseToNode( inStr );
strBuf_.clear();
if (printPOS) {
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
strBuf_.append(node->surface, node->length).append(posDelimiter_).
append(node->feature, getPOSOffset(node->feature) ).append(wordDelimiter_);
}
} else {
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
strBuf_.append(node->surface, node->length).append(wordDelimiter_);
}
}
return strBuf_.c_str();
}
int JMA_Analyzer::runWithStream(const char* inFileName, const char* outFileName)
{
assert(inFileName);
assert(outFileName);
if(tagger_ == 0)
{
cerr << "MeCab::Tagger is not created, please insure that dictionary files are loaded successfully." << endl;
return 0;
}
bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;
ifstream in(inFileName);
if(!in)
{
cerr<<"[Error] The input file "<<inFileName<<" not exists!"<<endl;
return 0;
}
ofstream out(outFileName);
if(!out)
{
cerr<<"[Error] The output file "<<outFileName<<" could not be created!"<<endl;
return 0;
}
string line;
bool remains = !in.eof();
while (remains) {
getline(in, line);
remains = !in.eof();
if (!line.length()) {
if( remains )
out << endl;
continue;
}
const MeCab::Node* bosNode = tagger_->parseToNode( line.c_str() );
if (printPOS) {
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
out.write(node->surface, node->length) << posDelimiter_;
out.write(node->feature, getPOSOffset(node->feature) ) << wordDelimiter_;
}
if (remains)
out << endl;
else
break;
} else {
for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
string seg(node->surface, node->length);
if(knowledge_->isStopWord(seg))
continue;
out.write(node->surface, node->length) << wordDelimiter_;
}
if (remains)
out << endl;
else
break;
}
}
in.close();
out.close();
return 1;
}
void JMA_Analyzer::splitSentence(const char* paragraph, std::vector<Sentence>& sentences)
{
if(! paragraph)
return;
Sentence result;
string sentenceStr;
CTypeTokenizer tokenizer( knowledge_->getCType() );
tokenizer.assign(paragraph);
for(const char* p=tokenizer.next(); p; p=tokenizer.next())
{
if( knowledge_->isSentenceSeparator(p) )
{
sentenceStr += p;
result.setString(sentenceStr.c_str());
sentences.push_back(result);
sentenceStr.clear();
}
/*// white-space characters are also used as sentence separator,
// but they are ignored in the sentence result
else if(ctype_->isSpace(p))
{
if(! sentenceStr.empty())
{
result.setString(sentenceStr.c_str());
sentences.push_back(result);
sentenceStr.clear();
}
}*/
else
{
sentenceStr += p;
}
}
// in case the last character is not space or sentence separator
if(! sentenceStr.empty())
{
result.setString(sentenceStr.c_str());
sentences.push_back(result);
sentenceStr.clear();
}
}
int JMA_Analyzer::getPOSOffset(const char* feature){
if( knowledge_->isOutputFullPOS() )
{
// count for the index of the fourth offset
int offset = 0;
int commaCount = 0;
for( ; feature[offset]; ++offset )
{
if(feature[offset] == ',')
{
++commaCount;
if( commaCount > maxPosCateOffset_ )
break;
}
}
return offset;
}
//count for the index of the comma that after non-star pos sections
int offset = 0;
int commaCount = 0;
for( ; feature[offset]; ++offset )
{
if(feature[offset] == ',')
{
++commaCount;
if( commaCount > maxPosCateOffset_ )
break;
}
else if(feature[offset] == '*')
{
//if offset is 0, contains nothing
return offset ? offset - 1 : 0 ;
}
}
return offset;
}
} // namespace jma
<|endoftext|>
|
<commit_before>//
// Created by david on 2020-05-13.
//
#include "env.h"
#include <math/num.h>
#include <tensors/edges/class_edges_finite.h>
#include <tensors/edges/class_env_ene.h>
#include <tensors/edges/class_env_var.h>
#include <tensors/model/class_model_finite.h>
#include <tensors/state/class_state_finite.h>
#include <tensors/state/class_mps_site.h>
#include <tensors/model/class_mpo_site.h>
#include <tools/common/log.h>
#include <tools/common/prof.h>
void tools::finite::env::assert_edges_ene(const class_state_finite &state, const class_model_finite &model, const class_edges_finite &edges){
size_t min_pos = 0;
size_t max_pos = state.get_length() - 1;
// If there are no active sites then we can build up until current position
// Otherwise it's enough to check up until the bracket defined by active_sites
long current_position = state.get_position<long>();
size_t posL_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
size_t posR_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
if(not edges.active_sites.empty()) {
posL_active = edges.active_sites.front();
posR_active = edges.active_sites.back();
}
tools::log->trace("Asserting edges eneL from [{} to {}]", min_pos,posL_active);
for(size_t pos = min_pos; pos <= posL_active; pos++) {
auto &ene = edges.get_eneL(pos);
if(pos == 0 and not ene.has_block()) throw std::runtime_error(fmt::format("ene L at pos {} does not have a block", pos));
if(pos >= std::min(posL_active,state.get_length()-1)) continue;
auto &mps = state.get_mps_site(pos);
auto &mpo = model.get_mpo(pos);
auto &ene_next = edges.get_eneL(pos + 1);
ene_next.assert_unique_id(ene,mps, mpo);
}
tools::log->trace("Asserting edges eneR from [{} to {}]", posR_active,max_pos);
for(size_t pos = max_pos; pos >= posR_active and pos < state.get_length(); pos--) {
auto &ene = edges.get_eneR(pos);
if(pos == state.get_length() - 1 and not ene.has_block()) throw std::runtime_error(fmt::format("ene R at pos {} does not have a block", pos));
if(pos <= std::max(posR_active,0ul)) continue;
auto &mps = state.get_mps_site(pos);
auto &mpo = model.get_mpo(pos);
auto &ene_prev = edges.get_eneR(pos - 1);
ene_prev.assert_unique_id(ene, mps, mpo);
}
}
void tools::finite::env::assert_edges_var(const class_state_finite &state, const class_model_finite &model, const class_edges_finite &edges){
size_t min_pos = 0;
size_t max_pos = state.get_length() - 1;
// If there are no active sites then we can build up until current position
// Otherwise it's enough to check up until the bracket defined by active_sites
long current_position = state.get_position<long>();
size_t posL_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
size_t posR_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
if(not edges.active_sites.empty()) {
posL_active = edges.active_sites.front();
posR_active = edges.active_sites.back();
}
tools::log->trace("Asserting edges varL from [{} to {}]", min_pos,posL_active);
for(size_t pos = min_pos; pos <= posL_active; pos++) {
auto &var = edges.get_varL(pos);
if(pos == 0 and not var.has_block()) throw std::runtime_error(fmt::format("var L at pos {} does not have a block", pos));
if(pos >= std::min(posL_active,state.get_length()-1)) continue;
auto &mps = state.get_mps_site(pos);
auto &mpo = model.get_mpo(pos);
auto &var_next = edges.get_varL(pos + 1);
var_next.assert_unique_id(var,mps, mpo);
}
tools::log->trace("Asserting edges varR from [{} to {}]", posR_active,max_pos);
for(size_t pos = max_pos; pos >= posR_active and pos < state.get_length(); pos--) {
auto &var = edges.get_varR(pos);
if(pos == state.get_length() - 1 and not var.has_block()) throw std::runtime_error(fmt::format("var R at pos {} does not have a block", pos));
if(pos <= std::max(posR_active,0ul)) continue;
auto &mps = state.get_mps_site(pos);
auto &mpo = model.get_mpo(pos);
auto &var_prev = edges.get_varR(pos - 1);
var_prev.assert_unique_id(var, mps, mpo);
}
}
void tools::finite::env::assert_edges(const class_state_finite &state, const class_model_finite &model, const class_edges_finite &edges){
assert_edges_ene(state,model,edges);
assert_edges_var(state,model,edges);
}
void tools::finite::env::rebuild_edges_ene(const class_state_finite &state, const class_model_finite &model, class_edges_finite &edges) {
if(not num::all_equal(state.get_length(), model.get_length(), edges.get_length()))
throw std::runtime_error(
fmt::format("All lengths not equal: state {} | model {} | edges {}", state.get_length(), model.get_length(), edges.get_length()));
if(not num::all_equal(state.active_sites, model.active_sites, edges.active_sites))
throw std::runtime_error(
fmt::format("All active sites are not equal: state {} | model {} | edges {}", state.active_sites, model.active_sites, edges.active_sites));
tools::common::profile::get_default_prof()["t_env"]->tic();
size_t min_pos = 0;
size_t max_pos = state.get_length() - 1;
// If there are no active sites then we can build up until current position
long current_position = state.get_position<long>();
size_t posL_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
size_t posR_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
if(not edges.active_sites.empty()) {
posL_active = edges.active_sites.front();
posR_active = edges.active_sites.back();
}
tools::log->trace("Inspecting edges eneL from [{} to {}]", min_pos,posL_active);
std::vector<size_t> ene_pos_log;
for(size_t pos = min_pos; pos <= posL_active; pos++) {
auto &ene_curr = edges.get_eneL(pos);
if(pos == 0 and not ene_curr.has_block()){
ene_pos_log.emplace_back(pos);
ene_curr.set_edge_dims(state.get_mps_site(pos), model.get_mpo(pos));
}
if(pos >= std::min(posL_active,state.get_length()-1)) continue;
auto &ene_next = edges.get_eneL(pos + 1);
auto id = ene_next.get_unique_id();
ene_next.refresh(ene_curr, state.get_mps_site(pos), model.get_mpo(pos));
if(id != ene_next.get_unique_id()) ene_pos_log.emplace_back(ene_next.get_position());
}
if(not ene_pos_log.empty()) tools::log->debug("Rebuilt L ene edges: {}", ene_pos_log);
ene_pos_log.clear();
tools::log->trace("Inspecting edges eneR from [{} to {}]", posR_active,max_pos);
for(size_t pos = max_pos; pos >= posR_active and pos < state.get_length(); pos--) {
auto &ene_curr = edges.get_eneR(pos);
if(pos == state.get_length() -1 and not ene_curr.has_block()){
ene_pos_log.emplace_back(pos);
ene_curr.set_edge_dims(state.get_mps_site(pos), model.get_mpo(pos));
// state.set_edge_ene_status(pos,EdgeStatus::FRESH);
}
if(pos <= std::max(posR_active,0ul)) continue;
auto &ene_prev = edges.get_eneR(pos - 1);
auto id = ene_prev.get_unique_id();
ene_prev.refresh(ene_curr, state.get_mps_site(pos), model.get_mpo(pos));
if(id != ene_prev.get_unique_id()) ene_pos_log.emplace_back(ene_prev.get_position());
}
std::reverse(ene_pos_log.begin(), ene_pos_log.end());
if(not ene_pos_log.empty()) tools::log->debug("Rebuilt R ene edges: {}", ene_pos_log);
if(not edges.get_eneL(posL_active).has_block()) throw std::logic_error(fmt::format("Left active ene edge has undefined block"));
if(not edges.get_eneR(posR_active).has_block()) throw std::logic_error(fmt::format("Right active ene edge has undefined block"));
tools::common::profile::get_default_prof()["t_env"]->toc();
}
void tools::finite::env::rebuild_edges_var(const class_state_finite &state, const class_model_finite &model, class_edges_finite &edges) {
if(not num::all_equal(state.get_length(), model.get_length(), edges.get_length()))
throw std::runtime_error(
fmt::format("All lengths not equal: state {} | model {} | edges {}", state.get_length(), model.get_length(), edges.get_length()));
if(not num::all_equal(state.active_sites, model.active_sites, edges.active_sites))
throw std::runtime_error(
fmt::format("All active sites are not equal: state {} | model {} | edges {}", state.active_sites, model.active_sites, edges.active_sites));
tools::common::profile::get_default_prof()["t_env"]->tic();
size_t min_pos = 0;
size_t max_pos = state.get_length() - 1;
// If there are no active sites then we can build up until current position
// Otherwise it's enough to build up until the bracket defined by active_sites
long current_position = state.get_position<long>();
size_t posL_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
size_t posR_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
if(not edges.active_sites.empty()) {
posL_active = edges.active_sites.front();
posR_active = edges.active_sites.back();
}
tools::log->trace("Inspecting edges varL from [{} to {}]", min_pos,posL_active);
std::vector<size_t> var_pos_log;
for(size_t pos = min_pos; pos <= posL_active; pos++) {
auto &var_curr = edges.get_varL(pos);
if(pos == 0 and not var_curr.has_block()){
tools::log->trace("Edge not found at pos {}, has_block: {}", var_curr.get_position(), var_curr.has_block());
var_pos_log.emplace_back(pos);
var_curr.set_edge_dims(state.get_mps_site(pos), model.get_mpo(pos));
if(not var_curr.has_block()) throw std::runtime_error("No edge detected after setting edge");
}
if(pos >= std::min(posL_active,state.get_length()-1)) continue;
auto &var_next = edges.get_varL(pos + 1);
auto id = var_next.get_unique_id();
var_next.refresh(var_curr, state.get_mps_site(pos), model.get_mpo(pos));
if(id != var_next.get_unique_id()) var_pos_log.emplace_back(var_next.get_position());
}
if(not var_pos_log.empty()) tools::log->debug("Rebuilt L var edges: {}", var_pos_log);
var_pos_log.clear();
tools::log->trace("Inspecting edges varR from [{} to {}]", posR_active,max_pos);
for(size_t pos = max_pos; pos >= posR_active and pos < state.get_length(); pos--) {
auto &var_curr = edges.get_varR(pos);
if(pos == state.get_length() - 1 and not var_curr.has_block()){
var_pos_log.emplace_back(pos);
var_curr.set_edge_dims(state.get_mps_site(pos), model.get_mpo(pos));
}
if(pos <= std::max(posR_active,0ul)) continue;
auto &var_prev = edges.get_varR(pos - 1);
auto id = var_prev.get_unique_id();
var_prev.refresh(var_curr,state.get_mps_site(pos), model.get_mpo(pos));
if(id != var_prev.get_unique_id()) var_pos_log.emplace_back(var_prev.get_position());
}
std::reverse(var_pos_log.begin(), var_pos_log.end());
if(not var_pos_log.empty()) tools::log->debug("Rebuilt R var edges: {}", var_pos_log);
if(not edges.get_varL(posL_active).has_block()) throw std::logic_error(fmt::format("Left active var edge has undefined block"));
if(not edges.get_varR(posR_active).has_block()) throw std::logic_error(fmt::format("Right active var edge has undefined block"));
tools::common::profile::get_default_prof()["t_env"]->toc();
}
void tools::finite::env::rebuild_edges(const class_state_finite &state, const class_model_finite &model, class_edges_finite &edges) {
rebuild_edges_ene(state,model,edges);
rebuild_edges_var(state,model,edges);
}
<commit_msg>clang-format<commit_after>//
// Created by david on 2020-05-13.
//
#include "env.h"
#include <math/num.h>
#include <tensors/edges/class_edges_finite.h>
#include <tensors/edges/class_env_ene.h>
#include <tensors/edges/class_env_var.h>
#include <tensors/model/class_model_finite.h>
#include <tensors/state/class_state_finite.h>
#include <tensors/state/class_mps_site.h>
#include <tensors/model/class_mpo_site.h>
#include <tools/common/log.h>
#include <tools/common/prof.h>
void tools::finite::env::assert_edges_ene(const class_state_finite &state, const class_model_finite &model, const class_edges_finite &edges){
size_t min_pos = 0;
size_t max_pos = state.get_length() - 1;
// If there are no active sites then we can build up until current position
// Otherwise it's enough to check up until the bracket defined by active_sites
long current_position = state.get_position<long>();
size_t posL_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
size_t posR_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
if(not edges.active_sites.empty()) {
posL_active = edges.active_sites.front();
posR_active = edges.active_sites.back();
}
tools::log->trace("Asserting edges eneL from [{} to {}]", min_pos,posL_active);
for(size_t pos = min_pos; pos <= posL_active; pos++) {
auto &ene = edges.get_eneL(pos);
if(pos == 0 and not ene.has_block()) throw std::runtime_error(fmt::format("ene L at pos {} does not have a block", pos));
if(pos >= std::min(posL_active,state.get_length()-1)) continue;
auto &mps = state.get_mps_site(pos);
auto &mpo = model.get_mpo(pos);
auto &ene_next = edges.get_eneL(pos + 1);
ene_next.assert_unique_id(ene,mps, mpo);
}
tools::log->trace("Asserting edges eneR from [{} to {}]", posR_active,max_pos);
for(size_t pos = max_pos; pos >= posR_active and pos < state.get_length(); pos--) {
auto &ene = edges.get_eneR(pos);
if(pos == state.get_length() - 1 and not ene.has_block()) throw std::runtime_error(fmt::format("ene R at pos {} does not have a block", pos));
if(pos <= std::max(posR_active,0ul)) continue;
auto &mps = state.get_mps_site(pos);
auto &mpo = model.get_mpo(pos);
auto &ene_prev = edges.get_eneR(pos - 1);
ene_prev.assert_unique_id(ene, mps, mpo);
}
}
void tools::finite::env::assert_edges_var(const class_state_finite &state, const class_model_finite &model, const class_edges_finite &edges){
size_t min_pos = 0;
size_t max_pos = state.get_length() - 1;
// If there are no active sites then we can build up until current position
// Otherwise it's enough to check up until the bracket defined by active_sites
long current_position = state.get_position<long>();
size_t posL_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
size_t posR_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
if(not edges.active_sites.empty()) {
posL_active = edges.active_sites.front();
posR_active = edges.active_sites.back();
}
tools::log->trace("Asserting edges varL from [{} to {}]", min_pos,posL_active);
for(size_t pos = min_pos; pos <= posL_active; pos++) {
auto &var = edges.get_varL(pos);
if(pos == 0 and not var.has_block()) throw std::runtime_error(fmt::format("var L at pos {} does not have a block", pos));
if(pos >= std::min(posL_active,state.get_length()-1)) continue;
auto &mps = state.get_mps_site(pos);
auto &mpo = model.get_mpo(pos);
auto &var_next = edges.get_varL(pos + 1);
var_next.assert_unique_id(var,mps, mpo);
}
tools::log->trace("Asserting edges varR from [{} to {}]", posR_active,max_pos);
for(size_t pos = max_pos; pos >= posR_active and pos < state.get_length(); pos--) {
auto &var = edges.get_varR(pos);
if(pos == state.get_length() - 1 and not var.has_block()) throw std::runtime_error(fmt::format("var R at pos {} does not have a block", pos));
if(pos <= std::max(posR_active,0ul)) continue;
auto &mps = state.get_mps_site(pos);
auto &mpo = model.get_mpo(pos);
auto &var_prev = edges.get_varR(pos - 1);
var_prev.assert_unique_id(var, mps, mpo);
}
}
void tools::finite::env::assert_edges(const class_state_finite &state, const class_model_finite &model, const class_edges_finite &edges){
assert_edges_ene(state,model,edges);
assert_edges_var(state,model,edges);
}
void tools::finite::env::rebuild_edges_ene(const class_state_finite &state, const class_model_finite &model, class_edges_finite &edges) {
if(not num::all_equal(state.get_length(), model.get_length(), edges.get_length()))
throw std::runtime_error(
fmt::format("All lengths not equal: state {} | model {} | edges {}", state.get_length(), model.get_length(), edges.get_length()));
if(not num::all_equal(state.active_sites, model.active_sites, edges.active_sites))
throw std::runtime_error(
fmt::format("All active sites are not equal: state {} | model {} | edges {}", state.active_sites, model.active_sites, edges.active_sites));
tools::common::profile::get_default_prof()["t_env"]->tic();
size_t min_pos = 0;
size_t max_pos = state.get_length() - 1;
// If there are no active sites then we can build up until current position
long current_position = state.get_position<long>();
size_t posL_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
size_t posR_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
if(not edges.active_sites.empty()) {
posL_active = edges.active_sites.front();
posR_active = edges.active_sites.back();
}
tools::log->trace("Inspecting edges eneL from [{} to {}]", min_pos,posL_active);
std::vector<size_t> ene_pos_log;
for(size_t pos = min_pos; pos <= posL_active; pos++) {
auto &ene_curr = edges.get_eneL(pos);
if(pos == 0 and not ene_curr.has_block()){
ene_pos_log.emplace_back(pos);
ene_curr.set_edge_dims(state.get_mps_site(pos), model.get_mpo(pos));
}
if(pos >= std::min(posL_active,state.get_length()-1)) continue;
auto &ene_next = edges.get_eneL(pos + 1);
auto id = ene_next.get_unique_id();
ene_next.refresh(ene_curr, state.get_mps_site(pos), model.get_mpo(pos));
if(id != ene_next.get_unique_id()) ene_pos_log.emplace_back(ene_next.get_position());
}
if(not ene_pos_log.empty()) tools::log->debug("Rebuilt L ene edges: {}", ene_pos_log);
ene_pos_log.clear();
tools::log->trace("Inspecting edges eneR from [{} to {}]", posR_active,max_pos);
for(size_t pos = max_pos; pos >= posR_active and pos < state.get_length(); pos--) {
auto &ene_curr = edges.get_eneR(pos);
if(pos == state.get_length() - 1 and not ene_curr.has_block()){
ene_pos_log.emplace_back(pos);
ene_curr.set_edge_dims(state.get_mps_site(pos), model.get_mpo(pos));
// state.set_edge_ene_status(pos,EdgeStatus::FRESH);
}
if(pos <= std::max(posR_active,0ul)) continue;
auto &ene_prev = edges.get_eneR(pos - 1);
auto id = ene_prev.get_unique_id();
ene_prev.refresh(ene_curr, state.get_mps_site(pos), model.get_mpo(pos));
if(id != ene_prev.get_unique_id()) ene_pos_log.emplace_back(ene_prev.get_position());
}
std::reverse(ene_pos_log.begin(), ene_pos_log.end());
if(not ene_pos_log.empty()) tools::log->debug("Rebuilt R ene edges: {}", ene_pos_log);
if(not edges.get_eneL(posL_active).has_block()) throw std::logic_error(fmt::format("Left active ene edge has undefined block"));
if(not edges.get_eneR(posR_active).has_block()) throw std::logic_error(fmt::format("Right active ene edge has undefined block"));
tools::common::profile::get_default_prof()["t_env"]->toc();
}
void tools::finite::env::rebuild_edges_var(const class_state_finite &state, const class_model_finite &model, class_edges_finite &edges) {
if(not num::all_equal(state.get_length(), model.get_length(), edges.get_length()))
throw std::runtime_error(
fmt::format("All lengths not equal: state {} | model {} | edges {}", state.get_length(), model.get_length(), edges.get_length()));
if(not num::all_equal(state.active_sites, model.active_sites, edges.active_sites))
throw std::runtime_error(
fmt::format("All active sites are not equal: state {} | model {} | edges {}", state.active_sites, model.active_sites, edges.active_sites));
tools::common::profile::get_default_prof()["t_env"]->tic();
size_t min_pos = 0;
size_t max_pos = state.get_length() - 1;
// If there are no active sites then we can build up until current position
// Otherwise it's enough to build up until the bracket defined by active_sites
long current_position = state.get_position<long>();
size_t posL_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
size_t posR_active = static_cast<size_t>(std::clamp<long>(current_position,0, state.get_length<long>()-1));
if(not edges.active_sites.empty()) {
posL_active = edges.active_sites.front();
posR_active = edges.active_sites.back();
}
tools::log->trace("Inspecting edges varL from [{} to {}]", min_pos,posL_active);
std::vector<size_t> var_pos_log;
for(size_t pos = min_pos; pos <= posL_active; pos++) {
auto &var_curr = edges.get_varL(pos);
if(pos == 0 and not var_curr.has_block()){
tools::log->trace("Edge not found at pos {}, has_block: {}", var_curr.get_position(), var_curr.has_block());
var_pos_log.emplace_back(pos);
var_curr.set_edge_dims(state.get_mps_site(pos), model.get_mpo(pos));
if(not var_curr.has_block()) throw std::runtime_error("No edge detected after setting edge");
}
if(pos >= std::min(posL_active,state.get_length()-1)) continue;
auto &var_next = edges.get_varL(pos + 1);
auto id = var_next.get_unique_id();
var_next.refresh(var_curr, state.get_mps_site(pos), model.get_mpo(pos));
if(id != var_next.get_unique_id()) var_pos_log.emplace_back(var_next.get_position());
}
if(not var_pos_log.empty()) tools::log->debug("Rebuilt L var edges: {}", var_pos_log);
var_pos_log.clear();
tools::log->trace("Inspecting edges varR from [{} to {}]", posR_active,max_pos);
for(size_t pos = max_pos; pos >= posR_active and pos < state.get_length(); pos--) {
auto &var_curr = edges.get_varR(pos);
if(pos == state.get_length() - 1 and not var_curr.has_block()){
var_pos_log.emplace_back(pos);
var_curr.set_edge_dims(state.get_mps_site(pos), model.get_mpo(pos));
}
if(pos <= std::max(posR_active,0ul)) continue;
auto &var_prev = edges.get_varR(pos - 1);
auto id = var_prev.get_unique_id();
var_prev.refresh(var_curr,state.get_mps_site(pos), model.get_mpo(pos));
if(id != var_prev.get_unique_id()) var_pos_log.emplace_back(var_prev.get_position());
}
std::reverse(var_pos_log.begin(), var_pos_log.end());
if(not var_pos_log.empty()) tools::log->debug("Rebuilt R var edges: {}", var_pos_log);
if(not edges.get_varL(posL_active).has_block()) throw std::logic_error(fmt::format("Left active var edge has undefined block"));
if(not edges.get_varR(posR_active).has_block()) throw std::logic_error(fmt::format("Right active var edge has undefined block"));
tools::common::profile::get_default_prof()["t_env"]->toc();
}
void tools::finite::env::rebuild_edges(const class_state_finite &state, const class_model_finite &model, class_edges_finite &edges) {
rebuild_edges_ene(state,model,edges);
rebuild_edges_var(state,model,edges);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: npwrap.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2005-06-21 10:31:46 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <errno.h>
#include <dlfcn.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <plugin/unx/plugcon.hxx>
PluginConnector* pConnector = NULL;
int nAppArguments = 0;
char** pAppArguments = NULL;
Display* pAppDisplay = NULL;
extern void* pPluginLib;
extern NPError (*pNP_Shutdown)();
void LoadAdditionalLibs(const char*);
XtAppContext app_context;
Widget topLevel = NULL, topBox = NULL;
int wakeup_fd[2] = { 0, 0 };
static bool bPluginAppQuit = false;
static long GlobalConnectionLostHdl( void* pInst, void* pArg )
{
medDebug( 1, "pluginapp exiting due to connection lost\n" );
write( wakeup_fd[1], "xxxx", 4 );
return 0;
}
extern "C"
{
static int plugin_x_error_handler( Display*, XErrorEvent* )
{
return 0;
}
static void ThreadEventHandler( XtPointer client_data, int* source, XtInputId* id )
{
char buf[256];
// clear pipe
int len, nLast = -1;
while( (len = read( wakeup_fd[0], buf, sizeof( buf ) ) ) > 0 )
nLast = len-1;
if( ! bPluginAppQuit )
{
if( ( nLast == -1 || buf[nLast] != 'x' ) && pConnector )
pConnector->CallWorkHandler();
else
{
// it seems you can use XtRemoveInput only
// safely from within the callback
// why is that ?
medDebug( 1, "removing wakeup pipe\n" );
XtRemoveInput( *id );
XtAppSetExitFlag( app_context );
bPluginAppQuit = true;
delete pConnector;
pConnector = NULL;
}
}
}
}
IMPL_LINK( PluginConnector, NewMessageHdl, Mediator*, pMediator )
{
medDebug( 1, "new message handler\n" );
write( wakeup_fd[1], "cccc", 4 );
return 0;
}
Widget createSubWidget( char* pPluginText, Widget shell, XLIB_Window aParentWindow )
{
Widget newWidget = XtVaCreateManagedWidget(
#if defined USE_MOTIF
"drawingArea",
xmDrawingAreaWidgetClass,
#else
"",
labelWidgetClass,
#endif
shell,
XtNwidth, 200,
XtNheight, 200,
(char *)NULL );
XtRealizeWidget( shell );
medDebug( 1, "Reparenting new widget %x to %x\n", XtWindow( newWidget ), aParentWindow );
XReparentWindow( pAppDisplay,
XtWindow( shell ),
aParentWindow,
0, 0 );
XtMapWidget( shell );
XtMapWidget( newWidget );
XRaiseWindow( pAppDisplay, XtWindow( shell ) );
XSync( pAppDisplay, False );
return newWidget;
}
void* CreateNewShell( void** pShellReturn, XLIB_Window aParentWindow )
{
XLIB_String n, c;
XtGetApplicationNameAndClass(pAppDisplay, &n, &c);
Widget newShell =
XtVaAppCreateShell( "pane", c,
topLevelShellWidgetClass,
pAppDisplay,
XtNwidth, 200,
XtNheight, 200,
XtNoverrideRedirect, True,
(char *)NULL );
*pShellReturn = newShell;
char pText[1024];
sprintf( pText, "starting plugin %s ...", pAppArguments[2] );
Widget newWidget = createSubWidget( pText, newShell, aParentWindow );
return newWidget;
}
// Unix specific implementation
static void CheckPlugin( const char* pPath )
{
rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();
void *pLib = dlopen( pPath, RTLD_LAZY );
if( ! pLib )
{
medDebug( 1, "could not dlopen( %s ) (%s)\n", pPath, dlerror() );
return;
}
char*(*pNP_GetMIMEDescription)() = (char*(*)())
dlsym( pLib, "NP_GetMIMEDescription" );
if( pNP_GetMIMEDescription )
printf( "%s\n", pNP_GetMIMEDescription() );
else
medDebug( 1, "could not dlsym NP_GetMIMEDescription (%s)\n", dlerror() );
dlclose( pLib );
}
#if OSL_DEBUG_LEVEL > 1 && defined LINUX
#include <execinfo.h>
#endif
extern "C" {
static void signal_handler( int nSig )
{
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "caught signal %d, exiting\n", nSig );
#ifdef LINUX
void* pStack[64];
int nStackLevels = backtrace( pStack, sizeof(pStack)/sizeof(pStack[0]) );
backtrace_symbols_fd( pStack, nStackLevels, STDERR_FILENO );
#endif
#endif
if( pConnector )
{
// ensure that a read on the other side will wakeup
delete pConnector;
pConnector = NULL;
}
_exit(nSig);
}
}
int main( int argc, char **argv)
{
struct sigaction aSigAction;
aSigAction.sa_handler = signal_handler;
sigemptyset( &aSigAction.sa_mask );
aSigAction.sa_flags = SA_NOCLDSTOP;
sigaction( SIGSEGV, &aSigAction, NULL );
sigaction( SIGBUS, &aSigAction, NULL );
sigaction( SIGABRT, &aSigAction, NULL );
sigaction( SIGTERM, &aSigAction, NULL );
sigaction( SIGILL, &aSigAction, NULL );
int nArg = (argc < 3) ? 1 : 2;
char* pBaseName = argv[nArg] + strlen(argv[nArg]);
while( pBaseName > argv[nArg] && pBaseName[-1] != '/' )
pBaseName--;
LoadAdditionalLibs( pBaseName );
if( argc < 3 )
{
CheckPlugin(argv[1]);
exit(0);
}
nAppArguments = argc;
pAppArguments = argv;
XSetErrorHandler( plugin_x_error_handler );
if( pipe( wakeup_fd ) )
{
medDebug( 1, "could not pipe()\n" );
return 1;
}
// initialize 'wakeup' pipe.
int flags;
// set close-on-exec descriptor flag.
if ((flags = fcntl (wakeup_fd[0], F_GETFD)) != -1)
{
flags |= FD_CLOEXEC;
fcntl (wakeup_fd[0], F_SETFD, flags);
}
if ((flags = fcntl (wakeup_fd[1], F_GETFD)) != -1)
{
flags |= FD_CLOEXEC;
fcntl (wakeup_fd[1], F_SETFD, flags);
}
// set non-blocking I/O flag.
if ((flags = fcntl (wakeup_fd[0], F_GETFL)) != -1)
{
flags |= O_NONBLOCK;
fcntl (wakeup_fd[0], F_SETFL, flags);
}
if ((flags = fcntl (wakeup_fd[1], F_GETFL)) != -1)
{
flags |= O_NONBLOCK;
fcntl (wakeup_fd[1], F_SETFL, flags);
}
pPluginLib = dlopen( argv[2], RTLD_LAZY );
if( ! pPluginLib )
{
medDebug( 1, "dlopen on %s failed because of:\n\t%s\n",
argv[2], dlerror() );
exit(255);
}
int nSocket = atol( argv[1] );
pConnector = new PluginConnector( nSocket );
pConnector->SetConnectionLostHdl( Link( NULL, GlobalConnectionLostHdl ) );
XtSetLanguageProc( NULL, NULL, NULL );
topLevel = XtVaOpenApplication(
&app_context, /* Application context */
"SOPlugin", /* Application class */
NULL, 0, /* command line option list */
&argc, argv, /* command line args */
NULL, /* for missing app-defaults file */
topLevelShellWidgetClass,
XtNoverrideRedirect, True,
(char *)NULL); /* terminate varargs list */
pAppDisplay = XtDisplay( topLevel );
XtAppAddInput( app_context,
wakeup_fd[0],
(XtPointer)XtInputReadMask,
ThreadEventHandler, NULL );
/*
* Create windows for widgets and map them.
*/
INT32 nWindow;
sscanf( argv[3], "%d", &nWindow );
char pText[1024];
sprintf( pText, "starting plugin %s ...", pAppArguments[2] );
topBox = createSubWidget( pText, topLevel, (XLIB_Window)nWindow );
// send that we are ready to go
MediatorMessage* pMessage =
pConnector->Transact( "init req", 8,
NULL );
delete pMessage;
#if OSL_DEBUG_LEVEL > 3
int nPID = getpid();
int nChild = fork();
if( nChild == 0 )
{
char pidbuf[16];
char* pArgs[] = { "xterm", "-sl", "2000", "-sb", "-e", "gdb", "pluginapp.bin", pidbuf, NULL };
sprintf( pidbuf, "%d", nPID );
execvp( pArgs[0], pArgs );
_exit(255);
}
else
sleep( 10 );
#endif
/*
* Loop for events.
*/
// for some reason XtAppSetExitFlag won't quit the application
// in ThreadEventHandler most of times; Xt will hang in select
// (hat is in XtAppNextEvent). Have our own mainloop instead
// of XtAppMainLoop
do
{
XtAppProcessEvent( app_context, XtIMAll );
} while( ! XtAppGetExitFlag( app_context ) && ! bPluginAppQuit );
medDebug( 1, "left plugin app main loop\n" );
pNP_Shutdown();
medDebug( 1, "NP_Shutdown done\n" );
dlclose( pPluginLib );
medDebug( 1, "plugin close\n" );
close( wakeup_fd[0] );
close( wakeup_fd[1] );
return 0;
}
#ifdef GCC
extern "C" {
void __pure_virtual()
{}
void* __builtin_new( int nBytes )
{ return malloc(nBytes); }
void* __builtin_vec_new( int nBytes )
{ return malloc(nBytes); }
void __builtin_delete( char* pMem )
{ free(pMem); }
void __builtin_vec_delete( char* pMem )
{ free(pMem); }
}
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.11.64); FILE MERGED 2005/09/05 12:59:50 rt 1.11.64.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: npwrap.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-09-08 19:56:16 $
*
* 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 <errno.h>
#include <dlfcn.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <plugin/unx/plugcon.hxx>
PluginConnector* pConnector = NULL;
int nAppArguments = 0;
char** pAppArguments = NULL;
Display* pAppDisplay = NULL;
extern void* pPluginLib;
extern NPError (*pNP_Shutdown)();
void LoadAdditionalLibs(const char*);
XtAppContext app_context;
Widget topLevel = NULL, topBox = NULL;
int wakeup_fd[2] = { 0, 0 };
static bool bPluginAppQuit = false;
static long GlobalConnectionLostHdl( void* pInst, void* pArg )
{
medDebug( 1, "pluginapp exiting due to connection lost\n" );
write( wakeup_fd[1], "xxxx", 4 );
return 0;
}
extern "C"
{
static int plugin_x_error_handler( Display*, XErrorEvent* )
{
return 0;
}
static void ThreadEventHandler( XtPointer client_data, int* source, XtInputId* id )
{
char buf[256];
// clear pipe
int len, nLast = -1;
while( (len = read( wakeup_fd[0], buf, sizeof( buf ) ) ) > 0 )
nLast = len-1;
if( ! bPluginAppQuit )
{
if( ( nLast == -1 || buf[nLast] != 'x' ) && pConnector )
pConnector->CallWorkHandler();
else
{
// it seems you can use XtRemoveInput only
// safely from within the callback
// why is that ?
medDebug( 1, "removing wakeup pipe\n" );
XtRemoveInput( *id );
XtAppSetExitFlag( app_context );
bPluginAppQuit = true;
delete pConnector;
pConnector = NULL;
}
}
}
}
IMPL_LINK( PluginConnector, NewMessageHdl, Mediator*, pMediator )
{
medDebug( 1, "new message handler\n" );
write( wakeup_fd[1], "cccc", 4 );
return 0;
}
Widget createSubWidget( char* pPluginText, Widget shell, XLIB_Window aParentWindow )
{
Widget newWidget = XtVaCreateManagedWidget(
#if defined USE_MOTIF
"drawingArea",
xmDrawingAreaWidgetClass,
#else
"",
labelWidgetClass,
#endif
shell,
XtNwidth, 200,
XtNheight, 200,
(char *)NULL );
XtRealizeWidget( shell );
medDebug( 1, "Reparenting new widget %x to %x\n", XtWindow( newWidget ), aParentWindow );
XReparentWindow( pAppDisplay,
XtWindow( shell ),
aParentWindow,
0, 0 );
XtMapWidget( shell );
XtMapWidget( newWidget );
XRaiseWindow( pAppDisplay, XtWindow( shell ) );
XSync( pAppDisplay, False );
return newWidget;
}
void* CreateNewShell( void** pShellReturn, XLIB_Window aParentWindow )
{
XLIB_String n, c;
XtGetApplicationNameAndClass(pAppDisplay, &n, &c);
Widget newShell =
XtVaAppCreateShell( "pane", c,
topLevelShellWidgetClass,
pAppDisplay,
XtNwidth, 200,
XtNheight, 200,
XtNoverrideRedirect, True,
(char *)NULL );
*pShellReturn = newShell;
char pText[1024];
sprintf( pText, "starting plugin %s ...", pAppArguments[2] );
Widget newWidget = createSubWidget( pText, newShell, aParentWindow );
return newWidget;
}
// Unix specific implementation
static void CheckPlugin( const char* pPath )
{
rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();
void *pLib = dlopen( pPath, RTLD_LAZY );
if( ! pLib )
{
medDebug( 1, "could not dlopen( %s ) (%s)\n", pPath, dlerror() );
return;
}
char*(*pNP_GetMIMEDescription)() = (char*(*)())
dlsym( pLib, "NP_GetMIMEDescription" );
if( pNP_GetMIMEDescription )
printf( "%s\n", pNP_GetMIMEDescription() );
else
medDebug( 1, "could not dlsym NP_GetMIMEDescription (%s)\n", dlerror() );
dlclose( pLib );
}
#if OSL_DEBUG_LEVEL > 1 && defined LINUX
#include <execinfo.h>
#endif
extern "C" {
static void signal_handler( int nSig )
{
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "caught signal %d, exiting\n", nSig );
#ifdef LINUX
void* pStack[64];
int nStackLevels = backtrace( pStack, sizeof(pStack)/sizeof(pStack[0]) );
backtrace_symbols_fd( pStack, nStackLevels, STDERR_FILENO );
#endif
#endif
if( pConnector )
{
// ensure that a read on the other side will wakeup
delete pConnector;
pConnector = NULL;
}
_exit(nSig);
}
}
int main( int argc, char **argv)
{
struct sigaction aSigAction;
aSigAction.sa_handler = signal_handler;
sigemptyset( &aSigAction.sa_mask );
aSigAction.sa_flags = SA_NOCLDSTOP;
sigaction( SIGSEGV, &aSigAction, NULL );
sigaction( SIGBUS, &aSigAction, NULL );
sigaction( SIGABRT, &aSigAction, NULL );
sigaction( SIGTERM, &aSigAction, NULL );
sigaction( SIGILL, &aSigAction, NULL );
int nArg = (argc < 3) ? 1 : 2;
char* pBaseName = argv[nArg] + strlen(argv[nArg]);
while( pBaseName > argv[nArg] && pBaseName[-1] != '/' )
pBaseName--;
LoadAdditionalLibs( pBaseName );
if( argc < 3 )
{
CheckPlugin(argv[1]);
exit(0);
}
nAppArguments = argc;
pAppArguments = argv;
XSetErrorHandler( plugin_x_error_handler );
if( pipe( wakeup_fd ) )
{
medDebug( 1, "could not pipe()\n" );
return 1;
}
// initialize 'wakeup' pipe.
int flags;
// set close-on-exec descriptor flag.
if ((flags = fcntl (wakeup_fd[0], F_GETFD)) != -1)
{
flags |= FD_CLOEXEC;
fcntl (wakeup_fd[0], F_SETFD, flags);
}
if ((flags = fcntl (wakeup_fd[1], F_GETFD)) != -1)
{
flags |= FD_CLOEXEC;
fcntl (wakeup_fd[1], F_SETFD, flags);
}
// set non-blocking I/O flag.
if ((flags = fcntl (wakeup_fd[0], F_GETFL)) != -1)
{
flags |= O_NONBLOCK;
fcntl (wakeup_fd[0], F_SETFL, flags);
}
if ((flags = fcntl (wakeup_fd[1], F_GETFL)) != -1)
{
flags |= O_NONBLOCK;
fcntl (wakeup_fd[1], F_SETFL, flags);
}
pPluginLib = dlopen( argv[2], RTLD_LAZY );
if( ! pPluginLib )
{
medDebug( 1, "dlopen on %s failed because of:\n\t%s\n",
argv[2], dlerror() );
exit(255);
}
int nSocket = atol( argv[1] );
pConnector = new PluginConnector( nSocket );
pConnector->SetConnectionLostHdl( Link( NULL, GlobalConnectionLostHdl ) );
XtSetLanguageProc( NULL, NULL, NULL );
topLevel = XtVaOpenApplication(
&app_context, /* Application context */
"SOPlugin", /* Application class */
NULL, 0, /* command line option list */
&argc, argv, /* command line args */
NULL, /* for missing app-defaults file */
topLevelShellWidgetClass,
XtNoverrideRedirect, True,
(char *)NULL); /* terminate varargs list */
pAppDisplay = XtDisplay( topLevel );
XtAppAddInput( app_context,
wakeup_fd[0],
(XtPointer)XtInputReadMask,
ThreadEventHandler, NULL );
/*
* Create windows for widgets and map them.
*/
INT32 nWindow;
sscanf( argv[3], "%d", &nWindow );
char pText[1024];
sprintf( pText, "starting plugin %s ...", pAppArguments[2] );
topBox = createSubWidget( pText, topLevel, (XLIB_Window)nWindow );
// send that we are ready to go
MediatorMessage* pMessage =
pConnector->Transact( "init req", 8,
NULL );
delete pMessage;
#if OSL_DEBUG_LEVEL > 3
int nPID = getpid();
int nChild = fork();
if( nChild == 0 )
{
char pidbuf[16];
char* pArgs[] = { "xterm", "-sl", "2000", "-sb", "-e", "gdb", "pluginapp.bin", pidbuf, NULL };
sprintf( pidbuf, "%d", nPID );
execvp( pArgs[0], pArgs );
_exit(255);
}
else
sleep( 10 );
#endif
/*
* Loop for events.
*/
// for some reason XtAppSetExitFlag won't quit the application
// in ThreadEventHandler most of times; Xt will hang in select
// (hat is in XtAppNextEvent). Have our own mainloop instead
// of XtAppMainLoop
do
{
XtAppProcessEvent( app_context, XtIMAll );
} while( ! XtAppGetExitFlag( app_context ) && ! bPluginAppQuit );
medDebug( 1, "left plugin app main loop\n" );
pNP_Shutdown();
medDebug( 1, "NP_Shutdown done\n" );
dlclose( pPluginLib );
medDebug( 1, "plugin close\n" );
close( wakeup_fd[0] );
close( wakeup_fd[1] );
return 0;
}
#ifdef GCC
extern "C" {
void __pure_virtual()
{}
void* __builtin_new( int nBytes )
{ return malloc(nBytes); }
void* __builtin_vec_new( int nBytes )
{ return malloc(nBytes); }
void __builtin_delete( char* pMem )
{ free(pMem); }
void __builtin_vec_delete( char* pMem )
{ free(pMem); }
}
#endif
<|endoftext|>
|
<commit_before>/*!
* @file File game.cpp
* @brief Implementation of the class of game actions
*
* The class implemented provides the flow of the game
*
* @sa game.hpp
*/
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_ttf.h>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <functional>
#include <map>
#include <vector>
#include <game.hpp>
#include <gameException.hpp>
#include <inputManager.hpp>
#include <resources.hpp>
#include <state.hpp>
Game* Game::instance = NULL;
/*!
@fn Game::Game(string title,int width,int height):frameStart{0},dt{0},winSize{(float)width,(float)height}
@brief This is a constructor
@param title
@param width
@param height
@warning Method that requires review of comment
*/
Game::Game(string title,int width,int height):frameStart{0},deltatime{0},windowSize{(float)width,(float)height} {
srand(time(NULL));
if (instance) {
cerr << "Erro, mais de uma instancia de 'Game' instanciada, o programa ira encerrar agora" << endl;
exit(EXIT_FAILURE);
}
instance=this;
bool success = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) == 0;
if (!success) {
string error_msg(error_messege = SDL_GetError());
error_messege = "Could not initialize SDL:\n" + error_messege;
throw GameException(error_messege);
}
// Initialize image module and check if process went OK
map<int, string> code_name_map = {{IMAGE_INIT_TIF, "tif"},
{IMAGE_INIT_JPG, "jpg"},
{IMAGE_INIT_PNG, "png"}};
vector<int> image_formats{IMAGE_INIT_TIF, IMAGE_INIT_JPG, IMAGE_INIT_PNG};
// Initialize image module or between all desired formats
int image_settings = accumulate(image_formats.begin(),
image_formats.end(),
0,
[](const int &a, const int &b) {
return a | b;
}
);
int res = IMAGE_Init(image_settings);
/* Check the possibility initialize image library and return the error messege
for ever type
*/
if (image_settings != res) {
string error_messege_main = SDL_GetError();
string error_messege = "Could not initiazlie image libary for type:";
for (auto format : image_formats)
if ((format & res) == 0) {
error_messege += code_name_map[format];
}
error_messege += "\n";
error_messege = error_messege_main + error_messege;
throw GameException(error_messege);
}
int audio_modules = MIX_INIT_OGG;
res = Mix_Init(audio_modules);
/* Check the possibility initiation of SDL audio and return a error messege
if its necessary
*/
if (res != audio_modules) {
if ((MIX_INIT_OGG & res ) == 0 )cerr << "OGG flag not in res!" << endl;
if ((MIX_INIT_MP3 & res ) == 0 )cerr << "MP3 flag not in res!" << endl;
throw GameException("Problem when initiating SDL audio!");
}
res = Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024);
if (res != 0)throw GameException("Problem when initiating SDL audio!");
res = TTF_Init();
if (res != 0)cerr << "Could not initialize TTF module!" << endl;
// Creating the window that will contain the game interface
window = SDL_CreateWindow(title.c_str(),SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,width,height,SDL_WINDOW_FULLSCREEN);
if (!window)throw GameException("Window nao foi carregada)!");
renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED);
if (!renderer)throw GameException("Erro ao instanciar renderizador da SDL!");
storedState = nullptr;
SDL_SetRenderDrawBlendMode(GAMERENDER, SDL_BLENDMODE_BLEND);
};
/*!
@fn Game::~Game()
@brief This is a destructor
@warning Method that requires review of comment
*/
Game::~Game() {
while (stateStack.size()) {
delete stateStack.top().get();
stateStack.pop();
}
if (storedState)delete storedState;
Resources::ClearImages();
Resources::ClearMusics();
Resources::ClearFonts();
TTF_Quit();
Mix_CloseAudio();
Mix_Quit();
IMAGE_Quit();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
/*!
@fn Game& Game::GetInstance()
@brief Create a instance of class Game
@return Returns a instance of Game
@warning Method that requires review of comment
*/
Game& Game::GetInstance() {
return (*instance);
}
/*!
@fn State& Game::GetCurrentState()
@brief Verify the current object state
@return state
@warning Method that requires review of comment
*/
State& Game::GetCurrentState() {
return (*stateStack.top());
}
/*!
@fn void Game::Run()
@brief
@param
@return
@warning Method that requires review of comment
*/
SDL_Renderer* Game::GetRenderer() {
return renderer;
}
/*!
@fn void Game::Push(State* state)
@brief Swapping the object state
@param state
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void Game::Push(State* state) {
if (storedState)delete storedState;
storedState=state;
}
/*!
@fn void Game::Run()
@brief
@param
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void Game::Run() {
if (storedState) {
stateStack.push(unique_ptr<State>(storedState));
storedState=nullptr;
GetCurrentState().Begin();
}
while (!stateStack.empty()) {
CalculateDeltaTime();
INPUT.update(deltatime);
//if (INPUT.KeyPress(KEY_F(11))) SwitchWindowMode();
GetCurrentState().update(deltatime);
GetCurrentState().render();
SDL_RenderPresent(renderer);
if (GetCurrentState().QuitRequested()) {
break;
}
if (GetCurrentState().PopRequested()) {
GetCurrentState().Pause();
GetCurrentState().End();
stateStack.pop();
Resources::ClearImages();
Resources::ClearMusics();
Resources::ClearFonts();
if (stateStack.size()) {
GetCurrentState().Resume();
}
}
if (storedState) {
GetCurrentState().Pause();
stateStack.push(unique_ptr<State>(storedState));
storedState=nullptr;
GetCurrentState().Begin();
}
SDL_Delay(17);
}
while (stateStack.size()) {
GetCurrentState().End();
stateStack.pop();
}
}
float Game::GetDeltaTime() {
return deltatime;
}
/*!
@fn void Game::CalculateDeltaTime()
@brief
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void Game::CalculateDeltaTime() {
unsigned int tmp = frameStart;
frameStart = SDL_GetTicks();
deltatime = max((frameStart - tmp) / 1000.0, 0.001);
}
/*!
@fn void Game::SwitchWindowMode()
@brief
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void Game::SwitchWindowMode() {
// Method body its empty
}
<commit_msg>Appling stylesheet in game.cpp<commit_after>/*!
* @file File game.cpp
* @brief Implementation of the class of game actions
*
* The class implemented provides the flow of the game
*
* @sa game.hpp
*/
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_ttf.h>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <functional>
#include <map>
#include <vector>
#include <game.hpp>
#include <gameException.hpp>
#include <inputManager.hpp>
#include <resources.hpp>
#include <state.hpp>
Game* Game::instance = NULL;
/*!
@fn Game::Game(string title,int width,int height):frameStart{0},dt{0},winSize{(float)width,(float)height}
@brief This is a constructor
@param title
@param width
@param height
@warning Method that requires review of comment
*/
Game::Game(string title, int width, int height):frameStart{0},deltatime{0},windowSize{(float)width,(float)height} {
srand(time(NULL));
if (instance) {
cerr << "Erro, mais de uma instancia de 'Game' instanciada, o programa ira encerrar agora" << endl;
exit(EXIT_FAILURE);
}
instance = this;
bool success = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) == 0;
if (!success) {
string error_msg(error_messege = SDL_GetError());
error_messege = "Could not initialize SDL:\n" + error_messege;
throw GameException(error_messege);
}
// Initialize image module and check if process went OK
map<int, string> code_name_map = {{IMAGE_INIT_TIF, "tif"},
{IMAGE_INIT_JPG, "jpg"},
{IMAGE_INIT_PNG, "png"}};
vector<int> image_formats{IMAGE_INIT_TIF, IMAGE_INIT_JPG, IMAGE_INIT_PNG};
// Initialize image module or between all desired formats
int image_settings = accumulate(image_formats.begin(),
image_formats.end(),
0,
[](const int &a, const int &b) {
return a | b;
}
);
int res = IMAGE_Init(image_settings);
/* Check the possibility initialize image library and return the error messege
for ever type
*/
if (image_settings != res) {
string error_messege_main = SDL_GetError();
string error_messege = "Could not initiazlie image libary for type:";
for (auto format : image_formats)
if ((format & res) == 0) {
error_messege += code_name_map[format];
}
error_messege += "\n";
error_messege = error_messege_main + error_messege;
throw GameException(error_messege);
}
int audio_modules = MIX_INIT_OGG;
res = Mix_Init(audio_modules);
/* Check the possibility initiation of SDL audio and return a error messege
if its necessary
*/
if (res != audio_modules) {
if ((MIX_INIT_OGG & res ) == 0 )cerr << "OGG flag not in res!" << endl;
if ((MIX_INIT_MP3 & res ) == 0 )cerr << "MP3 flag not in res!" << endl;
throw GameException("Problem when initiating SDL audio!");
}
res = Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024);
if (res != 0)throw GameException("Problem when initiating SDL audio!");
res = TTF_Init();
if (res != 0)cerr << "Could not initialize TTF module!" << endl;
// Creating the window that will contain the game interface
window = SDL_CreateWindow(title.c_str(),SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,width,height,SDL_WINDOW_FULLSCREEN);
if (!window){
throw GameException("Window nao foi carregada)!");
}
renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED);
if (!renderer){
throw GameException("Erro ao instanciar renderizador da SDL!");
}
storedState = nullptr;
SDL_SetRenderDrawBlendMode(GAMERENDER, SDL_BLENDMODE_BLEND);
};
/*!
@fn Game::~Game()
@brief This is a destructor
@warning Method that requires review of comment
*/
Game::~Game() {
while (stateStack.size()) {
delete stateStack.top().get();
stateStack.pop();
}
if (storedState) {
delete storedState;
}
Resources::ClearImages();
Resources::ClearMusics();
Resources::ClearFonts();
TTF_Quit();
Mix_CloseAudio();
Mix_Quit();
IMAGE_Quit();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
/*!
@fn Game& Game::GetInstance()
@brief Create a instance of class Game
@return Returns a instance of Game
@warning Method that requires review of comment
*/
Game& Game::GetInstance() {
return (*instance);
}
/*!
@fn State& Game::GetCurrentState()
@brief Verify the current object state
@return state
@warning Method that requires review of comment
*/
State& Game::GetCurrentState() {
return (*stateStack.top());
}
/*!
@fn void Game::Run()
@brief
@param
@return
@warning Method that requires review of comment
*/
SDL_Renderer* Game::GetRenderer() {
return renderer;
}
/*!
@fn void Game::Push(State* state)
@brief Swapping the object state
@param state
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void Game::Push(State* state) {
if (storedState)delete storedState;
storedState=state;
}
/*!
@fn void Game::Run()
@brief
@param
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void Game::Run() {
if (storedState) {
stateStack.push(unique_ptr<State>(storedState));
storedState=nullptr;
GetCurrentState().Begin();
}
while (!stateStack.empty()) {
CalculateDeltaTime();
INPUT.update(deltatime);
//if (INPUT.KeyPress(KEY_F(11))) SwitchWindowMode();
GetCurrentState().update(deltatime);
GetCurrentState().render();
SDL_RenderPresent(renderer);
if (GetCurrentState().QuitRequested()) {
break;
}
if (GetCurrentState().PopRequested()) {
GetCurrentState().Pause();
GetCurrentState().End();
stateStack.pop();
Resources::ClearImages();
Resources::ClearMusics();
Resources::ClearFonts();
if (stateStack.size()) {
GetCurrentState().Resume();
}
}
if (storedState) {
GetCurrentState().Pause();
stateStack.push(unique_ptr<State>(storedState));
storedState=nullptr;
GetCurrentState().Begin();
}
SDL_Delay(17);
}
while (stateStack.size()) {
GetCurrentState().End();
stateStack.pop();
}
}
float Game::GetDeltaTime() {
return deltatime;
}
/*!
@fn void Game::CalculateDeltaTime()
@brief
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void Game::CalculateDeltaTime() {
unsigned int tmp = frameStart;
frameStart = SDL_GetTicks();
deltatime = max((frameStart - tmp) / 1000.0, 0.001);
}
/*!
@fn void Game::SwitchWindowMode()
@brief
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void Game::SwitchWindowMode() {
// Method body its empty
}
<|endoftext|>
|
<commit_before>#include "game.h"
namespace Game {
sdl_info::sdl_info(const char* game_name, std::string font_name, int fps_param) {
window = SDL_CreateWindow(game_name, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN_DESKTOP);
if (window == NULL) { throw SDLError(); }
win_renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED );
if (fps_param > 0) fps = fps_param;
fonts[Small] = TTF_OpenFont(font_name.c_str(), 20);
fonts[Normal] = TTF_OpenFont(font_name.c_str(), 24);
fonts[Huge] = TTF_OpenFont(font_name.c_str(), 32);
if (fonts[Small] == NULL || fonts[Normal] == NULL || fonts[Huge] == NULL) {
throw SDLError("Error loading fonts");
};
gm_name = game_name;
}
sdl_info::~sdl_info() {
for (const auto& pair : txts) {
SDL_DestroyTexture(pair.second.texture);
};
SDL_DestroyWindow(window);
std::cout << "Cleaning up resources ..." << std::endl;
}
Resolution sdl_info::get_current_res() {
SDL_DisplayMode current;
SDL_GetCurrentDisplayMode(0, ¤t); // we assume nothing goes wrong..
return Resolution(current.w, current.h);
};
void sdl_info::set_background(std::string bg_name) {
music = Mix_LoadMUS(bg_name.c_str());
Mix_PlayMusic(music, -1);
Mix_VolumeMusic(MIX_MAX_VOLUME / 4);
};
void sdl_info::load_png(std::string key, std::string path) {
{
auto it = txts.find(key);
if (it != txts.end()) return;
}
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
if (loadedSurface == NULL) { throw SDLError(IMG_GetError()); }
SDL_Texture* texture = SDL_CreateTextureFromSurface(win_renderer, loadedSurface);
SDL_FreeSurface(loadedSurface);
TextureInfo &inf = txts[key];
SDL_QueryTexture(texture, NULL, NULL, &(inf.width), &(inf.height));
inf.texture = texture;
}
void sdl_info::load_sfx(std::string key, std::string path) {
sfx[key] = Mix_LoadWAV(path.c_str());
};
void sdl_info::play_sfx(std::string key) {
Mix_PlayChannel(-1, sfx[key], 0);
};
void sdl_info::render_text(int x, int y, FontID f_id, SDL_Color txt_color, std::string text) {
SDL_Rect pos;
SDL_Surface* textSurface = TTF_RenderUTF8_Solid(fonts[f_id], text.c_str(), txt_color);
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(win_renderer, textSurface);
if (textSurface == NULL) return;
pos.h = textSurface->h;
pos.w = textSurface->w;
pos.x = x;
pos.y = y;
SDL_FreeSurface(textSurface);
SDL_SetTextureBlendMode(textTexture, SDL_BLENDMODE_BLEND);
SDL_RenderCopy(win_renderer, textTexture, NULL, &pos);
SDL_DestroyTexture(textTexture);
};
}<commit_msg>add clean up of sfx/music/ttf<commit_after>#include "game.h"
namespace Game {
sdl_info::sdl_info(const char* game_name, std::string font_name, int fps_param) {
window = SDL_CreateWindow(game_name, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN_DESKTOP);
if (window == NULL) { throw SDLError(); }
win_renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED );
if (fps_param > 0) fps = fps_param;
fonts[Small] = TTF_OpenFont(font_name.c_str(), 20);
fonts[Normal] = TTF_OpenFont(font_name.c_str(), 24);
fonts[Huge] = TTF_OpenFont(font_name.c_str(), 32);
if (fonts[Small] == NULL || fonts[Normal] == NULL || fonts[Huge] == NULL) {
throw SDLError("Error loading fonts");
};
gm_name = game_name;
}
sdl_info::~sdl_info() {
for (const auto& pair : txts) {
SDL_DestroyTexture(pair.second.texture);
};
for (const auto& pair : sfx) {
Mix_FreeChunk(pair.second);
};
Mix_FreeMusic(music);
for (const auto& pair : fonts) {
TTF_CloseFont(pair.second);
};
SDL_DestroyWindow(window);
std::cout << "Cleaning up resources ..." << std::endl;
}
Resolution sdl_info::get_current_res() {
SDL_DisplayMode current;
SDL_GetCurrentDisplayMode(0, ¤t); // we assume nothing goes wrong..
return Resolution(current.w, current.h);
};
void sdl_info::set_background(std::string bg_name) {
music = Mix_LoadMUS(bg_name.c_str());
Mix_PlayMusic(music, -1);
Mix_VolumeMusic(MIX_MAX_VOLUME / 4);
};
void sdl_info::load_png(std::string key, std::string path) {
{
auto it = txts.find(key);
if (it != txts.end()) return;
}
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
if (loadedSurface == NULL) { throw SDLError(IMG_GetError()); }
SDL_Texture* texture = SDL_CreateTextureFromSurface(win_renderer, loadedSurface);
SDL_FreeSurface(loadedSurface);
TextureInfo &inf = txts[key];
SDL_QueryTexture(texture, NULL, NULL, &(inf.width), &(inf.height));
inf.texture = texture;
}
void sdl_info::load_sfx(std::string key, std::string path) {
sfx[key] = Mix_LoadWAV(path.c_str());
};
void sdl_info::play_sfx(std::string key) {
Mix_PlayChannel(-1, sfx[key], 0);
};
void sdl_info::render_text(int x, int y, FontID f_id, SDL_Color txt_color, std::string text) {
SDL_Rect pos;
SDL_Surface* textSurface = TTF_RenderUTF8_Solid(fonts[f_id], text.c_str(), txt_color);
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(win_renderer, textSurface);
if (textSurface == NULL) return;
pos.h = textSurface->h;
pos.w = textSurface->w;
pos.x = x;
pos.y = y;
SDL_FreeSurface(textSurface);
SDL_SetTextureBlendMode(textTexture, SDL_BLENDMODE_BLEND);
SDL_RenderCopy(win_renderer, textTexture, NULL, &pos);
SDL_DestroyTexture(textTexture);
};
}<|endoftext|>
|
<commit_before>#include "dominator.h"
/*
* TODO Is there a need to do the post dominators and strictly post dominators?
* - The algorithm to do so is the same as computing dominators but you
* look swap the exit and entry node and look at look at the "outs" of
* block rather than the ins.
*/
/*
* Computes the dominators for the set of basic blocks.
*
* This algorithm is based on the dominator computation in Advanced Compiler Design
* Implementation. While the running time is O(n^2e)for a flowgraph with n nodes and
* e edges this algorithm is probably the most efficient as the number of basic blocks
* we look at at a time is usually pretty small. There are more complex algorithms that
* can run in near linear time, but have poor performance for computations that don't
* contain at least a few hundred nodes.
*
* If a node a dominates node b then dominators[b]->get(a) will be true. That is to say that
* dominators[i] stores the set of all nodes that dominate node i
*
* This algorithm will be most efficient if the basic blocks are in a depth-first order.
*/
void computeDominators(std::vector<BitVec*>& dominators, std::vector<BasicBlock*>& basicBlocks) {
unsigned nBlocks = basicBlocks.size();
//The root node cannot be dominated
dominators[0]->set(0);
//Initially set all other nodes as dominated by every other node
for(unsigned i = 1; i < nBlocks; i++) {
dominators[i]->set();
}
//Iteratively look for changes. A node a dominates b
//if a = b, a is immediate predecessor of b, of i
//b has multiple predecessors but a dominates
//all of them.
bool changed = true;
while(changed) {
changed = false;
for(unsigned i = 1; i < nBlocks; i++) {
BitVec temp = BitVec(nBlocks);
temp.set();
BasicBlock* curBB = basicBlocks[i];
for(unsigned j = 0; j < curBB->ins.size(); j++) {
//TODO I would ideally like this to be &=
temp.intersection(*dominators[curBB->ins[j]->id]);
}
temp.set(i);
//TODO would like to implement == and !=
if(temp.equals(*dominators[i]) == false) {
changed = true;
dominators[i]->reset();
dominators[i]->disjunction(temp);
}
}
}
}
/*
* Checks if a node a dominates node b in the set of dominators
*
* A node a dominates node b if every path path from the entry node
* to node b must go through a.
*/
bool dominates(unsigned a, unsigned b, std::vector<BitVec*> & dominators) {
if(dominators[b]->test(a)) {
return true;
}
return false;
}
/*
* Checks if a node a strictly dominates node b in the set of dominators
*
* A node a strictly dominates node b if a dominates b and a!= b
*/
bool strictlyDominates(unsigned a, unsigned b, std::vector<BitVec*> & dominators) {
if(a == b) {
return false;
}
return dominates(a, b, dominators);
}
/*
* Computes the immediate dominators from the dominators
*
* This algorithm is based on the immediate dominator computation found in Advanced Compiler
* Design Implementation. It takes the already computed dominator set and set the immediate
* dominators. For instance to get the immediate dominator of i simply get
* immediate Dominators[i]
*
* A node a immediately dominates node b if and only if a strictly dominates b
* and there does not exist a node c such that a strictly dominates c and c
* strictly dominates b
*/
void computeImmediateDominators(std::vector<unsigned>& immediateDominators, std::vector<BitVec*>& dominators) {
unsigned nBlocks = dominators.size();
//Create a temporary dominator set
std::vector<BitVec*> temp;
for(unsigned i = 0; i < nBlocks; i++) {
temp.push_back(new BitVec(nBlocks));
}
//Set temp[i] to the dominators[i] - {i} (the strict dominators)
for(unsigned i = 0; i < nBlocks; i++) {
for(unsigned j = 0; j < nBlocks; j++) {
if(strictlyDominates(i, j, dominators)) {
temp[j]->set(i);
}
}
}
//For each node i check whether each node that dominates i
//has dominators other than itself and if so remove them.
//This leaves each non-root node having a single dominator
for(unsigned i = 1; i < nBlocks; i++) {
for(unsigned j = 0; j < nBlocks; j++){
for(unsigned k = 0; k < nBlocks; k++) {
if(strictlyDominates(k, i, temp) && strictlyDominates(j, i, temp)) {
if(strictlyDominates(k, j, temp)) {
temp[i]->reset(k);
}
}
}
}
}
//Extract the node that is the immediate dominator
//and store it in immediateDominators
for(unsigned i = 1; i < nBlocks; i++) {
for(unsigned j = 0; j < nBlocks; j++) {
if(strictlyDominates(j, i, temp)) {
immediateDominators[i] = j;
}
}
}
}
<commit_msg>Somehow a tab snuck in on me.<commit_after>#include "dominator.h"
/*
* TODO Is there a need to do the post dominators and strictly post dominators?
* - The algorithm to do so is the same as computing dominators but you
* look swap the exit and entry node and look at look at the "outs" of
* block rather than the ins.
*/
/*
* Computes the dominators for the set of basic blocks.
*
* This algorithm is based on the dominator computation in Advanced Compiler Design
* Implementation. While the running time is O(n^2e)for a flowgraph with n nodes and
* e edges this algorithm is probably the most efficient as the number of basic blocks
* we look at at a time is usually pretty small. There are more complex algorithms that
* can run in near linear time, but have poor performance for computations that don't
* contain at least a few hundred nodes.
*
* If a node a dominates node b then dominators[b]->get(a) will be true. That is to say that
* dominators[i] stores the set of all nodes that dominate node i
*
* This algorithm will be most efficient if the basic blocks are in a depth-first order.
*/
void computeDominators(std::vector<BitVec*>& dominators, std::vector<BasicBlock*>& basicBlocks) {
unsigned nBlocks = basicBlocks.size();
//The root node cannot be dominated
dominators[0]->set(0);
//Initially set all other nodes as dominated by every other node
for(unsigned i = 1; i < nBlocks; i++) {
dominators[i]->set();
}
//Iteratively look for changes. A node a dominates b
//if a = b, a is immediate predecessor of b, of i
//b has multiple predecessors but a dominates
//all of them.
bool changed = true;
while(changed) {
changed = false;
for(unsigned i = 1; i < nBlocks; i++) {
BitVec temp = BitVec(nBlocks);
temp.set();
BasicBlock* curBB = basicBlocks[i];
for(unsigned j = 0; j < curBB->ins.size(); j++) {
//TODO I would ideally like this to be &=
temp.intersection(*dominators[curBB->ins[j]->id]);
}
temp.set(i);
//TODO would like to implement == and !=
if(temp.equals(*dominators[i]) == false) {
changed = true;
dominators[i]->reset();
dominators[i]->disjunction(temp);
}
}
}
}
/*
* Checks if a node a dominates node b in the set of dominators
*
* A node a dominates node b if every path path from the entry node
* to node b must go through a.
*/
bool dominates(unsigned a, unsigned b, std::vector<BitVec*> & dominators) {
if(dominators[b]->test(a)) {
return true;
}
return false;
}
/*
* Checks if a node a strictly dominates node b in the set of dominators
*
* A node a strictly dominates node b if a dominates b and a!= b
*/
bool strictlyDominates(unsigned a, unsigned b, std::vector<BitVec*> & dominators) {
if(a == b) {
return false;
}
return dominates(a, b, dominators);
}
/*
* Computes the immediate dominators from the dominators
*
* This algorithm is based on the immediate dominator computation found in Advanced Compiler
* Design Implementation. It takes the already computed dominator set and set the immediate
* dominators. For instance to get the immediate dominator of i simply get
* immediate Dominators[i]
*
* A node a immediately dominates node b if and only if a strictly dominates b
* and there does not exist a node c such that a strictly dominates c and c
* strictly dominates b
*/
void computeImmediateDominators(std::vector<unsigned>& immediateDominators, std::vector<BitVec*>& dominators) {
unsigned nBlocks = dominators.size();
//Create a temporary dominator set
std::vector<BitVec*> temp;
for(unsigned i = 0; i < nBlocks; i++) {
temp.push_back(new BitVec(nBlocks));
}
//Set temp[i] to the dominators[i] - {i} (the strict dominators)
for(unsigned i = 0; i < nBlocks; i++) {
for(unsigned j = 0; j < nBlocks; j++) {
if(strictlyDominates(i, j, dominators)) {
temp[j]->set(i);
}
}
}
//For each node i check whether each node that dominates i
//has dominators other than itself and if so remove them.
//This leaves each non-root node having a single dominator
for(unsigned i = 1; i < nBlocks; i++) {
for(unsigned j = 0; j < nBlocks; j++){
for(unsigned k = 0; k < nBlocks; k++) {
if(strictlyDominates(k, i, temp) && strictlyDominates(j, i, temp)) {
if(strictlyDominates(k, j, temp)) {
temp[i]->reset(k);
}
}
}
}
}
//Extract the node that is the immediate dominator
//and store it in immediateDominators
for(unsigned i = 1; i < nBlocks; i++) {
for(unsigned j = 0; j < nBlocks; j++) {
if(strictlyDominates(j, i, temp)) {
immediateDominators[i] = j;
}
}
}
}
<|endoftext|>
|
<commit_before>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
//#define DBUG
//#define DENORMAL_CHECK
#define MAIN
#include <pthread.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream.h>
#include <signal.h>
#ifdef LINUX
#include <sys/soundcard.h>
#endif
#ifdef SGI
#include <dmedia/audio.h>
#endif
#include <globals.h>
#include <prototypes.h>
#include <ugens.h>
#include <version.h>
#include "../rtstuff/rt.h"
#include "sockdefs.h"
#include "notetags.h" // contains defs for note-tagging
#include "../H/dbug.h"
#include "rtcmix_parse.h"
extern "C" {
int ug_intro();
int profile();
void rtprofile();
#ifdef SGI
void flush_all_underflows_to_zero();
#endif
#ifdef LINUX
void sigfpe_handler(int sig);
#endif
}
rt_item *rt_list; /* can't put this in globals.h because of rt.h trouble */
/* ---------------------------------------------------------------- usage --- */
static void
usage()
{
printf("\n"
"Usage: CMIX [options] [arguments] < minc_script.sco\n"
"\n"
" or, to use Perl instead of Minc:\n"
" PCMIX [options] [arguments] < perl_script.pl\n"
" or:\n"
" PCMIX [options] perl_script.pl [arguments]\n"
"\n"
" or, to use Python:\n"
" PYCMIX [options] [arguments] < python_script.py\n"
"\n"
" options:\n"
" -i run in interactive mode\n"
" -n no init script (interactive mode only)\n"
" -o NUM socket offset (interactive mode only)\n"
" -c enable continuous control (rtupdates)\n"
" NOTE: -s, -d, and -e are not yet implemented\n"
" -s NUM start time (seconds)\n"
" -d NUM duration (seconds)\n"
" -e NUM end time (seconds)\n"
" -f NAME read score from NAME instead of stdin\n"
" (Minc and Python only)\n"
" --debug enter parser debugger (Perl only)\n"
" -q quiet -- suppress print to screen\n"
" -Q really quiet -- not even peak stats\n"
" -h this help blurb\n"
" Other options, and arguments, passed on to parser.\n\n");
exit(1);
}
/* --------------------------------------------------------- init_globals --- */
static void
init_globals()
{
int i;
RTBUFSAMPS = 8192; /* default, modifiable with rtsetparams */
NCHANS = 2;
audioNCHANS = 0;
#ifdef LINUX
for (i = 0; i < MAXBUS; i++)
in_port[i] = out_port[i] = 0;
#endif /* LINUX */
#ifdef SGI
in_port = 0;
out_port = 0;
#endif /* SGI */
rtInteractive = 0;
noParse = 0;
socknew = 0;
rtsetparams_called = 0;
audio_on = 0;
audio_config = 1;
play_audio = 1; /* modified with set_option */
full_duplex = 0;
check_peaks = 1;
report_clipping = 1;
/* I can't believe these were never initialized */
baseTime = 0;
elapsed = 0;
schedtime = 0;
output_data_format = -1;
output_header_type = -1;
normalize_output_floats = 0;
is_float_format = 0;
rtoutsfname = NULL;
tags_on = 0;
rtfileit = 0; /* signal writing to soundfile */
rtoutfile = 0;
print_is_on = 1;
for (i = 0; i < MAXBUS; i++) {
AuxToAuxPlayList[i] = -1; /* The playback order for AUX buses */
ToOutPlayList[i] = -1; /* The playback order for AUX buses */
ToAuxPlayList[i] =-1; /* The playback order for AUX buses */
}
for (i = 0; i < MAX_INPUT_FDS; i++)
inputFileTable[i].fd = NO_FD;
init_buf_ptrs();
}
/* ------------------------------------------------------- sigint_handler --- */
static void
sigint_handler(int signo)
{
#ifdef DBUG
printf("Signal handler called (signo %d)\n", signo);
#endif
if (rtsetparams_called) {
close_audio_ports();
rtreportstats();
rtcloseout();
}
else
closesf();
exit(1);
}
/* ----------------------------------------------------- detect_denormals --- */
/* Unmask "denormalized operand" bit of the x86 FPU control word, so that
any operations with denormalized numbers will raise a SIGFPE signal,
and our handler will be called. NOTE: This is for debugging only!
This will not tell you how many denormal ops there are, so just because
the exception is thrown doesn't mean there's a serious problem. For
more info, see: http://www.smartelectronix.com/musicdsp/text/other001.txt.
*/
static void
detect_denormals()
{
#ifdef LINUX
#include <fpu_control.h>
int cw = 0;
_FPU_GETCW(cw);
cw &= ~_FPU_MASK_DM;
_FPU_SETCW(cw);
#endif
}
/* ----------------------------------------------------------------- main --- */
int
main(int argc, char *argv[])
{
int i, j, xargc;
int retcode; /* for mutexes */
char *infile;
char *xargv[MAXARGS + 1];
pthread_t sockitThread, inTraverseThread;
init_globals();
#ifdef LINUX
#ifdef DENORMAL_CHECK
detect_denormals();
#endif
signal(SIGFPE, sigfpe_handler); /* Install signal handler */
#endif /* LINUX */
#ifdef SGI
flush_all_underflows_to_zero();
#endif
/* Call sigint_handler on cntl-C. */
if (signal(SIGINT, sigint_handler) == SIG_ERR) {
fprintf(stderr, "Error installing signal handler.\n");
exit(1);
}
xargv[0] = argv[0];
for (i = 1; i <= MAXARGS; i++)
xargv[i] = NULL;
xargc = 1;
/* Process command line, copying any args we don't handle into
<xargv> for parsers to deal with.
*/
for (i = 1; i < argc; i++) {
char *arg = argv[i];
if (arg[0] == '-') {
switch (arg[1]) {
case 'h':
usage();
break;
case 'i': /* for separate parseit thread */
rtInteractive = 1;
audio_config = 0;
break;
case 'n': /* for use in rtInteractive mode only */
noParse = 1;
break;
case 'Q': /* reall quiet */
report_clipping = 0; /* (then fall through) */
case 'q': /* quiet */
print_is_on = 0;
break;
case 'o': /* NOTE NOTE NOTE: will soon replace -s */
case 's': /* set up a socket offset */
if (++i >= argc) {
fprintf(stderr, "You didn't give a socket offset.\n");
exit(1);
}
socknew = atoi(argv[i]);
printf("listening on socket: %d\n", MYPORT + socknew);
break;
// case 's': /* start time (unimplemented) */
case 'd': /* duration to play for (unimplemented) */
case 'e': /* time to stop playing (unimplemented) */
fprintf(stderr, "-s, -d, -e options not yet implemented\n");
exit(1);
break;
case 'c': /* set up for continuous control (note tags on) */
tags_on = 1;
printf("rtupdates enabled\n");
curtag = 1; /* "0" is reserved for all notes */
for (j = 0; j < MAXPUPS; j++) /* initialize element 0 */
pupdatevals[0][j] = NOPUPDATE;
break;
case 'f': /* use file name arg instead of stdin as score */
if (++i >= argc) {
fprintf(stderr, "You didn't give a file name.\n");
exit(1);
}
infile = argv[i];
use_script_file(infile);
break;
case '-': /* accept "--debug" and pass to Perl as "-d" */
if (strncmp(&arg[2], "debug", 10) == 0)
xargv[xargc++] = strdup("-d");
break;
default:
xargv[xargc++] = arg; /* copy for parser */
}
}
else
xargv[xargc++] = arg; /* copy for parser */
if (xargc >= MAXARGS) {
fprintf(stderr, "Too many command-line options.\n");
exit(1);
}
}
/* Banner */
if (print_is_on)
printf("--------> %s %s (%s) <--------\n",
RTCMIX_NAME, RTCMIX_VERSION, argv[0]);
ug_intro(); /* introduce standard routines */
profile(); /* introduce user-written routines etc. */
rtprofile(); /* introduce real-time user-written routines */
setbuf(stdout, NULL); /* Want to see stdout errors */
/* In rtInteractive mode, we set up RTcmix to listen for score data
over a socket, and then parse this, schedule instruments, and play
them concurrently. The socket listening and parsing go in one
thread, and the scheduler and instrument code go in another.
When not in rtInteractive mode, RTcmix parses the score, schedules
all instruments, and then plays them -- in that order. No threads.
*/
if (rtInteractive) {
if (print_is_on)
fprintf(stdout, "rtInteractive mode set\n");
/* Read an initialization score. */
if (!noParse) {
int status;
#ifdef DBUG
cout << "Parsing once ...\n";
#endif
status = parse_score(xargc, xargv);
if (status != 0)
exit(1);
}
/* Create parsing thread. */
#ifdef DBUG
fprintf(stdout, "creating sockit() thread\n");
#endif
retcode = pthread_create(&sockitThread, NULL, sockit, (void *) "");
if (retcode != 0) {
fprintf(stderr, "sockit() thread create failed\n");
}
/* Create scheduling thread. */
#ifdef DBUG
fprintf(stdout, "creating inTraverse() thread\n");
#endif
retcode = pthread_create(&inTraverseThread, NULL, inTraverse,
(void *) "");
if (retcode != 0) {
fprintf(stderr, "inTraverse() thread create failed\n");
}
/* Join scheduling thread. */
#ifdef DBUG
fprintf(stdout, "joining inTraverse() thread\n");
#endif
/* retcode = pthread_join(inTraverseThread, NULL); */
if (retcode != 0) {
fprintf(stderr, "inTraverse() thread join failed\n");
}
/* Join parsing thread. */
#ifdef DBUG
fprintf(stdout, "joining sockit() thread\n");
#endif
/* retcode = pthread_join(sockitThread, NULL); */
if (retcode != 0) {
fprintf(stderr, "sockit() thread join failed\n");
}
if (!noParse)
destroy_parser();
}
else {
int status;
status = parse_score(xargc, xargv);
if (status == 0)
inTraverse(NULL);
else
exit(status);
destroy_parser();
}
/* DJT: this instead of above joins */
while (rtInteractive) {};
closesf();
return 0;
}
<commit_msg>Change detect_denormals compilation condition so that LinuxPPC is happy.<commit_after>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
//#define DBUG
//#define DENORMAL_CHECK
#define MAIN
#include <pthread.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream.h>
#include <signal.h>
#ifdef LINUX
#include <sys/soundcard.h>
#endif
#ifdef SGI
#include <dmedia/audio.h>
#endif
#include <globals.h>
#include <prototypes.h>
#include <ugens.h>
#include <version.h>
#include "../rtstuff/rt.h"
#include "sockdefs.h"
#include "notetags.h" // contains defs for note-tagging
#include "../H/dbug.h"
#include "rtcmix_parse.h"
extern "C" {
int ug_intro();
int profile();
void rtprofile();
#ifdef SGI
void flush_all_underflows_to_zero();
#endif
#ifdef LINUX
void sigfpe_handler(int sig);
#endif
}
rt_item *rt_list; /* can't put this in globals.h because of rt.h trouble */
/* ---------------------------------------------------------------- usage --- */
static void
usage()
{
printf("\n"
"Usage: CMIX [options] [arguments] < minc_script.sco\n"
"\n"
" or, to use Perl instead of Minc:\n"
" PCMIX [options] [arguments] < perl_script.pl\n"
" or:\n"
" PCMIX [options] perl_script.pl [arguments]\n"
"\n"
" or, to use Python:\n"
" PYCMIX [options] [arguments] < python_script.py\n"
"\n"
" options:\n"
" -i run in interactive mode\n"
" -n no init script (interactive mode only)\n"
" -o NUM socket offset (interactive mode only)\n"
" -c enable continuous control (rtupdates)\n"
" NOTE: -s, -d, and -e are not yet implemented\n"
" -s NUM start time (seconds)\n"
" -d NUM duration (seconds)\n"
" -e NUM end time (seconds)\n"
" -f NAME read score from NAME instead of stdin\n"
" (Minc and Python only)\n"
" --debug enter parser debugger (Perl only)\n"
" -q quiet -- suppress print to screen\n"
" -Q really quiet -- not even peak stats\n"
" -h this help blurb\n"
" Other options, and arguments, passed on to parser.\n\n");
exit(1);
}
/* --------------------------------------------------------- init_globals --- */
static void
init_globals()
{
int i;
RTBUFSAMPS = 8192; /* default, modifiable with rtsetparams */
NCHANS = 2;
audioNCHANS = 0;
#ifdef LINUX
for (i = 0; i < MAXBUS; i++)
in_port[i] = out_port[i] = 0;
#endif /* LINUX */
#ifdef SGI
in_port = 0;
out_port = 0;
#endif /* SGI */
rtInteractive = 0;
noParse = 0;
socknew = 0;
rtsetparams_called = 0;
audio_on = 0;
audio_config = 1;
play_audio = 1; /* modified with set_option */
full_duplex = 0;
check_peaks = 1;
report_clipping = 1;
/* I can't believe these were never initialized */
baseTime = 0;
elapsed = 0;
schedtime = 0;
output_data_format = -1;
output_header_type = -1;
normalize_output_floats = 0;
is_float_format = 0;
rtoutsfname = NULL;
tags_on = 0;
rtfileit = 0; /* signal writing to soundfile */
rtoutfile = 0;
print_is_on = 1;
for (i = 0; i < MAXBUS; i++) {
AuxToAuxPlayList[i] = -1; /* The playback order for AUX buses */
ToOutPlayList[i] = -1; /* The playback order for AUX buses */
ToAuxPlayList[i] =-1; /* The playback order for AUX buses */
}
for (i = 0; i < MAX_INPUT_FDS; i++)
inputFileTable[i].fd = NO_FD;
init_buf_ptrs();
}
/* ------------------------------------------------------- sigint_handler --- */
static void
sigint_handler(int signo)
{
#ifdef DBUG
printf("Signal handler called (signo %d)\n", signo);
#endif
if (rtsetparams_called) {
close_audio_ports();
rtreportstats();
rtcloseout();
}
else
closesf();
exit(1);
}
/* ----------------------------------------------------- detect_denormals --- */
/* Unmask "denormalized operand" bit of the x86 FPU control word, so that
any operations with denormalized numbers will raise a SIGFPE signal,
and our handler will be called. NOTE: This is for debugging only!
This will not tell you how many denormal ops there are, so just because
the exception is thrown doesn't mean there's a serious problem. For
more info, see: http://www.smartelectronix.com/musicdsp/text/other001.txt.
*/
#ifdef LINUX
#ifdef DENORMAL_CHECK
static void
detect_denormals()
{
#include <fpu_control.h>
int cw = 0;
_FPU_GETCW(cw);
cw &= ~_FPU_MASK_DM;
_FPU_SETCW(cw);
}
#endif /* DENORMAL_CHECK */
#endif /* LINUX */
/* ----------------------------------------------------------------- main --- */
int
main(int argc, char *argv[])
{
int i, j, xargc;
int retcode; /* for mutexes */
char *infile;
char *xargv[MAXARGS + 1];
pthread_t sockitThread, inTraverseThread;
init_globals();
#ifdef LINUX
#ifdef DENORMAL_CHECK
detect_denormals();
#endif
signal(SIGFPE, sigfpe_handler); /* Install signal handler */
#endif /* LINUX */
#ifdef SGI
flush_all_underflows_to_zero();
#endif
/* Call sigint_handler on cntl-C. */
if (signal(SIGINT, sigint_handler) == SIG_ERR) {
fprintf(stderr, "Error installing signal handler.\n");
exit(1);
}
xargv[0] = argv[0];
for (i = 1; i <= MAXARGS; i++)
xargv[i] = NULL;
xargc = 1;
/* Process command line, copying any args we don't handle into
<xargv> for parsers to deal with.
*/
for (i = 1; i < argc; i++) {
char *arg = argv[i];
if (arg[0] == '-') {
switch (arg[1]) {
case 'h':
usage();
break;
case 'i': /* for separate parseit thread */
rtInteractive = 1;
audio_config = 0;
break;
case 'n': /* for use in rtInteractive mode only */
noParse = 1;
break;
case 'Q': /* reall quiet */
report_clipping = 0; /* (then fall through) */
case 'q': /* quiet */
print_is_on = 0;
break;
case 'o': /* NOTE NOTE NOTE: will soon replace -s */
case 's': /* set up a socket offset */
if (++i >= argc) {
fprintf(stderr, "You didn't give a socket offset.\n");
exit(1);
}
socknew = atoi(argv[i]);
printf("listening on socket: %d\n", MYPORT + socknew);
break;
// case 's': /* start time (unimplemented) */
case 'd': /* duration to play for (unimplemented) */
case 'e': /* time to stop playing (unimplemented) */
fprintf(stderr, "-s, -d, -e options not yet implemented\n");
exit(1);
break;
case 'c': /* set up for continuous control (note tags on) */
tags_on = 1;
printf("rtupdates enabled\n");
curtag = 1; /* "0" is reserved for all notes */
for (j = 0; j < MAXPUPS; j++) /* initialize element 0 */
pupdatevals[0][j] = NOPUPDATE;
break;
case 'f': /* use file name arg instead of stdin as score */
if (++i >= argc) {
fprintf(stderr, "You didn't give a file name.\n");
exit(1);
}
infile = argv[i];
use_script_file(infile);
break;
case '-': /* accept "--debug" and pass to Perl as "-d" */
if (strncmp(&arg[2], "debug", 10) == 0)
xargv[xargc++] = strdup("-d");
break;
default:
xargv[xargc++] = arg; /* copy for parser */
}
}
else
xargv[xargc++] = arg; /* copy for parser */
if (xargc >= MAXARGS) {
fprintf(stderr, "Too many command-line options.\n");
exit(1);
}
}
/* Banner */
if (print_is_on)
printf("--------> %s %s (%s) <--------\n",
RTCMIX_NAME, RTCMIX_VERSION, argv[0]);
ug_intro(); /* introduce standard routines */
profile(); /* introduce user-written routines etc. */
rtprofile(); /* introduce real-time user-written routines */
setbuf(stdout, NULL); /* Want to see stdout errors */
/* In rtInteractive mode, we set up RTcmix to listen for score data
over a socket, and then parse this, schedule instruments, and play
them concurrently. The socket listening and parsing go in one
thread, and the scheduler and instrument code go in another.
When not in rtInteractive mode, RTcmix parses the score, schedules
all instruments, and then plays them -- in that order. No threads.
*/
if (rtInteractive) {
if (print_is_on)
fprintf(stdout, "rtInteractive mode set\n");
/* Read an initialization score. */
if (!noParse) {
int status;
#ifdef DBUG
cout << "Parsing once ...\n";
#endif
status = parse_score(xargc, xargv);
if (status != 0)
exit(1);
}
/* Create parsing thread. */
#ifdef DBUG
fprintf(stdout, "creating sockit() thread\n");
#endif
retcode = pthread_create(&sockitThread, NULL, sockit, (void *) "");
if (retcode != 0) {
fprintf(stderr, "sockit() thread create failed\n");
}
/* Create scheduling thread. */
#ifdef DBUG
fprintf(stdout, "creating inTraverse() thread\n");
#endif
retcode = pthread_create(&inTraverseThread, NULL, inTraverse,
(void *) "");
if (retcode != 0) {
fprintf(stderr, "inTraverse() thread create failed\n");
}
/* Join scheduling thread. */
#ifdef DBUG
fprintf(stdout, "joining inTraverse() thread\n");
#endif
/* retcode = pthread_join(inTraverseThread, NULL); */
if (retcode != 0) {
fprintf(stderr, "inTraverse() thread join failed\n");
}
/* Join parsing thread. */
#ifdef DBUG
fprintf(stdout, "joining sockit() thread\n");
#endif
/* retcode = pthread_join(sockitThread, NULL); */
if (retcode != 0) {
fprintf(stderr, "sockit() thread join failed\n");
}
if (!noParse)
destroy_parser();
}
else {
int status;
status = parse_score(xargc, xargv);
if (status == 0)
inTraverse(NULL);
else
exit(status);
destroy_parser();
}
/* DJT: this instead of above joins */
while (rtInteractive) {};
closesf();
return 0;
}
<|endoftext|>
|
<commit_before>// @(#)root/test:$name: $:$id: filter.cxx,v 1.0 exp $
// Author: O.Couet
//
// filters doc files.
//
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <cstring>
#include <iostream>
#include <stdlib.h>
#include <stdarg.h>
#include <memory>
using namespace std;
// Auxiliary functions
void FilterClass();
void FilterTutorial();
void GetClassName();
void ExecuteMacro();
void ExecuteCommand(string);
void ReplaceAll(string&, const string&, const string&);
string StringFormat(const string fmt_str, ...);
bool EndsWith(string const &, string const &);
bool BeginsWith(const string&, const string&);
// Global variables.
FILE *f; // Pointer to the file being parsed.
char gLine[255]; // Current line in the current input file
string gFileName; // Input file name
string gLineString; // Current line (as a string) in the current input file
string gClassName; // Current class name
string gImageName; // Current image name
string gMacroName; // Current macro name
string gCwd; // Current working directory
string gOutDir; // Output directory
string gSourceDir; // Source directory
string gOutputName; // File containing a macro std::out
bool gHeader; // True if the input file is a header
bool gSource; // True if the input file is a source file
bool gImageSource; // True the source of the current macro should be shown
int gInMacro; // >0 if parsing a macro in a class documentation.
int gImageID; // Image Identifier.
int gMacroID; // Macro identifier in class documentation.
int gShowTutSource; // >0 if the tutorial source code should be shown
////////////////////////////////////////////////////////////////////////////////
/// Filter ROOT files for Doxygen.
int main(int argc, char *argv[])
{
// Initialisation
gFileName = argv[1];
gHeader = false;
gSource = false;
gImageSource = false;
gInMacro = 0;
gImageID = 0;
gMacroID = 0;
gOutputName = "stdout.dat";
gShowTutSource = 0;
if (EndsWith(gFileName,".cxx")) gSource = true;
if (EndsWith(gFileName,".h")) gHeader = true;
GetClassName();
// Retrieve the current working directory
int last = gFileName.rfind("/");
gCwd = gFileName.substr(0,last);
// Retrieve the output directory
gOutDir = getenv("DOXYGEN_OUTPUT_DIRECTORY");
ReplaceAll(gOutDir,"\"","");
// Retrieve the source directory
gSourceDir = getenv("DOXYGEN_SOURCE_DIRECTORY");
ReplaceAll(gSourceDir,"\"","");
// Open the input file name.
f = fopen(gFileName.c_str(),"r");
if (gFileName.find("tutorials") != string::npos) FilterTutorial();
else FilterClass();
}
////////////////////////////////////////////////////////////////////////////////
/// Filter ROOT class for Doxygen.
void FilterClass()
{
// File for inline macros.
FILE *m = 0;
// File header.
if (gHeader) {
while (fgets(gLine,255,f)) {
gLineString = gLine;
printf("%s",gLineString.c_str());
}
fclose(f);
return;
}
// Source file.
if (gSource) {
while (fgets(gLine,255,f)) {
gLineString = gLine;
if (gLineString.find("End_Macro") != string::npos) {
ReplaceAll(gLineString,"End_Macro","");
gImageSource = false;
gInMacro = 0;
if (m) {
fclose(m);
m = 0;
ExecuteCommand(StringFormat("root -l -b -q \"makeimage.C(\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",true)\""
, StringFormat("%s_%3.3d.C", gClassName.c_str(), gMacroID).c_str()
, StringFormat("%s_%3.3d.png", gClassName.c_str(), gImageID).c_str()
, gOutDir.c_str()));
ExecuteCommand(StringFormat("rm %s_%3.3d.C", gClassName.c_str(), gMacroID));
}
}
if (gInMacro) {
if (gInMacro == 1) {
if (EndsWith(gLineString,".C\n")) {
ExecuteMacro();
gInMacro++;
} else {
gMacroID++;
m = fopen(StringFormat("%s_%3.3d.C", gClassName.c_str(), gMacroID).c_str(), "w");
if (m) fprintf(m,"%s",gLineString.c_str());
if (BeginsWith(gLineString,"{")) {
if (gImageSource) {
ReplaceAll(gLineString,"{"
, StringFormat("\\include %s_%3.3d.C"
, gClassName.c_str()
, gMacroID));
} else {
gLineString = "\n";
}
}
gInMacro++;
}
} else {
if (m) fprintf(m,"%s",gLineString.c_str());
if (BeginsWith(gLineString,"}")) {
ReplaceAll(gLineString,"}", StringFormat("\\image html %s_%3.3d.png", gClassName.c_str(), gImageID));
} else {
gLineString = "\n";
}
gInMacro++;
}
}
if (gLineString.find("Begin_Macro") != string::npos) {
if (gLineString.find("source") != string::npos) gImageSource = true;
gImageID++;
gInMacro++;
gLineString = "\n";
}
printf("%s",gLineString.c_str());
}
fclose(f);
return;
}
// Output anything not header nor source
while (fgets(gLine,255,f)) {
gLineString = gLine;
printf("%s",gLineString.c_str());
}
fclose(f);
}
////////////////////////////////////////////////////////////////////////////////
/// Filter ROOT tutorials for Doxygen.
void FilterTutorial()
{
// File for inline macros.
FILE *m = 0;
// Extract the macro name
int i1 = gFileName.rfind('/')+1;
int i2 = gFileName.rfind('C');
gMacroName = gFileName.substr(i1,i2-i1+1);
gImageName = StringFormat("%s.png", gMacroName.c_str()); // Image name
gOutputName = StringFormat("%s.out", gMacroName.c_str()); // output name
// Parse the source and generate the image if needed
while (fgets(gLine,255,f)) {
gLineString = gLine;
// \macro_image found
if (gLineString.find("\\macro_image") != string::npos) {
ExecuteCommand(StringFormat("root -l -b -q \"makeimage.C(\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",false)\"",
gFileName.c_str(), gImageName.c_str(), gOutDir.c_str()));
ReplaceAll(gLineString, "\\macro_image", StringFormat("\\image html %s",gImageName.c_str()));
remove(gOutputName.c_str());
}
// \macro_code found
if (gLineString.find("\\macro_code") != string::npos) {
gShowTutSource = 1;
m = fopen(StringFormat("%s/macros/%s",gOutDir.c_str(),gMacroName.c_str()).c_str(), "w");
ReplaceAll(gLineString, "\\macro_code", StringFormat("\\include %s",gMacroName.c_str()));
}
// \macro_output found
if (gLineString.find("\\macro_output") != string::npos) {
ExecuteCommand(StringFormat("root -l -b -q %s", gFileName.c_str()).c_str());
rename(gOutputName.c_str(), StringFormat("%s/macros/%s",gOutDir.c_str(), gOutputName.c_str()).c_str());
ReplaceAll(gLineString, "\\macro_output", StringFormat("\\include %s",gOutputName.c_str()));
}
// \author is the last comment line.
if (gLineString.find("\\author") != string::npos) {
printf("%s",StringFormat("%s \n/// \\cond \n",gLineString.c_str()).c_str());
if (gShowTutSource == 1) gShowTutSource = 2;
} else {
printf("%s",gLineString.c_str());
if (m && gShowTutSource == 2) fprintf(m,"%s",gLineString.c_str());
}
}
if (m) fclose(m);
}
////////////////////////////////////////////////////////////////////////////////
/// Retrieve the class name.
void GetClassName()
{
int i1 = 0;
int i2 = 0;
FILE *f = fopen(gFileName.c_str(),"r");
// File header.
if (gHeader) {
while (fgets(gLine,255,f)) {
gLineString = gLine;
if (gLineString.find("ClassDef") != string::npos) {
i1 = gLineString.find("(")+1;
i2 = gLineString.find(",")-1;
gClassName = gLineString.substr(i1,i2-i1+1);
fclose(f);
return;
}
}
}
// Source file.
if (gSource) {
while (fgets(gLine,255,f)) {
gLineString = gLine;
if (gLineString.find("ClassImp") != string::npos) {
i1 = gLineString.find("(")+1;
i2 = gLineString.find(")")-1;
gClassName = gLineString.substr(i1,i2-i1+1);
fclose(f);
return;
}
}
}
fclose(f);
}
////////////////////////////////////////////////////////////////////////////////
/// Execute the macro in gLineString and produce the corresponding picture
void ExecuteMacro()
{
// Name of the next Image to be generated
gImageName = StringFormat("%s_%3.3d.png", gClassName.c_str(), gImageID);
// Retrieve the macro to be executed.
if (gLineString.find("../../..") != string::npos) {
ReplaceAll(gLineString,"../../..", gSourceDir.c_str());
} else {
gLineString.insert(0, StringFormat("%s/../doc/macros/",gCwd.c_str()));
}
int i1 = gLineString.rfind('/')+1;
int i2 = gLineString.rfind('C');
gMacroName = gLineString.substr(i1,i2-i1+1);
// Build the ROOT command to be executed.
gLineString.insert(0, StringFormat("root -l -b -q \"makeimage.C(\\\""));
int l = gLineString.length();
gLineString.replace(l-2,1,StringFormat("C\\\",\\\"%s\\\",\\\"%s\\\",true)\"", gImageName.c_str(), gOutDir.c_str()));
ExecuteCommand(gLineString);
if (gImageSource) {
gLineString = StringFormat("\\include %s\n\\image html %s\n", gMacroName.c_str(), gImageName.c_str());
} else {
gLineString = StringFormat("\n\\image html %s\n", gImageName.c_str());
}
}
////////////////////////////////////////////////////////////////////////////////
/// Execute a command making sure stdout will not go in the doxygen file.
void ExecuteCommand(string command)
{
int o = dup(fileno(stdout));
freopen(gOutputName.c_str(),"a",stdout);
system(command.c_str());
dup2(o,fileno(stdout));
close(o);
}
////////////////////////////////////////////////////////////////////////////////
/// Replace all instances of a string with another string.
void ReplaceAll(string& str, const string& from, const string& to) {
if (from.empty()) return;
string wsRet;
wsRet.reserve(str.length());
size_t start_pos = 0, pos;
while ((pos = str.find(from, start_pos)) != string::npos) {
wsRet += str.substr(start_pos, pos - start_pos);
wsRet += to;
pos += from.length();
start_pos = pos;
}
wsRet += str.substr(start_pos);
str.swap(wsRet);
}
////////////////////////////////////////////////////////////////////////////////
/// std::string formatting like sprintf
string StringFormat(const string fmt_str, ...) {
int final_n, n = ((int)fmt_str.size()) * 2; /* Reserve two times as much as the length of the fmt_str */
string str;
unique_ptr<char[]> formatted;
va_list ap;
while (1) {
formatted.reset(new char[n]); /* Wrap the plain char array into the unique_ptr */
strcpy(&formatted[0], fmt_str.c_str());
va_start(ap, fmt_str);
final_n = vsnprintf(&formatted[0], n, fmt_str.c_str(), ap);
va_end(ap);
if (final_n < 0 || final_n >= n) n += abs(final_n - n + 1);
else break;
}
return string(formatted.get());
}
////////////////////////////////////////////////////////////////////////////////
/// find if a string ends with another string
bool EndsWith(string const &fullString, string const &ending) {
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}
////////////////////////////////////////////////////////////////////////////////
/// find if a string begins with another string
bool BeginsWith(const string& haystack, const string& needle) {
return needle.length() <= haystack.length() && equal(needle.begin(), needle.end(), haystack.begin());
}
<commit_msg>Document the features implemented by the filter.<commit_after>// @(#)root/test:$name: $:$id: filter.cxx,v 1.0 exp $
// Author: O.Couet
/// The ROOT doxygen filter implements ROOT's specific directives used to generate
/// the ROOT reference guide.
///
/// ## In the ROOT classes
///
/// ### `Begin_Macro` and `End_Macro`
/// The two tags where used the THtml version to generate images from ROOT code.
/// The genererated picture is inlined exactly at the place where the macro is
/// defined. The Macro can be defined in two way:
/// - by direct in-lining of the the C++ code
/// - by a reference to a C++ file
/// The tag `Begin_Macro` can have the parameter `(source)`. The directive becomes:
/// `Begin_Macro(source)`. This parameter allows to show the macro's code in addition.
///
/// ## In the ROOT tutorials
///
/// ROOT tutorials are also included in the ROOT documentation. The tutorials'
/// macros headers should look like:
///
/// ~~~ {.cpp}
/// \file
/// \ingroup tutorial_hist
/// Getting Contours From TH2D.
///
/// #### Image produced by `.x ContourList.C`
/// The contours values are drawn next to each contour.
/// \macro_image
///
/// #### Output produced by `.x ContourList.C`
/// It shows that 6 contours and 12 graphs were found.
/// \macro_output
///
/// #### `ContourList.C`
/// \macro_code
///
/// \authors Josh de Bever, Olivier Couet
/// ~~~
///
/// This example shows that three new directives have been implemented:
///
/// 1. `\macro_image`
/// The image produced by this macro is shown. A caption can be added to document
/// the picture: `\macro_image This is a picture`
///
/// 2. `\macro_code`
/// The macro code is shown. A caption can be added: `\macro_code This is code`
///
/// 3. `\macro_output`
/// The output produced by this macro is shown. A caption can be added:
/// `\macro_image This the macro output`
///
/// Note that the doxygen directive `\authors` or `\author` must be the last one
/// of the macro header.
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <cstring>
#include <iostream>
#include <stdlib.h>
#include <stdarg.h>
#include <memory>
using namespace std;
// Auxiliary functions
void FilterClass();
void FilterTutorial();
void GetClassName();
void ExecuteMacro();
void ExecuteCommand(string);
void ReplaceAll(string&, const string&, const string&);
string StringFormat(const string fmt_str, ...);
bool EndsWith(string const &, string const &);
bool BeginsWith(const string&, const string&);
// Global variables.
FILE *f; // Pointer to the file being parsed.
char gLine[255]; // Current line in the current input file
string gFileName; // Input file name
string gLineString; // Current line (as a string) in the current input file
string gClassName; // Current class name
string gImageName; // Current image name
string gMacroName; // Current macro name
string gCwd; // Current working directory
string gOutDir; // Output directory
string gSourceDir; // Source directory
string gOutputName; // File containing a macro std::out
bool gHeader; // True if the input file is a header
bool gSource; // True if the input file is a source file
bool gImageSource; // True the source of the current macro should be shown
int gInMacro; // >0 if parsing a macro in a class documentation.
int gImageID; // Image Identifier.
int gMacroID; // Macro identifier in class documentation.
int gShowTutSource; // >0 if the tutorial source code should be shown
////////////////////////////////////////////////////////////////////////////////
/// Filter ROOT files for Doxygen.
int main(int argc, char *argv[])
{
// Initialisation
gFileName = argv[1];
gHeader = false;
gSource = false;
gImageSource = false;
gInMacro = 0;
gImageID = 0;
gMacroID = 0;
gOutputName = "stdout.dat";
gShowTutSource = 0;
if (EndsWith(gFileName,".cxx")) gSource = true;
if (EndsWith(gFileName,".h")) gHeader = true;
GetClassName();
// Retrieve the current working directory
int last = gFileName.rfind("/");
gCwd = gFileName.substr(0,last);
// Retrieve the output directory
gOutDir = getenv("DOXYGEN_OUTPUT_DIRECTORY");
ReplaceAll(gOutDir,"\"","");
// Retrieve the source directory
gSourceDir = getenv("DOXYGEN_SOURCE_DIRECTORY");
ReplaceAll(gSourceDir,"\"","");
// Open the input file name.
f = fopen(gFileName.c_str(),"r");
if (gFileName.find("tutorials") != string::npos) FilterTutorial();
else FilterClass();
}
////////////////////////////////////////////////////////////////////////////////
/// Filter ROOT class for Doxygen.
void FilterClass()
{
// File for inline macros.
FILE *m = 0;
// File header.
if (gHeader) {
while (fgets(gLine,255,f)) {
gLineString = gLine;
printf("%s",gLineString.c_str());
}
fclose(f);
return;
}
// Source file.
if (gSource) {
while (fgets(gLine,255,f)) {
gLineString = gLine;
if (gLineString.find("End_Macro") != string::npos) {
ReplaceAll(gLineString,"End_Macro","");
gImageSource = false;
gInMacro = 0;
if (m) {
fclose(m);
m = 0;
ExecuteCommand(StringFormat("root -l -b -q \"makeimage.C(\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",true)\""
, StringFormat("%s_%3.3d.C", gClassName.c_str(), gMacroID).c_str()
, StringFormat("%s_%3.3d.png", gClassName.c_str(), gImageID).c_str()
, gOutDir.c_str()));
ExecuteCommand(StringFormat("rm %s_%3.3d.C", gClassName.c_str(), gMacroID));
}
}
if (gInMacro) {
if (gInMacro == 1) {
if (EndsWith(gLineString,".C\n")) {
ExecuteMacro();
gInMacro++;
} else {
gMacroID++;
m = fopen(StringFormat("%s_%3.3d.C", gClassName.c_str(), gMacroID).c_str(), "w");
if (m) fprintf(m,"%s",gLineString.c_str());
if (BeginsWith(gLineString,"{")) {
if (gImageSource) {
ReplaceAll(gLineString,"{"
, StringFormat("\\include %s_%3.3d.C"
, gClassName.c_str()
, gMacroID));
} else {
gLineString = "\n";
}
}
gInMacro++;
}
} else {
if (m) fprintf(m,"%s",gLineString.c_str());
if (BeginsWith(gLineString,"}")) {
ReplaceAll(gLineString,"}", StringFormat("\\image html %s_%3.3d.png", gClassName.c_str(), gImageID));
} else {
gLineString = "\n";
}
gInMacro++;
}
}
if (gLineString.find("Begin_Macro") != string::npos) {
if (gLineString.find("source") != string::npos) gImageSource = true;
gImageID++;
gInMacro++;
gLineString = "\n";
}
printf("%s",gLineString.c_str());
}
fclose(f);
return;
}
// Output anything not header nor source
while (fgets(gLine,255,f)) {
gLineString = gLine;
printf("%s",gLineString.c_str());
}
fclose(f);
}
////////////////////////////////////////////////////////////////////////////////
/// Filter ROOT tutorials for Doxygen.
void FilterTutorial()
{
// File for inline macros.
FILE *m = 0;
// Extract the macro name
int i1 = gFileName.rfind('/')+1;
int i2 = gFileName.rfind('C');
gMacroName = gFileName.substr(i1,i2-i1+1);
gImageName = StringFormat("%s.png", gMacroName.c_str()); // Image name
gOutputName = StringFormat("%s.out", gMacroName.c_str()); // output name
// Parse the source and generate the image if needed
while (fgets(gLine,255,f)) {
gLineString = gLine;
// \macro_image found
if (gLineString.find("\\macro_image") != string::npos) {
ExecuteCommand(StringFormat("root -l -b -q \"makeimage.C(\\\"%s\\\",\\\"%s\\\",\\\"%s\\\",false)\"",
gFileName.c_str(), gImageName.c_str(), gOutDir.c_str()));
ReplaceAll(gLineString, "\\macro_image", StringFormat("\\image html %s",gImageName.c_str()));
remove(gOutputName.c_str());
}
// \macro_code found
if (gLineString.find("\\macro_code") != string::npos) {
gShowTutSource = 1;
m = fopen(StringFormat("%s/macros/%s",gOutDir.c_str(),gMacroName.c_str()).c_str(), "w");
ReplaceAll(gLineString, "\\macro_code", StringFormat("\\include %s",gMacroName.c_str()));
}
// \macro_output found
if (gLineString.find("\\macro_output") != string::npos) {
ExecuteCommand(StringFormat("root -l -b -q %s", gFileName.c_str()).c_str());
rename(gOutputName.c_str(), StringFormat("%s/macros/%s",gOutDir.c_str(), gOutputName.c_str()).c_str());
ReplaceAll(gLineString, "\\macro_output", StringFormat("\\include %s",gOutputName.c_str()));
}
// \author is the last comment line.
if (gLineString.find("\\author") != string::npos) {
printf("%s",StringFormat("%s \n/// \\cond \n",gLineString.c_str()).c_str());
if (gShowTutSource == 1) gShowTutSource = 2;
} else {
printf("%s",gLineString.c_str());
if (m && gShowTutSource == 2) fprintf(m,"%s",gLineString.c_str());
}
}
if (m) fclose(m);
}
////////////////////////////////////////////////////////////////////////////////
/// Retrieve the class name.
void GetClassName()
{
int i1 = 0;
int i2 = 0;
FILE *f = fopen(gFileName.c_str(),"r");
// File header.
if (gHeader) {
while (fgets(gLine,255,f)) {
gLineString = gLine;
if (gLineString.find("ClassDef") != string::npos) {
i1 = gLineString.find("(")+1;
i2 = gLineString.find(",")-1;
gClassName = gLineString.substr(i1,i2-i1+1);
fclose(f);
return;
}
}
}
// Source file.
if (gSource) {
while (fgets(gLine,255,f)) {
gLineString = gLine;
if (gLineString.find("ClassImp") != string::npos) {
i1 = gLineString.find("(")+1;
i2 = gLineString.find(")")-1;
gClassName = gLineString.substr(i1,i2-i1+1);
fclose(f);
return;
}
}
}
fclose(f);
}
////////////////////////////////////////////////////////////////////////////////
/// Execute the macro in gLineString and produce the corresponding picture
void ExecuteMacro()
{
// Name of the next Image to be generated
gImageName = StringFormat("%s_%3.3d.png", gClassName.c_str(), gImageID);
// Retrieve the macro to be executed.
if (gLineString.find("../../..") != string::npos) {
ReplaceAll(gLineString,"../../..", gSourceDir.c_str());
} else {
gLineString.insert(0, StringFormat("%s/../doc/macros/",gCwd.c_str()));
}
int i1 = gLineString.rfind('/')+1;
int i2 = gLineString.rfind('C');
gMacroName = gLineString.substr(i1,i2-i1+1);
// Build the ROOT command to be executed.
gLineString.insert(0, StringFormat("root -l -b -q \"makeimage.C(\\\""));
int l = gLineString.length();
gLineString.replace(l-2,1,StringFormat("C\\\",\\\"%s\\\",\\\"%s\\\",true)\"", gImageName.c_str(), gOutDir.c_str()));
ExecuteCommand(gLineString);
if (gImageSource) {
gLineString = StringFormat("\\include %s\n\\image html %s\n", gMacroName.c_str(), gImageName.c_str());
} else {
gLineString = StringFormat("\n\\image html %s\n", gImageName.c_str());
}
}
////////////////////////////////////////////////////////////////////////////////
/// Execute a command making sure stdout will not go in the doxygen file.
void ExecuteCommand(string command)
{
int o = dup(fileno(stdout));
freopen(gOutputName.c_str(),"a",stdout);
system(command.c_str());
dup2(o,fileno(stdout));
close(o);
}
////////////////////////////////////////////////////////////////////////////////
/// Replace all instances of a string with another string.
void ReplaceAll(string& str, const string& from, const string& to) {
if (from.empty()) return;
string wsRet;
wsRet.reserve(str.length());
size_t start_pos = 0, pos;
while ((pos = str.find(from, start_pos)) != string::npos) {
wsRet += str.substr(start_pos, pos - start_pos);
wsRet += to;
pos += from.length();
start_pos = pos;
}
wsRet += str.substr(start_pos);
str.swap(wsRet);
}
////////////////////////////////////////////////////////////////////////////////
/// std::string formatting like sprintf
string StringFormat(const string fmt_str, ...) {
int final_n, n = ((int)fmt_str.size()) * 2; /* Reserve two times as much as the length of the fmt_str */
string str;
unique_ptr<char[]> formatted;
va_list ap;
while (1) {
formatted.reset(new char[n]); /* Wrap the plain char array into the unique_ptr */
strcpy(&formatted[0], fmt_str.c_str());
va_start(ap, fmt_str);
final_n = vsnprintf(&formatted[0], n, fmt_str.c_str(), ap);
va_end(ap);
if (final_n < 0 || final_n >= n) n += abs(final_n - n + 1);
else break;
}
return string(formatted.get());
}
////////////////////////////////////////////////////////////////////////////////
/// find if a string ends with another string
bool EndsWith(string const &fullString, string const &ending) {
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}
////////////////////////////////////////////////////////////////////////////////
/// find if a string begins with another string
bool BeginsWith(const string& haystack, const string& needle) {
return needle.length() <= haystack.length() && equal(needle.begin(), needle.end(), haystack.begin());
}
<|endoftext|>
|
<commit_before>//===--- Rewriter.cpp - Code rewriting interface --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the Rewriter class, which is used for code
// transformations.
//
//===----------------------------------------------------------------------===//
#include "clang/Rewrite/Rewriter.h"
#include "clang/AST/Stmt.h"
#include "clang/Lex/Lexer.h"
#include "clang/Basic/SourceManager.h"
#include <sstream>
using namespace clang;
/// getMappedOffset - Given an offset into the original SourceBuffer that this
/// RewriteBuffer is based on, map it into the offset space of the
/// RewriteBuffer.
unsigned RewriteBuffer::getMappedOffset(unsigned OrigOffset,
bool AfterInserts) const {
unsigned ResultOffset = OrigOffset;
unsigned DeltaIdx = 0;
// Move past any deltas that are relevant.
// FIXME: binary search.
for (; DeltaIdx != Deltas.size() &&
Deltas[DeltaIdx].FileLoc < OrigOffset; ++DeltaIdx)
ResultOffset += Deltas[DeltaIdx].Delta;
if (AfterInserts && DeltaIdx != Deltas.size() &&
OrigOffset == Deltas[DeltaIdx].FileLoc)
ResultOffset += Deltas[DeltaIdx].Delta;
return ResultOffset;
}
/// AddDelta - When a change is made that shifts around the text buffer, this
/// method is used to record that info.
void RewriteBuffer::AddDelta(unsigned OrigOffset, int Change) {
assert(Change != 0 && "Not changing anything");
unsigned DeltaIdx = 0;
// Skip over any unrelated deltas.
for (; DeltaIdx != Deltas.size() &&
Deltas[DeltaIdx].FileLoc < OrigOffset; ++DeltaIdx)
;
// If there is no a delta for this offset, insert a new delta record.
if (DeltaIdx == Deltas.size() || OrigOffset != Deltas[DeltaIdx].FileLoc) {
// If this is a removal, check to see if this can be folded into
// a delta at the end of the deletion. For example, if we have:
// ABCXDEF (X inserted after C) and delete C, we want to end up with no
// delta because X basically replaced C.
if (Change < 0 && DeltaIdx != Deltas.size() &&
OrigOffset-Change == Deltas[DeltaIdx].FileLoc) {
// Adjust the start of the delta to be the start of the deleted region.
Deltas[DeltaIdx].FileLoc += Change;
Deltas[DeltaIdx].Delta += Change;
// If the delta becomes a noop, remove it.
if (Deltas[DeltaIdx].Delta == 0)
Deltas.erase(Deltas.begin()+DeltaIdx);
return;
}
// Otherwise, create an entry and return.
Deltas.insert(Deltas.begin()+DeltaIdx,
SourceDelta::get(OrigOffset, Change));
return;
}
// Otherwise, we found a delta record at this offset, adjust it.
Deltas[DeltaIdx].Delta += Change;
// If it is now dead, remove it.
if (Deltas[DeltaIdx].Delta)
Deltas.erase(Deltas.begin()+DeltaIdx);
}
void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size) {
// Nothing to remove, exit early.
if (Size == 0) return;
unsigned RealOffset = getMappedOffset(OrigOffset, true);
assert(RealOffset+Size < Buffer.size() && "Invalid location");
// Remove the dead characters.
Buffer.erase(Buffer.begin()+RealOffset, Buffer.begin()+RealOffset+Size);
// Add a delta so that future changes are offset correctly.
AddDelta(OrigOffset, -Size);
}
void RewriteBuffer::InsertText(unsigned OrigOffset,
const char *StrData, unsigned StrLen) {
// Nothing to insert, exit early.
if (StrLen == 0) return;
unsigned RealOffset = getMappedOffset(OrigOffset, true);
assert(RealOffset <= Buffer.size() && "Invalid location");
// Remove the dead characters.
Buffer.insert(Buffer.begin()+RealOffset, StrData, StrData+StrLen);
// Add a delta so that future changes are offset correctly.
AddDelta(OrigOffset, StrLen);
}
/// ReplaceText - This method replaces a range of characters in the input
/// buffer with a new string. This is effectively a combined "remove/insert"
/// operation.
void RewriteBuffer::ReplaceText(unsigned OrigOffset, unsigned OrigLength,
const char *NewStr, unsigned NewLength) {
unsigned RealOffset = getMappedOffset(OrigOffset);
assert(RealOffset+OrigLength <= Buffer.size() && "Invalid location");
// Overwrite the common piece.
memcpy(&Buffer[RealOffset], NewStr, std::min(OrigLength, NewLength));
// If replacing without shifting around, just overwrite the text.
if (OrigLength == NewLength)
return;
// If inserting more than existed before, this is like an insertion.
if (NewLength > OrigLength) {
Buffer.insert(Buffer.begin()+RealOffset+OrigLength,
NewStr+OrigLength, NewStr+NewLength);
} else {
// If insertion less than existed before, this is like a removal.
Buffer.erase(Buffer.begin()+RealOffset+NewLength,
Buffer.begin()+RealOffset+OrigLength);
}
AddDelta(OrigOffset, NewLength-OrigLength);
}
//===----------------------------------------------------------------------===//
// Rewriter class
//===----------------------------------------------------------------------===//
/// getRangeSize - Return the size in bytes of the specified range if they
/// are in the same file. If not, this returns -1.
int Rewriter::getRangeSize(SourceRange Range) const {
if (!isRewritable(Range.getBegin()) ||
!isRewritable(Range.getEnd())) return -1;
unsigned StartOff, StartFileID;
unsigned EndOff , EndFileID;
StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
if (StartFileID != EndFileID)
return -1;
// If edits have been made to this buffer, the delta between the range may
// have changed.
std::map<unsigned, RewriteBuffer>::const_iterator I =
RewriteBuffers.find(StartFileID);
if (I != RewriteBuffers.end()) {
const RewriteBuffer &RB = I->second;
EndOff = RB.getMappedOffset(EndOff, true);
StartOff = RB.getMappedOffset(StartOff);
}
// Adjust the end offset to the end of the last token, instead of being the
// start of the last token.
EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr);
return EndOff-StartOff;
}
unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc,
unsigned &FileID) const {
std::pair<unsigned,unsigned> V = SourceMgr->getDecomposedFileLoc(Loc);
FileID = V.first;
return V.second;
}
/// getEditBuffer - Get or create a RewriteBuffer for the specified FileID.
///
RewriteBuffer &Rewriter::getEditBuffer(unsigned FileID) {
std::map<unsigned, RewriteBuffer>::iterator I =
RewriteBuffers.lower_bound(FileID);
if (I != RewriteBuffers.end() && I->first == FileID)
return I->second;
I = RewriteBuffers.insert(I, std::make_pair(FileID, RewriteBuffer()));
std::pair<const char*, const char*> MB = SourceMgr->getBufferData(FileID);
I->second.Initialize(MB.first, MB.second);
return I->second;
}
/// RemoveText - Remove the specified text region. This method is only valid
/// on a rewritable source location.
void Rewriter::RemoveText(SourceLocation Start, unsigned Length) {
unsigned FileID;
unsigned StartOffs = getLocationOffsetAndFileID(Start, FileID);
getEditBuffer(FileID).RemoveText(StartOffs, Length);
}
/// ReplaceText - This method replaces a range of characters in the input
/// buffer with a new string. This is effectively a combined "remove/insert"
/// operation.
void Rewriter::ReplaceText(SourceLocation Start, unsigned OrigLength,
const char *NewStr, unsigned NewLength) {
assert(isRewritable(Start) && "Not a rewritable location!");
unsigned StartFileID;
unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID);
getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength,
NewStr, NewLength);
}
/// ReplaceStmt - This replaces a Stmt/Expr with another, using the pretty
/// printer to generate the replacement code. This returns true if the input
/// could not be rewritten, or false if successful.
bool Rewriter::ReplaceStmt(Stmt *From, Stmt *To) {
// Measaure the old text.
int Size = getRangeSize(From->getSourceRange());
if (Size == -1)
return true;
// Get the new text.
std::ostringstream S;
To->printPretty(S);
const std::string &Str = S.str();
ReplaceText(From->getLocStart(), Size, &Str[0], Str.size());
return false;
}
<commit_msg>Expose InsertText, fixing an oversight.<commit_after>//===--- Rewriter.cpp - Code rewriting interface --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the Rewriter class, which is used for code
// transformations.
//
//===----------------------------------------------------------------------===//
#include "clang/Rewrite/Rewriter.h"
#include "clang/AST/Stmt.h"
#include "clang/Lex/Lexer.h"
#include "clang/Basic/SourceManager.h"
#include <sstream>
using namespace clang;
/// getMappedOffset - Given an offset into the original SourceBuffer that this
/// RewriteBuffer is based on, map it into the offset space of the
/// RewriteBuffer.
unsigned RewriteBuffer::getMappedOffset(unsigned OrigOffset,
bool AfterInserts) const {
unsigned ResultOffset = OrigOffset;
unsigned DeltaIdx = 0;
// Move past any deltas that are relevant.
// FIXME: binary search.
for (; DeltaIdx != Deltas.size() &&
Deltas[DeltaIdx].FileLoc < OrigOffset; ++DeltaIdx)
ResultOffset += Deltas[DeltaIdx].Delta;
if (AfterInserts && DeltaIdx != Deltas.size() &&
OrigOffset == Deltas[DeltaIdx].FileLoc)
ResultOffset += Deltas[DeltaIdx].Delta;
return ResultOffset;
}
/// AddDelta - When a change is made that shifts around the text buffer, this
/// method is used to record that info.
void RewriteBuffer::AddDelta(unsigned OrigOffset, int Change) {
assert(Change != 0 && "Not changing anything");
unsigned DeltaIdx = 0;
// Skip over any unrelated deltas.
for (; DeltaIdx != Deltas.size() &&
Deltas[DeltaIdx].FileLoc < OrigOffset; ++DeltaIdx)
;
// If there is no a delta for this offset, insert a new delta record.
if (DeltaIdx == Deltas.size() || OrigOffset != Deltas[DeltaIdx].FileLoc) {
// If this is a removal, check to see if this can be folded into
// a delta at the end of the deletion. For example, if we have:
// ABCXDEF (X inserted after C) and delete C, we want to end up with no
// delta because X basically replaced C.
if (Change < 0 && DeltaIdx != Deltas.size() &&
OrigOffset-Change == Deltas[DeltaIdx].FileLoc) {
// Adjust the start of the delta to be the start of the deleted region.
Deltas[DeltaIdx].FileLoc += Change;
Deltas[DeltaIdx].Delta += Change;
// If the delta becomes a noop, remove it.
if (Deltas[DeltaIdx].Delta == 0)
Deltas.erase(Deltas.begin()+DeltaIdx);
return;
}
// Otherwise, create an entry and return.
Deltas.insert(Deltas.begin()+DeltaIdx,
SourceDelta::get(OrigOffset, Change));
return;
}
// Otherwise, we found a delta record at this offset, adjust it.
Deltas[DeltaIdx].Delta += Change;
// If it is now dead, remove it.
if (Deltas[DeltaIdx].Delta)
Deltas.erase(Deltas.begin()+DeltaIdx);
}
void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size) {
// Nothing to remove, exit early.
if (Size == 0) return;
unsigned RealOffset = getMappedOffset(OrigOffset, true);
assert(RealOffset+Size < Buffer.size() && "Invalid location");
// Remove the dead characters.
Buffer.erase(Buffer.begin()+RealOffset, Buffer.begin()+RealOffset+Size);
// Add a delta so that future changes are offset correctly.
AddDelta(OrigOffset, -Size);
}
void RewriteBuffer::InsertText(unsigned OrigOffset,
const char *StrData, unsigned StrLen) {
// Nothing to insert, exit early.
if (StrLen == 0) return;
unsigned RealOffset = getMappedOffset(OrigOffset, true);
assert(RealOffset <= Buffer.size() && "Invalid location");
// Remove the dead characters.
Buffer.insert(Buffer.begin()+RealOffset, StrData, StrData+StrLen);
// Add a delta so that future changes are offset correctly.
AddDelta(OrigOffset, StrLen);
}
/// ReplaceText - This method replaces a range of characters in the input
/// buffer with a new string. This is effectively a combined "remove/insert"
/// operation.
void RewriteBuffer::ReplaceText(unsigned OrigOffset, unsigned OrigLength,
const char *NewStr, unsigned NewLength) {
unsigned RealOffset = getMappedOffset(OrigOffset);
assert(RealOffset+OrigLength <= Buffer.size() && "Invalid location");
// Overwrite the common piece.
memcpy(&Buffer[RealOffset], NewStr, std::min(OrigLength, NewLength));
// If replacing without shifting around, just overwrite the text.
if (OrigLength == NewLength)
return;
// If inserting more than existed before, this is like an insertion.
if (NewLength > OrigLength) {
Buffer.insert(Buffer.begin()+RealOffset+OrigLength,
NewStr+OrigLength, NewStr+NewLength);
} else {
// If insertion less than existed before, this is like a removal.
Buffer.erase(Buffer.begin()+RealOffset+NewLength,
Buffer.begin()+RealOffset+OrigLength);
}
AddDelta(OrigOffset, NewLength-OrigLength);
}
//===----------------------------------------------------------------------===//
// Rewriter class
//===----------------------------------------------------------------------===//
/// getRangeSize - Return the size in bytes of the specified range if they
/// are in the same file. If not, this returns -1.
int Rewriter::getRangeSize(SourceRange Range) const {
if (!isRewritable(Range.getBegin()) ||
!isRewritable(Range.getEnd())) return -1;
unsigned StartOff, StartFileID;
unsigned EndOff , EndFileID;
StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
if (StartFileID != EndFileID)
return -1;
// If edits have been made to this buffer, the delta between the range may
// have changed.
std::map<unsigned, RewriteBuffer>::const_iterator I =
RewriteBuffers.find(StartFileID);
if (I != RewriteBuffers.end()) {
const RewriteBuffer &RB = I->second;
EndOff = RB.getMappedOffset(EndOff, true);
StartOff = RB.getMappedOffset(StartOff);
}
// Adjust the end offset to the end of the last token, instead of being the
// start of the last token.
EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr);
return EndOff-StartOff;
}
unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc,
unsigned &FileID) const {
std::pair<unsigned,unsigned> V = SourceMgr->getDecomposedFileLoc(Loc);
FileID = V.first;
return V.second;
}
/// getEditBuffer - Get or create a RewriteBuffer for the specified FileID.
///
RewriteBuffer &Rewriter::getEditBuffer(unsigned FileID) {
std::map<unsigned, RewriteBuffer>::iterator I =
RewriteBuffers.lower_bound(FileID);
if (I != RewriteBuffers.end() && I->first == FileID)
return I->second;
I = RewriteBuffers.insert(I, std::make_pair(FileID, RewriteBuffer()));
std::pair<const char*, const char*> MB = SourceMgr->getBufferData(FileID);
I->second.Initialize(MB.first, MB.second);
return I->second;
}
/// InsertText - Insert the specified string at the specified location in the
/// original buffer. This method is only valid on rewritable source
/// locations.
void Rewriter::InsertText(SourceLocation Loc,
const char *StrData, unsigned StrLen) {
unsigned FileID;
unsigned StartOffs = getLocationOffsetAndFileID(Loc, FileID);
getEditBuffer(FileID).InsertText(StartOffs, StrData, StrLen);
}
/// RemoveText - Remove the specified text region. This method is only valid
/// on a rewritable source location.
void Rewriter::RemoveText(SourceLocation Start, unsigned Length) {
unsigned FileID;
unsigned StartOffs = getLocationOffsetAndFileID(Start, FileID);
getEditBuffer(FileID).RemoveText(StartOffs, Length);
}
/// ReplaceText - This method replaces a range of characters in the input
/// buffer with a new string. This is effectively a combined "remove/insert"
/// operation.
void Rewriter::ReplaceText(SourceLocation Start, unsigned OrigLength,
const char *NewStr, unsigned NewLength) {
assert(isRewritable(Start) && "Not a rewritable location!");
unsigned StartFileID;
unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID);
getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength,
NewStr, NewLength);
}
/// ReplaceStmt - This replaces a Stmt/Expr with another, using the pretty
/// printer to generate the replacement code. This returns true if the input
/// could not be rewritten, or false if successful.
bool Rewriter::ReplaceStmt(Stmt *From, Stmt *To) {
// Measaure the old text.
int Size = getRangeSize(From->getSourceRange());
if (Size == -1)
return true;
// Get the new text.
std::ostringstream S;
To->printPretty(S);
const std::string &Str = S.str();
ReplaceText(From->getLocStart(), Size, &Str[0], Str.size());
return false;
}
<|endoftext|>
|
<commit_before>#include "diff_system.h"
#include "dof_map.h"
#include "numeric_vector.h"
#include "time_solver.h"
DifferentiableSystem::DifferentiableSystem
(EquationSystems& es,
const std::string& name,
const unsigned int number) :
Parent (es, name, number),
compute_internal_sides(false),
postprocess_sides(false),
time_solver (NULL),
time(0.),
deltat(1.),
print_solution_norms(false),
print_residual_norms(false),
print_residuals(false),
print_jacobian_norms(false),
print_jacobians(false),
current_local_nonlinear_solution(NumericVector<Number>::build())
{
untested();
}
DifferentiableSystem::~DifferentiableSystem ()
{
}
void DifferentiableSystem::reinit ()
{
Parent::reinit();
// Resize the serial nonlinear solution for the current mesh
current_local_nonlinear_solution->init (this->n_dofs());
time_solver->reinit();
}
void DifferentiableSystem::init_data ()
{
// First, allocate a vector for the iterate in our quasi_Newton
// solver
// FIXME - there really ought to be a way to just use the System
// solution vector if the solver doesn't need an extra vector!
// We don't want to project more solutions than we have to
// this->add_vector("_nonlinear_solution", false);
this->add_vector("_nonlinear_solution");
// this->project_solution_on_reinit() = false;
// Next, give us flags for every variable that might be time
// evolving
_time_evolving.resize(this->n_vars(), false);
// Do any initialization our solvers need
assert (time_solver.get() != NULL);
time_solver->init();
// Next initialize ImplicitSystem data
Parent::init_data();
// Finally initialize solution/residual/jacobian data structures
unsigned int n_vars = this->n_vars();
dof_indices_var.resize(n_vars);
elem_subsolutions.clear();
elem_subsolutions.reserve(n_vars);
elem_subresiduals.clear();
elem_subresiduals.reserve(n_vars);
elem_subjacobians.clear();
elem_subjacobians.resize(n_vars);
for (unsigned int i=0; i != n_vars; ++i)
{
elem_subsolutions.push_back(new DenseSubVector<Number>(elem_solution));
elem_subresiduals.push_back(new DenseSubVector<Number>(elem_residual));
elem_subjacobians[i].clear();
elem_subjacobians[i].reserve(n_vars);
for (unsigned int j=0; j != n_vars; ++j)
{
elem_subjacobians[i].push_back
(new DenseSubMatrix<Number>(elem_jacobian));
}
}
// Resize the serial nonlinear solution for the current mesh
current_local_nonlinear_solution->init (this->n_dofs());
}
void DifferentiableSystem::assemble ()
{
this->assembly(true, true);
}
void DifferentiableSystem::solve ()
{
time_solver->solve();
}
Number DifferentiableSystem::current_nonlinear_solution (const unsigned int global_dof_number) const
{
// Check the sizes
assert (global_dof_number < this->get_dof_map().n_dofs());
assert (global_dof_number < current_local_nonlinear_solution->size());
return (*current_local_nonlinear_solution)(global_dof_number);
}
<commit_msg>Make sure print_solutions is initialized to a sane default<commit_after>#include "diff_system.h"
#include "dof_map.h"
#include "numeric_vector.h"
#include "time_solver.h"
DifferentiableSystem::DifferentiableSystem
(EquationSystems& es,
const std::string& name,
const unsigned int number) :
Parent (es, name, number),
compute_internal_sides(false),
postprocess_sides(false),
time_solver (NULL),
time(0.),
deltat(1.),
print_solution_norms(false),
print_solutions(false),
print_residual_norms(false),
print_residuals(false),
print_jacobian_norms(false),
print_jacobians(false),
current_local_nonlinear_solution(NumericVector<Number>::build())
{
untested();
}
DifferentiableSystem::~DifferentiableSystem ()
{
}
void DifferentiableSystem::reinit ()
{
Parent::reinit();
// Resize the serial nonlinear solution for the current mesh
current_local_nonlinear_solution->init (this->n_dofs());
time_solver->reinit();
}
void DifferentiableSystem::init_data ()
{
// First, allocate a vector for the iterate in our quasi_Newton
// solver
// FIXME - there really ought to be a way to just use the System
// solution vector if the solver doesn't need an extra vector!
// We don't want to project more solutions than we have to
// this->add_vector("_nonlinear_solution", false);
this->add_vector("_nonlinear_solution");
// this->project_solution_on_reinit() = false;
// Next, give us flags for every variable that might be time
// evolving
_time_evolving.resize(this->n_vars(), false);
// Do any initialization our solvers need
assert (time_solver.get() != NULL);
time_solver->init();
// Next initialize ImplicitSystem data
Parent::init_data();
// Finally initialize solution/residual/jacobian data structures
unsigned int n_vars = this->n_vars();
dof_indices_var.resize(n_vars);
elem_subsolutions.clear();
elem_subsolutions.reserve(n_vars);
elem_subresiduals.clear();
elem_subresiduals.reserve(n_vars);
elem_subjacobians.clear();
elem_subjacobians.resize(n_vars);
for (unsigned int i=0; i != n_vars; ++i)
{
elem_subsolutions.push_back(new DenseSubVector<Number>(elem_solution));
elem_subresiduals.push_back(new DenseSubVector<Number>(elem_residual));
elem_subjacobians[i].clear();
elem_subjacobians[i].reserve(n_vars);
for (unsigned int j=0; j != n_vars; ++j)
{
elem_subjacobians[i].push_back
(new DenseSubMatrix<Number>(elem_jacobian));
}
}
// Resize the serial nonlinear solution for the current mesh
current_local_nonlinear_solution->init (this->n_dofs());
}
void DifferentiableSystem::assemble ()
{
this->assembly(true, true);
}
void DifferentiableSystem::solve ()
{
time_solver->solve();
}
Number DifferentiableSystem::current_nonlinear_solution (const unsigned int global_dof_number) const
{
// Check the sizes
assert (global_dof_number < this->get_dof_map().n_dofs());
assert (global_dof_number < current_local_nonlinear_solution->size());
return (*current_local_nonlinear_solution)(global_dof_number);
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include <chrono>
#ifdef __ANDROID__
# include <cstdlib>
#endif
#include "VLCMetadataService.h"
#include "Media.h"
#include "utils/VLCInstance.h"
namespace medialibrary
{
VLCMetadataService::VLCMetadataService()
: m_instance( VLCInstance::get() )
{
}
parser::Task::Status VLCMetadataService::run( parser::Task& task )
{
auto media = task.media;
auto file = task.file;
// FIXME: This is now becomming an invalid predicate
if ( media->duration() != -1 )
{
LOG_INFO( file->mrl(), " was already parsed" );
return parser::Task::Status::Success;
}
LOG_INFO( "Parsing ", file->mrl() );
auto chrono = std::chrono::steady_clock::now();
auto vlcMedia = VLC::Media( m_instance, file->mrl(), VLC::Media::FromPath );
std::unique_lock<compat::Mutex> lock( m_mutex );
VLC::Media::ParsedStatus status;
bool done = false;
auto event = vlcMedia.eventManager().onParsedChanged( [this, &status, &done](VLC::Media::ParsedStatus s ) {
std::lock_guard<compat::Mutex> lock( m_mutex );
status = s;
done = true;
m_cond.notify_all();
});
if ( vlcMedia.parseWithOptions( VLC::Media::ParseFlags::Local, 5000 ) == false )
return parser::Task::Status::Fatal;
m_cond.wait( lock, [&status, &done]() {
return done == true;
});
event->unregister();
if ( status == VLC::Media::ParsedStatus::Failed || status == VLC::Media::ParsedStatus::Timeout )
return parser::Task::Status::Fatal;
auto tracks = vlcMedia.tracks();
if ( tracks.size() == 0 )
{
LOG_ERROR( "Failed to fetch any tracks" );
return parser::Task::Status::Fatal;
}
for ( const auto& track : tracks )
{
auto codec = track.codec();
std::string fcc( reinterpret_cast<const char*>( &codec ), 4 );
if ( track.type() == VLC::MediaTrack::Video )
{
auto fps = static_cast<float>( track.fpsNum() ) / static_cast<float>( track.fpsDen() );
task.videoTracks.emplace_back( fcc, fps, track.width(), track.height(), track.language(),
track.description() );
}
else if ( track.type() == VLC::MediaTrack::Audio )
{
task.audioTracks.emplace_back( fcc, track.bitrate(), track.rate(), track.channels(),
track.language(), track.description() );
}
}
storeMeta( task, vlcMedia );
auto duration = std::chrono::steady_clock::now() - chrono;
LOG_DEBUG("VLC parsing done in ", std::chrono::duration_cast<std::chrono::microseconds>( duration ).count(), "µs" );
return parser::Task::Status::Success;
}
const char* VLCMetadataService::name() const
{
return "VLC";
}
uint8_t VLCMetadataService::nbThreads() const
{
return 1;
}
void VLCMetadataService::storeMeta( parser::Task& task, VLC::Media& vlcMedia )
{
#if LIBVLC_VERSION_INT >= LIBVLC_VERSION(3, 0, 0, 0)
task.albumArtist = vlcMedia.meta( libvlc_meta_AlbumArtist );
task.discNumber = toInt( vlcMedia, libvlc_meta_DiscNumber, "disc number" );
task.discTotal = toInt( vlcMedia, libvlc_meta_DiscTotal, "disc total" );
#else
task.discNumber = 0;
task.discTotal = 0;
#endif
task.artist = vlcMedia.meta( libvlc_meta_Artist );
task.artworkMrl = vlcMedia.meta( libvlc_meta_ArtworkURL );
task.title = vlcMedia.meta( libvlc_meta_Title );
task.genre = vlcMedia.meta( libvlc_meta_Genre );
task.releaseDate = vlcMedia.meta( libvlc_meta_Date );
task.showName = vlcMedia.meta( libvlc_meta_ShowName );
task.albumName = vlcMedia.meta( libvlc_meta_Album );
task.duration = vlcMedia.duration();
task.trackNumber = toInt( vlcMedia, libvlc_meta_TrackNumber, "track number" );
task.episode = toInt( vlcMedia, libvlc_meta_Episode, "episode number" );
}
int VLCMetadataService::toInt( VLC::Media& vlcMedia, libvlc_meta_t meta, const char* name )
{
auto str = vlcMedia.meta( meta );
if ( str.empty() == false )
{
#ifndef __ANDROID__
try
{
return std::stoi( str );
}
catch( std::logic_error& ex)
{
LOG_WARN( "Invalid ", name, " provided (", str, "): ", ex.what() );
}
#else
return atoi( str.c_str() );
#endif
}
return 0;
}
}
<commit_msg>VLCMetadataService: Log the MRL for which we can't fetch any tracks<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include <chrono>
#ifdef __ANDROID__
# include <cstdlib>
#endif
#include "VLCMetadataService.h"
#include "Media.h"
#include "utils/VLCInstance.h"
namespace medialibrary
{
VLCMetadataService::VLCMetadataService()
: m_instance( VLCInstance::get() )
{
}
parser::Task::Status VLCMetadataService::run( parser::Task& task )
{
auto media = task.media;
auto file = task.file;
// FIXME: This is now becomming an invalid predicate
if ( media->duration() != -1 )
{
LOG_INFO( file->mrl(), " was already parsed" );
return parser::Task::Status::Success;
}
LOG_INFO( "Parsing ", file->mrl() );
auto chrono = std::chrono::steady_clock::now();
auto vlcMedia = VLC::Media( m_instance, file->mrl(), VLC::Media::FromPath );
std::unique_lock<compat::Mutex> lock( m_mutex );
VLC::Media::ParsedStatus status;
bool done = false;
auto event = vlcMedia.eventManager().onParsedChanged( [this, &status, &done](VLC::Media::ParsedStatus s ) {
std::lock_guard<compat::Mutex> lock( m_mutex );
status = s;
done = true;
m_cond.notify_all();
});
if ( vlcMedia.parseWithOptions( VLC::Media::ParseFlags::Local, 5000 ) == false )
return parser::Task::Status::Fatal;
m_cond.wait( lock, [&status, &done]() {
return done == true;
});
event->unregister();
if ( status == VLC::Media::ParsedStatus::Failed || status == VLC::Media::ParsedStatus::Timeout )
return parser::Task::Status::Fatal;
auto tracks = vlcMedia.tracks();
if ( tracks.size() == 0 )
{
LOG_ERROR( "Failed to fetch any tracks for ", file->mrl() );
return parser::Task::Status::Fatal;
}
for ( const auto& track : tracks )
{
auto codec = track.codec();
std::string fcc( reinterpret_cast<const char*>( &codec ), 4 );
if ( track.type() == VLC::MediaTrack::Video )
{
auto fps = static_cast<float>( track.fpsNum() ) / static_cast<float>( track.fpsDen() );
task.videoTracks.emplace_back( fcc, fps, track.width(), track.height(), track.language(),
track.description() );
}
else if ( track.type() == VLC::MediaTrack::Audio )
{
task.audioTracks.emplace_back( fcc, track.bitrate(), track.rate(), track.channels(),
track.language(), track.description() );
}
}
storeMeta( task, vlcMedia );
auto duration = std::chrono::steady_clock::now() - chrono;
LOG_DEBUG("VLC parsing done in ", std::chrono::duration_cast<std::chrono::microseconds>( duration ).count(), "µs" );
return parser::Task::Status::Success;
}
const char* VLCMetadataService::name() const
{
return "VLC";
}
uint8_t VLCMetadataService::nbThreads() const
{
return 1;
}
void VLCMetadataService::storeMeta( parser::Task& task, VLC::Media& vlcMedia )
{
#if LIBVLC_VERSION_INT >= LIBVLC_VERSION(3, 0, 0, 0)
task.albumArtist = vlcMedia.meta( libvlc_meta_AlbumArtist );
task.discNumber = toInt( vlcMedia, libvlc_meta_DiscNumber, "disc number" );
task.discTotal = toInt( vlcMedia, libvlc_meta_DiscTotal, "disc total" );
#else
task.discNumber = 0;
task.discTotal = 0;
#endif
task.artist = vlcMedia.meta( libvlc_meta_Artist );
task.artworkMrl = vlcMedia.meta( libvlc_meta_ArtworkURL );
task.title = vlcMedia.meta( libvlc_meta_Title );
task.genre = vlcMedia.meta( libvlc_meta_Genre );
task.releaseDate = vlcMedia.meta( libvlc_meta_Date );
task.showName = vlcMedia.meta( libvlc_meta_ShowName );
task.albumName = vlcMedia.meta( libvlc_meta_Album );
task.duration = vlcMedia.duration();
task.trackNumber = toInt( vlcMedia, libvlc_meta_TrackNumber, "track number" );
task.episode = toInt( vlcMedia, libvlc_meta_Episode, "episode number" );
}
int VLCMetadataService::toInt( VLC::Media& vlcMedia, libvlc_meta_t meta, const char* name )
{
auto str = vlcMedia.meta( meta );
if ( str.empty() == false )
{
#ifndef __ANDROID__
try
{
return std::stoi( str );
}
catch( std::logic_error& ex)
{
LOG_WARN( "Invalid ", name, " provided (", str, "): ", ex.what() );
}
#else
return atoi( str.c_str() );
#endif
}
return 0;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DAVProperties.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-20 05:33:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DAVPROPERTIES_HXX_
#define _DAVPROPERTIES_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _NEONTYPES_HXX_
#include "NeonTypes.hxx"
#endif
namespace webdav_ucp
{
struct DAVProperties
{
static const ::rtl::OUString CREATIONDATE;
static const ::rtl::OUString DISPLAYNAME;
static const ::rtl::OUString GETCONTENTLANGUAGE;
static const ::rtl::OUString GETCONTENTLENGTH;
static const ::rtl::OUString GETCONTENTTYPE;
static const ::rtl::OUString GETETAG;
static const ::rtl::OUString GETLASTMODIFIED;
static const ::rtl::OUString LOCKDISCOVERY;
static const ::rtl::OUString RESOURCETYPE;
static const ::rtl::OUString SOURCE;
static const ::rtl::OUString SUPPORTEDLOCK;
static const ::rtl::OUString EXECUTABLE;
static void createNeonPropName( const rtl::OUString & rFullName,
NeonPropName & rName );
static void createUCBPropName ( const char * nspace,
const char * name,
rtl::OUString & rFullName );
static bool isUCBDeadProperty( const NeonPropName & rName );
};
} // namespace webdav_ucp
#endif // _DAVPROPERTIES_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.4.138); FILE MERGED 2008/04/01 16:02:24 thb 1.4.138.3: #i85898# Stripping all external header guards 2008/04/01 12:58:25 thb 1.4.138.2: #i85898# Stripping all external header guards 2008/03/31 15:30:29 rt 1.4.138.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: DAVProperties.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _DAVPROPERTIES_HXX_
#define _DAVPROPERTIES_HXX_
#include <rtl/ustring.hxx>
#include "NeonTypes.hxx"
namespace webdav_ucp
{
struct DAVProperties
{
static const ::rtl::OUString CREATIONDATE;
static const ::rtl::OUString DISPLAYNAME;
static const ::rtl::OUString GETCONTENTLANGUAGE;
static const ::rtl::OUString GETCONTENTLENGTH;
static const ::rtl::OUString GETCONTENTTYPE;
static const ::rtl::OUString GETETAG;
static const ::rtl::OUString GETLASTMODIFIED;
static const ::rtl::OUString LOCKDISCOVERY;
static const ::rtl::OUString RESOURCETYPE;
static const ::rtl::OUString SOURCE;
static const ::rtl::OUString SUPPORTEDLOCK;
static const ::rtl::OUString EXECUTABLE;
static void createNeonPropName( const rtl::OUString & rFullName,
NeonPropName & rName );
static void createUCBPropName ( const char * nspace,
const char * name,
rtl::OUString & rFullName );
static bool isUCBDeadProperty( const NeonPropName & rName );
};
} // namespace webdav_ucp
#endif // _DAVPROPERTIES_HXX_
<|endoftext|>
|
<commit_before>/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>
This file is part of Magnum.
Magnum 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.
Magnum 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.
*/
#include "Context.h"
#include <string>
#include <unordered_map>
#include <Utility/Debug.h>
#include <Utility/String.h>
#include "AbstractFramebuffer.h"
#include "AbstractShaderProgram.h"
#include "AbstractTexture.h"
#include "Buffer.h"
#include "BufferTexture.h"
#include "DebugMarker.h"
#include "DefaultFramebuffer.h"
#include "Extensions.h"
#include "Framebuffer.h"
#include "IndexedMesh.h"
#include "Mesh.h"
#include "Renderbuffer.h"
#include "Implementation/State.h"
namespace Magnum {
#ifndef DOXYGEN_GENERATING_OUTPUT
Debug operator<<(Debug debug, Version value) {
switch(value) {
#define _c(value, string) case Version::value: return debug << string;
_c(None, "None")
#ifndef MAGNUM_TARGET_GLES
_c(GL210, "OpenGL 2.1")
_c(GL300, "OpenGL 3.0")
_c(GL310, "OpenGL 3.1")
_c(GL320, "OpenGL 3.2")
_c(GL330, "OpenGL 3.3")
_c(GL400, "OpenGL 4.0")
_c(GL410, "OpenGL 4.1")
_c(GL420, "OpenGL 4.2")
_c(GL430, "OpenGL 4.3")
#else
_c(GLES200, "OpenGL ES 2.0")
_c(GLES300, "OpenGL ES 3.0")
#endif
#undef _c
}
return debug << "Invalid";
}
#endif
const std::vector<Extension>& Extension::extensions(Version version) {
#define _extension(prefix, vendor, extension) \
{Extensions::prefix::vendor::extension::Index, Extensions::prefix::vendor::extension::requiredVersion(), Extensions::prefix::vendor::extension::coreVersion(), Extensions::prefix::vendor::extension::string()}
static const std::vector<Extension> empty;
#ifndef MAGNUM_TARGET_GLES
static const std::vector<Extension> extensions{
_extension(GL,AMD,vertex_shader_layer), // done
_extension(GL,AMD,shader_trinary_minmax), // done
_extension(GL,EXT,texture_filter_anisotropic), // done
_extension(GL,EXT,direct_state_access),
_extension(GL,GREMEDY,string_marker)}; // done
static const std::vector<Extension> extensions300{
/**
* @todo Remove as it doesn't have all functionality present in GL 3.0
* and leave only ARB_map_buffer_range?
*/
_extension(GL,APPLE,flush_buffer_range), // done
_extension(GL,APPLE,vertex_array_object), // done
_extension(GL,ARB,map_buffer_range), // done, replaces APPLE_flush_buffer_range
_extension(GL,ARB,color_buffer_float),
_extension(GL,ARB,half_float_pixel), // done
_extension(GL,ARB,texture_float), // done
_extension(GL,ARB,depth_buffer_float), // done
_extension(GL,ARB,texture_rg), // done
/**
* @todo Remove as it doesn't have the same functionality present in
* GL 3.0 and replace with ARB_framebuffer_object?
*/
_extension(GL,EXT,framebuffer_object),
_extension(GL,EXT,packed_depth_stencil), // done
_extension(GL,EXT,framebuffer_blit), // done
_extension(GL,EXT,framebuffer_multisample),
_extension(GL,EXT,gpu_shader4),
_extension(GL,EXT,packed_float), // done
_extension(GL,EXT,texture_array),
_extension(GL,EXT,texture_compression_rgtc), // done
_extension(GL,EXT,texture_shared_exponent), // done
_extension(GL,EXT,framebuffer_sRGB),
_extension(GL,EXT,draw_buffers2),
_extension(GL,EXT,texture_integer),
_extension(GL,EXT,transform_feedback),
_extension(GL,NV,half_float), // done
_extension(GL,NV,depth_buffer_float),
_extension(GL,NV,conditional_render)}; // done
static const std::vector<Extension> extensions310{
_extension(GL,ARB,texture_rectangle),
_extension(GL,ARB,draw_instanced),
_extension(GL,ARB,texture_buffer_object),
_extension(GL,ARB,uniform_buffer_object),
_extension(GL,ARB,copy_buffer), // done
_extension(GL,EXT,texture_snorm), // done
_extension(GL,NV,primitive_restart)};
static const std::vector<Extension> extensions320{
_extension(GL,ARB,geometry_shader4),
_extension(GL,ARB,depth_clamp), // done
_extension(GL,ARB,draw_elements_base_vertex),
_extension(GL,ARB,fragment_coord_conventions), // done
_extension(GL,ARB,provoking_vertex), // done
_extension(GL,ARB,seamless_cube_map), // done
_extension(GL,ARB,sync),
_extension(GL,ARB,texture_multisample),
_extension(GL,ARB,vertex_array_bgra)}; // done
static const std::vector<Extension> extensions330{
_extension(GL,ARB,instanced_arrays),
_extension(GL,ARB,blend_func_extended),
_extension(GL,ARB,explicit_attrib_location), // done
_extension(GL,ARB,occlusion_query2), // done
_extension(GL,ARB,sampler_objects),
_extension(GL,ARB,shader_bit_encoding), // done
_extension(GL,ARB,texture_rgb10_a2ui), // done
_extension(GL,ARB,texture_swizzle),
_extension(GL,ARB,timer_query),
_extension(GL,ARB,vertex_type_2_10_10_10_rev)}; // done
static const std::vector<Extension> extensions400{
_extension(GL,ARB,draw_buffers_blend),
_extension(GL,ARB,sample_shading),
_extension(GL,ARB,texture_cube_map_array), // done
_extension(GL,ARB,texture_gather),
_extension(GL,ARB,texture_query_lod), // done
_extension(GL,ARB,draw_indirect),
_extension(GL,ARB,gpu_shader5),
_extension(GL,ARB,gpu_shader_fp64), // done
_extension(GL,ARB,shader_subroutine),
_extension(GL,ARB,tessellation_shader),
_extension(GL,ARB,texture_buffer_object_rgb32), // done
_extension(GL,ARB,transform_feedback2),
_extension(GL,ARB,transform_feedback3)};
static const std::vector<Extension> extensions410{
_extension(GL,ARB,ES2_compatibility),
_extension(GL,ARB,get_program_binary),
_extension(GL,ARB,separate_shader_objects),
_extension(GL,ARB,shader_precision), // done
_extension(GL,ARB,vertex_attrib_64bit), // done
_extension(GL,ARB,viewport_array)};
static const std::vector<Extension> extensions420{
_extension(GL,ARB,texture_compression_bptc), // done
_extension(GL,ARB,base_instance),
_extension(GL,ARB,shading_language_420pack), // done
_extension(GL,ARB,transform_feedback_instanced),
_extension(GL,ARB,compressed_texture_pixel_storage),
_extension(GL,ARB,conservative_depth), // done
_extension(GL,ARB,internalformat_query),
_extension(GL,ARB,map_buffer_alignment),
_extension(GL,ARB,shader_atomic_counters),
_extension(GL,ARB,shader_image_load_store),
_extension(GL,ARB,texture_storage)};
static const std::vector<Extension> extensions430{
_extension(GL,ARB,arrays_of_arrays), // done
_extension(GL,ARB,ES3_compatibility),
_extension(GL,ARB,clear_buffer_object),
_extension(GL,ARB,compute_shader),
_extension(GL,ARB,copy_image),
_extension(GL,KHR,debug),
_extension(GL,ARB,explicit_uniform_location),
_extension(GL,ARB,fragment_layer_viewport), // done
_extension(GL,ARB,framebuffer_no_attachments),
_extension(GL,ARB,internalformat_query2),
_extension(GL,ARB,invalidate_subdata),
_extension(GL,ARB,multi_draw_indirect),
_extension(GL,ARB,program_interface_query),
_extension(GL,ARB,robust_buffer_access_behavior), // done
_extension(GL,ARB,shader_image_size), // done
_extension(GL,ARB,shader_storage_buffer_object),
_extension(GL,ARB,stencil_texturing),
_extension(GL,ARB,texture_buffer_range), // done
_extension(GL,ARB,texture_query_levels), // done
_extension(GL,ARB,texture_storage_multisample),
_extension(GL,ARB,texture_view),
_extension(GL,ARB,vertex_attrib_binding)};
#undef _extension
#else
static const std::vector<Extension> extensions;
static const std::vector<Extension> extensionsES200;
static const std::vector<Extension> extensionsES300;
#endif
switch(version) {
case Version::None: return extensions;
#ifndef MAGNUM_TARGET_GLES
case Version::GL210: return empty;
case Version::GL300: return extensions300;
case Version::GL310: return extensions310;
case Version::GL320: return extensions320;
case Version::GL330: return extensions330;
case Version::GL400: return extensions400;
/* case Version::GLES200: */
case Version::GL410: return extensions410;
case Version::GL420: return extensions420;
/* case Version::GLES300: */
case Version::GL430: return extensions430;
#else
case Version::GLES200: return extensionsES200;
case Version::GLES300: return extensionsES300;
#endif
}
return empty;
}
Context* Context::_current = nullptr;
Context::Context() {
/* Version */
#ifndef MAGNUM_TARGET_GLES2
glGetIntegerv(GL_MAJOR_VERSION, &_majorVersion);
glGetIntegerv(GL_MINOR_VERSION, &_minorVersion);
#else
_majorVersion = 2;
_minorVersion = 0;
#endif
_version = static_cast<Version>(_majorVersion*100+_minorVersion*10);
/* Get first future (not supported) version */
std::vector<Version> versions{
#ifndef MAGNUM_TARGET_GLES
Version::GL300,
Version::GL310,
Version::GL320,
Version::GL330,
Version::GL400,
Version::GL410,
Version::GL420,
Version::GL430,
#else
Version::GLES200,
Version::GLES300,
#endif
Version::None
};
std::size_t future = 0;
while(versions[future] != Version::None && isVersionSupported(versions[future]))
++future;
/* List of extensions from future versions (extensions from current and
previous versions should be supported automatically, so we don't need
to check for them) */
std::unordered_map<std::string, Extension> futureExtensions;
for(std::size_t i = future; i != versions.size(); ++i)
for(const Extension& extension: Extension::extensions(versions[i]))
futureExtensions.insert(std::make_pair(extension._string, extension));
/* Check for presence of extensions in future versions */
#ifndef MAGNUM_TARGET_GLES
if(isVersionSupported(Version::GL300)) {
#else
if(isVersionSupported(Version::GLES300)) {
#endif
#ifndef MAGNUM_TARGET_GLES2
GLuint index = 0;
const char* extension;
while((extension = reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, index++)))) {
auto found = futureExtensions.find(extension);
if(found != futureExtensions.end()) {
_supportedExtensions.push_back(found->second);
extensionStatus.set(found->second._index);
}
}
#endif
/* OpenGL 2.1 / OpenGL ES 2.0 doesn't have glGetStringi() */
} else {
/* Don't crash when glGetString() returns nullptr */
const char* e = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
if(e) {
std::vector<std::string> extensions = Corrade::Utility::String::split(e, ' ');
for(const std::string& extension: extensions) {
auto found = futureExtensions.find(extension);
if(found != futureExtensions.end()) {
_supportedExtensions.push_back(found->second);
extensionStatus.set(found->second._index);
}
}
}
}
/* Set this context as current */
CORRADE_ASSERT(!_current, "Context: Another context currently active", );
_current = this;
/* Initialize state tracker */
_state = new Implementation::State;
/* Initialize functionality based on current OpenGL version and extensions */
AbstractFramebuffer::initializeContextBasedFunctionality(this);
AbstractShaderProgram::initializeContextBasedFunctionality(this);
AbstractTexture::initializeContextBasedFunctionality(this);
Buffer::initializeContextBasedFunctionality(this);
#ifndef MAGNUM_TARGET_GLES
BufferTexture::initializeContextBasedFunctionality(this);
#endif
DebugMarker::initializeContextBasedFunctionality(this);
DefaultFramebuffer::initializeContextBasedFunctionality(this);
Framebuffer::initializeContextBasedFunctionality(this);
IndexedMesh::initializeContextBasedFunctionality(this);
Mesh::initializeContextBasedFunctionality(this);
Renderbuffer::initializeContextBasedFunctionality(this);
}
Context::~Context() {
CORRADE_ASSERT(_current == this, "Context: Cannot destroy context which is not currently active", );
delete _state;
_current = nullptr;
}
Version Context::supportedVersion(std::initializer_list<Version> versions) const {
for(auto version: versions)
if(isVersionSupported(version)) return version;
#ifndef MAGNUM_TARGET_GLES
return Version::GL210;
#else
return Version::GLES200;
#endif
}
}
<commit_msg>ES 2.0 extension list is equivalent to GL 2.1 extension list -- empty.<commit_after>/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>
This file is part of Magnum.
Magnum 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.
Magnum 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.
*/
#include "Context.h"
#include <string>
#include <unordered_map>
#include <Utility/Debug.h>
#include <Utility/String.h>
#include "AbstractFramebuffer.h"
#include "AbstractShaderProgram.h"
#include "AbstractTexture.h"
#include "Buffer.h"
#include "BufferTexture.h"
#include "DebugMarker.h"
#include "DefaultFramebuffer.h"
#include "Extensions.h"
#include "Framebuffer.h"
#include "IndexedMesh.h"
#include "Mesh.h"
#include "Renderbuffer.h"
#include "Implementation/State.h"
namespace Magnum {
#ifndef DOXYGEN_GENERATING_OUTPUT
Debug operator<<(Debug debug, Version value) {
switch(value) {
#define _c(value, string) case Version::value: return debug << string;
_c(None, "None")
#ifndef MAGNUM_TARGET_GLES
_c(GL210, "OpenGL 2.1")
_c(GL300, "OpenGL 3.0")
_c(GL310, "OpenGL 3.1")
_c(GL320, "OpenGL 3.2")
_c(GL330, "OpenGL 3.3")
_c(GL400, "OpenGL 4.0")
_c(GL410, "OpenGL 4.1")
_c(GL420, "OpenGL 4.2")
_c(GL430, "OpenGL 4.3")
#else
_c(GLES200, "OpenGL ES 2.0")
_c(GLES300, "OpenGL ES 3.0")
#endif
#undef _c
}
return debug << "Invalid";
}
#endif
const std::vector<Extension>& Extension::extensions(Version version) {
#define _extension(prefix, vendor, extension) \
{Extensions::prefix::vendor::extension::Index, Extensions::prefix::vendor::extension::requiredVersion(), Extensions::prefix::vendor::extension::coreVersion(), Extensions::prefix::vendor::extension::string()}
static const std::vector<Extension> empty;
#ifndef MAGNUM_TARGET_GLES
static const std::vector<Extension> extensions{
_extension(GL,AMD,vertex_shader_layer), // done
_extension(GL,AMD,shader_trinary_minmax), // done
_extension(GL,EXT,texture_filter_anisotropic), // done
_extension(GL,EXT,direct_state_access),
_extension(GL,GREMEDY,string_marker)}; // done
static const std::vector<Extension> extensions300{
/**
* @todo Remove as it doesn't have all functionality present in GL 3.0
* and leave only ARB_map_buffer_range?
*/
_extension(GL,APPLE,flush_buffer_range), // done
_extension(GL,APPLE,vertex_array_object), // done
_extension(GL,ARB,map_buffer_range), // done, replaces APPLE_flush_buffer_range
_extension(GL,ARB,color_buffer_float),
_extension(GL,ARB,half_float_pixel), // done
_extension(GL,ARB,texture_float), // done
_extension(GL,ARB,depth_buffer_float), // done
_extension(GL,ARB,texture_rg), // done
/**
* @todo Remove as it doesn't have the same functionality present in
* GL 3.0 and replace with ARB_framebuffer_object?
*/
_extension(GL,EXT,framebuffer_object),
_extension(GL,EXT,packed_depth_stencil), // done
_extension(GL,EXT,framebuffer_blit), // done
_extension(GL,EXT,framebuffer_multisample),
_extension(GL,EXT,gpu_shader4),
_extension(GL,EXT,packed_float), // done
_extension(GL,EXT,texture_array),
_extension(GL,EXT,texture_compression_rgtc), // done
_extension(GL,EXT,texture_shared_exponent), // done
_extension(GL,EXT,framebuffer_sRGB),
_extension(GL,EXT,draw_buffers2),
_extension(GL,EXT,texture_integer),
_extension(GL,EXT,transform_feedback),
_extension(GL,NV,half_float), // done
_extension(GL,NV,depth_buffer_float),
_extension(GL,NV,conditional_render)}; // done
static const std::vector<Extension> extensions310{
_extension(GL,ARB,texture_rectangle),
_extension(GL,ARB,draw_instanced),
_extension(GL,ARB,texture_buffer_object),
_extension(GL,ARB,uniform_buffer_object),
_extension(GL,ARB,copy_buffer), // done
_extension(GL,EXT,texture_snorm), // done
_extension(GL,NV,primitive_restart)};
static const std::vector<Extension> extensions320{
_extension(GL,ARB,geometry_shader4),
_extension(GL,ARB,depth_clamp), // done
_extension(GL,ARB,draw_elements_base_vertex),
_extension(GL,ARB,fragment_coord_conventions), // done
_extension(GL,ARB,provoking_vertex), // done
_extension(GL,ARB,seamless_cube_map), // done
_extension(GL,ARB,sync),
_extension(GL,ARB,texture_multisample),
_extension(GL,ARB,vertex_array_bgra)}; // done
static const std::vector<Extension> extensions330{
_extension(GL,ARB,instanced_arrays),
_extension(GL,ARB,blend_func_extended),
_extension(GL,ARB,explicit_attrib_location), // done
_extension(GL,ARB,occlusion_query2), // done
_extension(GL,ARB,sampler_objects),
_extension(GL,ARB,shader_bit_encoding), // done
_extension(GL,ARB,texture_rgb10_a2ui), // done
_extension(GL,ARB,texture_swizzle),
_extension(GL,ARB,timer_query),
_extension(GL,ARB,vertex_type_2_10_10_10_rev)}; // done
static const std::vector<Extension> extensions400{
_extension(GL,ARB,draw_buffers_blend),
_extension(GL,ARB,sample_shading),
_extension(GL,ARB,texture_cube_map_array), // done
_extension(GL,ARB,texture_gather),
_extension(GL,ARB,texture_query_lod), // done
_extension(GL,ARB,draw_indirect),
_extension(GL,ARB,gpu_shader5),
_extension(GL,ARB,gpu_shader_fp64), // done
_extension(GL,ARB,shader_subroutine),
_extension(GL,ARB,tessellation_shader),
_extension(GL,ARB,texture_buffer_object_rgb32), // done
_extension(GL,ARB,transform_feedback2),
_extension(GL,ARB,transform_feedback3)};
static const std::vector<Extension> extensions410{
_extension(GL,ARB,ES2_compatibility),
_extension(GL,ARB,get_program_binary),
_extension(GL,ARB,separate_shader_objects),
_extension(GL,ARB,shader_precision), // done
_extension(GL,ARB,vertex_attrib_64bit), // done
_extension(GL,ARB,viewport_array)};
static const std::vector<Extension> extensions420{
_extension(GL,ARB,texture_compression_bptc), // done
_extension(GL,ARB,base_instance),
_extension(GL,ARB,shading_language_420pack), // done
_extension(GL,ARB,transform_feedback_instanced),
_extension(GL,ARB,compressed_texture_pixel_storage),
_extension(GL,ARB,conservative_depth), // done
_extension(GL,ARB,internalformat_query),
_extension(GL,ARB,map_buffer_alignment),
_extension(GL,ARB,shader_atomic_counters),
_extension(GL,ARB,shader_image_load_store),
_extension(GL,ARB,texture_storage)};
static const std::vector<Extension> extensions430{
_extension(GL,ARB,arrays_of_arrays), // done
_extension(GL,ARB,ES3_compatibility),
_extension(GL,ARB,clear_buffer_object),
_extension(GL,ARB,compute_shader),
_extension(GL,ARB,copy_image),
_extension(GL,KHR,debug),
_extension(GL,ARB,explicit_uniform_location),
_extension(GL,ARB,fragment_layer_viewport), // done
_extension(GL,ARB,framebuffer_no_attachments),
_extension(GL,ARB,internalformat_query2),
_extension(GL,ARB,invalidate_subdata),
_extension(GL,ARB,multi_draw_indirect),
_extension(GL,ARB,program_interface_query),
_extension(GL,ARB,robust_buffer_access_behavior), // done
_extension(GL,ARB,shader_image_size), // done
_extension(GL,ARB,shader_storage_buffer_object),
_extension(GL,ARB,stencil_texturing),
_extension(GL,ARB,texture_buffer_range), // done
_extension(GL,ARB,texture_query_levels), // done
_extension(GL,ARB,texture_storage_multisample),
_extension(GL,ARB,texture_view),
_extension(GL,ARB,vertex_attrib_binding)};
#undef _extension
#else
static const std::vector<Extension> extensions;
static const std::vector<Extension> extensionsES300;
#endif
switch(version) {
case Version::None: return extensions;
#ifndef MAGNUM_TARGET_GLES
case Version::GL210: return empty;
case Version::GL300: return extensions300;
case Version::GL310: return extensions310;
case Version::GL320: return extensions320;
case Version::GL330: return extensions330;
case Version::GL400: return extensions400;
/* case Version::GLES200: */
case Version::GL410: return extensions410;
case Version::GL420: return extensions420;
/* case Version::GLES300: */
case Version::GL430: return extensions430;
#else
case Version::GLES200: return empty;
case Version::GLES300: return extensionsES300;
#endif
}
return empty;
}
Context* Context::_current = nullptr;
Context::Context() {
/* Version */
#ifndef MAGNUM_TARGET_GLES2
glGetIntegerv(GL_MAJOR_VERSION, &_majorVersion);
glGetIntegerv(GL_MINOR_VERSION, &_minorVersion);
#else
_majorVersion = 2;
_minorVersion = 0;
#endif
_version = static_cast<Version>(_majorVersion*100+_minorVersion*10);
/* Get first future (not supported) version */
std::vector<Version> versions{
#ifndef MAGNUM_TARGET_GLES
Version::GL300,
Version::GL310,
Version::GL320,
Version::GL330,
Version::GL400,
Version::GL410,
Version::GL420,
Version::GL430,
#else
Version::GLES200,
Version::GLES300,
#endif
Version::None
};
std::size_t future = 0;
while(versions[future] != Version::None && isVersionSupported(versions[future]))
++future;
/* List of extensions from future versions (extensions from current and
previous versions should be supported automatically, so we don't need
to check for them) */
std::unordered_map<std::string, Extension> futureExtensions;
for(std::size_t i = future; i != versions.size(); ++i)
for(const Extension& extension: Extension::extensions(versions[i]))
futureExtensions.insert(std::make_pair(extension._string, extension));
/* Check for presence of extensions in future versions */
#ifndef MAGNUM_TARGET_GLES
if(isVersionSupported(Version::GL300)) {
#else
if(isVersionSupported(Version::GLES300)) {
#endif
#ifndef MAGNUM_TARGET_GLES2
GLuint index = 0;
const char* extension;
while((extension = reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, index++)))) {
auto found = futureExtensions.find(extension);
if(found != futureExtensions.end()) {
_supportedExtensions.push_back(found->second);
extensionStatus.set(found->second._index);
}
}
#endif
/* OpenGL 2.1 / OpenGL ES 2.0 doesn't have glGetStringi() */
} else {
/* Don't crash when glGetString() returns nullptr */
const char* e = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
if(e) {
std::vector<std::string> extensions = Corrade::Utility::String::split(e, ' ');
for(const std::string& extension: extensions) {
auto found = futureExtensions.find(extension);
if(found != futureExtensions.end()) {
_supportedExtensions.push_back(found->second);
extensionStatus.set(found->second._index);
}
}
}
}
/* Set this context as current */
CORRADE_ASSERT(!_current, "Context: Another context currently active", );
_current = this;
/* Initialize state tracker */
_state = new Implementation::State;
/* Initialize functionality based on current OpenGL version and extensions */
AbstractFramebuffer::initializeContextBasedFunctionality(this);
AbstractShaderProgram::initializeContextBasedFunctionality(this);
AbstractTexture::initializeContextBasedFunctionality(this);
Buffer::initializeContextBasedFunctionality(this);
#ifndef MAGNUM_TARGET_GLES
BufferTexture::initializeContextBasedFunctionality(this);
#endif
DebugMarker::initializeContextBasedFunctionality(this);
DefaultFramebuffer::initializeContextBasedFunctionality(this);
Framebuffer::initializeContextBasedFunctionality(this);
IndexedMesh::initializeContextBasedFunctionality(this);
Mesh::initializeContextBasedFunctionality(this);
Renderbuffer::initializeContextBasedFunctionality(this);
}
Context::~Context() {
CORRADE_ASSERT(_current == this, "Context: Cannot destroy context which is not currently active", );
delete _state;
_current = nullptr;
}
Version Context::supportedVersion(std::initializer_list<Version> versions) const {
for(auto version: versions)
if(isVersionSupported(version)) return version;
#ifndef MAGNUM_TARGET_GLES
return Version::GL210;
#else
return Version::GLES200;
#endif
}
}
<|endoftext|>
|
<commit_before>#include <JsonBox/Convert.h>
#include <sstream>
#define MASKBITS 0x3F //00111111
#define MASK1BYTE 0x80 //10000000
#define MASK2BYTES 0xC0 //11000000
#define MASK3BYTES 0xE0 //11100000
#define MASK4BYTES 0xF0 //11110000
#define MASK5BYTES 0xF8 //11111000
#define MASK6BYTES 0xFC //11111100
namespace JsonBox {
std::string Convert::encodeToUTF8(const String32& utf32String) {
std::stringstream result;
for(String32::const_iterator i = utf32String.begin() ; i < utf32String.end(); ++i) {
// 0xxxxxxx
if(*i < 0x80) {
result << static_cast<char>(*i);
}
// 110xxxxx 10xxxxxx
else if(*i < 0x800) {
result << static_cast<char>(MASK2BYTES | *i >> 6);
result << static_cast<char>(MASK1BYTE | *i & MASKBITS);
}
// 1110xxxx 10xxxxxx 10xxxxxx
else if(*i < 0x10000) {
result << static_cast<char>(MASK3BYTES | *i >> 12);
result << static_cast<char>(MASK1BYTE | *i >> 6 & MASKBITS);
result << static_cast<char>(MASK1BYTE | *i & MASKBITS);
}
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
else if(*i < 0x200000) {
result << static_cast<char>(MASK4BYTES | *i >> 18);
result << static_cast<char>(MASK1BYTE | *i >> 12 & MASKBITS);
result << static_cast<char>(MASK1BYTE | *i >> 6 & MASKBITS);
result << static_cast<char>(MASK1BYTE | *i & MASKBITS);
}
// 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if(*i < 0x4000000) {
result << static_cast<char>(MASK5BYTES | *i >> 24);
result << static_cast<char>(MASK1BYTE | *i >> 18 & MASKBITS);
result << static_cast<char>(MASK1BYTE | *i >> 12 & MASKBITS);
result << static_cast<char>(MASK1BYTE | *i >> 6 & MASKBITS);
result << static_cast<char>(MASK1BYTE | *i & MASKBITS);
}
// 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if(*i < 0x8000000) {
result << static_cast<char>(MASK6BYTES | *i >> 30);
result << static_cast<char>(MASK1BYTE | *i >> 18 & MASKBITS);
result << static_cast<char>(MASK1BYTE | *i >> 12 & MASKBITS);
result << static_cast<char>(MASK1BYTE | *i >> 6 & MASKBITS);
result << static_cast<char>(MASK1BYTE | *i & MASKBITS);
}
}
return result.str();
}
String32 Convert::decodeUTF8(const std::string& utf8String) {
std::basic_stringstream<int32_t> result;
int32_t tmpUnicodeChar;
for(std::string::const_iterator i = utf8String.begin() ; i < utf8String.end();) {
// 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
if((*i & MASK6BYTES) == MASK6BYTES) {
tmpUnicodeChar = ((*i & 0x01) << 30) | ((*(i + 1) & MASKBITS) << 24)
| ((*(i + 2) & MASKBITS) << 18) | ((*(i + 3)
& MASKBITS) << 12)
| ((*(i + 4) & MASKBITS) << 6) | (*(i + 5) & MASKBITS);
i += 6;
}
// 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if((*i & MASK5BYTES) == MASK5BYTES) {
tmpUnicodeChar = ((*i & 0x03) << 24) | ((*(i + 1)
& MASKBITS) << 18)
| ((*(i + 2) & MASKBITS) << 12) | ((*(i + 3)
& MASKBITS) << 6)
| (*(i + 4) & MASKBITS);
i += 5;
}
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
else if((*i & MASK4BYTES) == MASK4BYTES) {
tmpUnicodeChar = ((*i & 0x07) << 18) | ((*(i + 1)
& MASKBITS) << 12)
| ((*(i + 2) & MASKBITS) << 6) | (*(i + 3) & MASKBITS);
i += 4;
}
// 1110xxxx 10xxxxxx 10xxxxxx
else if((*i & MASK3BYTES) == MASK3BYTES) {
tmpUnicodeChar = ((*i & 0x0F) << 12) | ((*(i + 1) & MASKBITS) << 6)
| (*(i + 2) & MASKBITS);
i += 3;
}
// 110xxxxx 10xxxxxx
else if((*i & MASK2BYTES) == MASK2BYTES) {
tmpUnicodeChar = ((*i & 0x1F) << 6) | (*(i + 1) & MASKBITS);
i += 2;
}
// 0xxxxxxx
else { // if(*i < MASK1BYTE)
tmpUnicodeChar = *i;
i += 1;
}
result << tmpUnicodeChar;
}
return result.str();
}
}<commit_msg>Convert.cpp: warning fixes for bit-twiddling operations<commit_after>#include <JsonBox/Convert.h>
#include <sstream>
#define MASKBITS 0x3F //00111111
#define MASK1BYTE 0x80 //10000000
#define MASK2BYTES 0xC0 //11000000
#define MASK3BYTES 0xE0 //11100000
#define MASK4BYTES 0xF0 //11110000
#define MASK5BYTES 0xF8 //11111000
#define MASK6BYTES 0xFC //11111100
namespace JsonBox {
std::string Convert::encodeToUTF8(const String32& utf32String) {
std::stringstream result;
for(String32::const_iterator i = utf32String.begin() ; i < utf32String.end(); ++i) {
// 0xxxxxxx
if(*i < 0x80) {
result << static_cast<char>(*i);
}
// 110xxxxx 10xxxxxx
else if(*i < 0x800) {
result << static_cast<char>(MASK2BYTES | (*i >> 6));
result << static_cast<char>(MASK1BYTE | (*i & MASKBITS));
}
// 1110xxxx 10xxxxxx 10xxxxxx
else if(*i < 0x10000) {
result << static_cast<char>(MASK3BYTES | (*i >> 12));
result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS));
result << static_cast<char>(MASK1BYTE | (*i & MASKBITS));
}
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
else if(*i < 0x200000) {
result << static_cast<char>(MASK4BYTES | (*i >> 18));
result << static_cast<char>(MASK1BYTE | (*i >> 12 & MASKBITS));
result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS));
result << static_cast<char>(MASK1BYTE | (*i & MASKBITS));
}
// 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if(*i < 0x4000000) {
result << static_cast<char>(MASK5BYTES | (*i >> 24));
result << static_cast<char>(MASK1BYTE | (*i >> 18 & MASKBITS));
result << static_cast<char>(MASK1BYTE | (*i >> 12 & MASKBITS));
result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS));
result << static_cast<char>(MASK1BYTE | (*i & MASKBITS));
}
// 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if(*i < 0x8000000) {
result << static_cast<char>(MASK6BYTES | (*i >> 30));
result << static_cast<char>(MASK1BYTE | (*i >> 18 & MASKBITS));
result << static_cast<char>(MASK1BYTE | (*i >> 12 & MASKBITS));
result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS));
result << static_cast<char>(MASK1BYTE | (*i & MASKBITS));
}
}
return result.str();
}
String32 Convert::decodeUTF8(const std::string& utf8String) {
std::basic_stringstream<int32_t> result;
int32_t tmpUnicodeChar;
for(std::string::const_iterator i = utf8String.begin() ; i < utf8String.end();) {
// 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
if((*i & MASK6BYTES) == MASK6BYTES) {
tmpUnicodeChar = ((*i & 0x01) << 30) | ((*(i + 1) & MASKBITS) << 24)
| ((*(i + 2) & MASKBITS) << 18) | ((*(i + 3)
& MASKBITS) << 12)
| ((*(i + 4) & MASKBITS) << 6) | (*(i + 5) & MASKBITS);
i += 6;
}
// 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if((*i & MASK5BYTES) == MASK5BYTES) {
tmpUnicodeChar = ((*i & 0x03) << 24) | ((*(i + 1)
& MASKBITS) << 18)
| ((*(i + 2) & MASKBITS) << 12) | ((*(i + 3)
& MASKBITS) << 6)
| (*(i + 4) & MASKBITS);
i += 5;
}
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
else if((*i & MASK4BYTES) == MASK4BYTES) {
tmpUnicodeChar = ((*i & 0x07) << 18) | ((*(i + 1)
& MASKBITS) << 12)
| ((*(i + 2) & MASKBITS) << 6) | (*(i + 3) & MASKBITS);
i += 4;
}
// 1110xxxx 10xxxxxx 10xxxxxx
else if((*i & MASK3BYTES) == MASK3BYTES) {
tmpUnicodeChar = ((*i & 0x0F) << 12) | ((*(i + 1) & MASKBITS) << 6)
| (*(i + 2) & MASKBITS);
i += 3;
}
// 110xxxxx 10xxxxxx
else if((*i & MASK2BYTES) == MASK2BYTES) {
tmpUnicodeChar = ((*i & 0x1F) << 6) | (*(i + 1) & MASKBITS);
i += 2;
}
// 0xxxxxxx
else { // if(*i < MASK1BYTE)
tmpUnicodeChar = *i;
i += 1;
}
result << tmpUnicodeChar;
}
return result.str();
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include "tatum/graph_walkers/TimingGraphWalker.hpp"
#include "tatum/TimingGraph.hpp"
#include "tatum/delay_calc/DelayCalculator.hpp"
#include "tatum/graph_visitors/GraphVisitor.hpp"
namespace tatum {
/**
* A simple serial graph walker which traverses the timing graph in a levelized
* manner.
*/
class SerialIncrWalker : public TimingGraphWalker {
protected:
void invalidate_edge_impl(const EdgeId edge) override {
invalidated_edges_.push_back(edge);
}
void clear_invalidated_edges_impl() override {
invalidated_edges_.clear();
}
void do_arrival_pre_traversal_impl(const TimingGraph& tg, const TimingConstraints& tc, GraphVisitor& visitor) override {
size_t num_unconstrained = 0;
LevelId first_level = *tg.levels().begin();
for(NodeId node_id : tg.level_nodes(first_level)) {
bool constrained = visitor.do_arrival_pre_traverse_node(tg, tc, node_id);
if(!constrained) {
++num_unconstrained;
}
}
num_unconstrained_startpoints_ = num_unconstrained;
}
void do_required_pre_traversal_impl(const TimingGraph& tg, const TimingConstraints& tc, GraphVisitor& visitor) override {
size_t num_unconstrained = 0;
for(NodeId node_id : tg.logical_outputs()) {
bool constrained = visitor.do_required_pre_traverse_node(tg, tc, node_id);
if(!constrained) {
++num_unconstrained;
}
}
num_unconstrained_endpoints_ = num_unconstrained;
}
void do_arrival_traversal_impl(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalculator& dc, GraphVisitor& visitor) override {
prepare_incr_arrival_update(tg, visitor);
std::cout << "Arr Levels " << incr_arr_update_.min_level << ": " << incr_arr_update_.max_level << "\n";
for(int level_idx = incr_arr_update_.min_level; level_idx <= incr_arr_update_.max_level; ++level_idx) {
LevelId level(level_idx);
auto& level_nodes = incr_arr_update_.nodes_to_process[level_idx];
uniquify(level_nodes);
std::cout << "Processing Arr Level " << size_t(level) << ": " << level_nodes.size() << " nodes\n";
for (NodeId node : level_nodes) {
//std::cout << " Processing Arr " << node << "\n";
bool node_updated = visitor.do_arrival_traverse_node(tg, tc, dc, node);
if (node_updated) {
//Record that this node was updated, for later efficient slack update
nodes_to_update_slack_.emplace_back(node);
//Queue this node's downstream dependencies for updating
for (EdgeId edge : tg.node_out_edges(node)) {
NodeId snk_node = tg.edge_sink_node(edge);
enqueue_arr_node(tg, snk_node, edge, visitor);
}
}
}
}
std::cout << "Arr Processed " << incr_arr_update_.total_levels_to_process() << " levels, " << incr_arr_update_.total_nodes_to_process() << " nodes\n";
}
void do_required_traversal_impl(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalculator& dc, GraphVisitor& visitor) override {
prepare_incr_required_update(tg, visitor);
std::cout << "Req Levels " << incr_req_update_.max_level << ": " << incr_req_update_.min_level << "\n";
for(int level_idx = incr_req_update_.max_level; level_idx >= incr_req_update_.min_level; --level_idx) {
LevelId level(level_idx);
auto& level_nodes = incr_req_update_.nodes_to_process[level_idx];
uniquify(level_nodes);
std::cout << "Processing Req Level " << size_t(level) << ": " << level_nodes.size() << " nodes\n";
for (NodeId node : level_nodes) {
//std::cout << " Processing Req " << node << "\n";
bool node_updated = visitor.do_required_traverse_node(tg, tc, dc, node);
if (node_updated) {
//Record that this node was updated, for later efficient slack update
nodes_to_update_slack_.emplace_back(node);
//Queue this node's downstream dependencies for updating
for (EdgeId edge : tg.node_in_edges(node)) {
NodeId src_node = tg.edge_src_node(edge);
enqueue_req_node(tg, src_node, edge, visitor);
}
}
}
}
std::cout << "Req Processed " << incr_req_update_.total_levels_to_process() << " levels, " << incr_req_update_.total_nodes_to_process() << " nodes\n";
}
void do_update_slack_impl(const TimingGraph& tg, const DelayCalculator& dc, GraphVisitor& visitor) override {
uniquify(nodes_to_update_slack_);
std::cout << "Processing slack updates for " << nodes_to_update_slack_.size() << " nodes\n";
for(NodeId node : nodes_to_update_slack_) {
visitor.do_slack_traverse_node(tg, dc, node);
}
nodes_to_update_slack_.clear();
}
void do_reset_impl(const TimingGraph& tg, GraphVisitor& visitor) override {
for(NodeId node_id : tg.nodes()) {
visitor.do_reset_node(node_id);
}
for(EdgeId edge_id : tg.edges()) {
visitor.do_reset_edge(edge_id);
}
}
size_t num_unconstrained_startpoints_impl() const override { return num_unconstrained_startpoints_; }
size_t num_unconstrained_endpoints_impl() const override { return num_unconstrained_endpoints_; }
private:
void uniquify(std::vector<NodeId>& nodes) {
std::sort(nodes.begin(), nodes.end());
nodes.erase(std::unique(nodes.begin(), nodes.end()),
nodes.end());
}
void prepare_incr_arrival_update(const TimingGraph& tg, GraphVisitor& visitor) {
incr_arr_update_.nodes_to_process.resize(tg.levels().size());
if (incr_arr_update_.min_level && incr_arr_update_.max_level) {
for (int level = incr_arr_update_.min_level; level <= incr_arr_update_.max_level; ++level) {
incr_arr_update_.nodes_to_process[level].clear();
}
}
incr_arr_update_.min_level = size_t(*(tg.levels().end() - 1));
incr_arr_update_.max_level = size_t(*tg.levels().begin());
/*
*for (LevelId level : tg.levels()) {
* TATUM_ASSERT_SAFE(inc_arr_update_.nodes_to_process[level].empty());
*}
*/
std::cout << "Invalidated Edges: " << invalidated_edges_.size() << " / " << tg.edges().size() << " (" << invalidated_edges_.size() / tg.edges().size() << ")\n";
for (EdgeId edge : invalidated_edges_) {
NodeId node = tg.edge_sink_node(edge);
enqueue_arr_node(tg, node, edge, visitor);
}
}
void prepare_incr_required_update(const TimingGraph& tg, GraphVisitor& visitor) {
incr_req_update_.nodes_to_process.resize(tg.levels().size());
if (incr_req_update_.min_level && incr_req_update_.max_level) {
for (int level = incr_req_update_.min_level; level <= incr_req_update_.max_level; ++level) {
incr_req_update_.nodes_to_process[level].clear();
}
}
incr_req_update_.min_level = size_t(*(tg.levels().end() - 1));
incr_req_update_.max_level = size_t(*tg.levels().begin());
/*
*for (LevelId level : tg.levels()) {
* TATUM_ASSERT_SAFE(inc_req_update_.nodes_to_process[level].empty());
*}
*/
for (EdgeId edge : invalidated_edges_) {
NodeId node = tg.edge_src_node(edge);
enqueue_req_node(tg, node, edge, visitor);
}
}
void enqueue_arr_node(const TimingGraph& tg, NodeId node, EdgeId invalidated_edge, GraphVisitor& visitor) {
if (0) { //Block invalidation
visitor.do_reset_node_arrival_tags(node);
} else { //Edge invalidation
NodeId src_node = tg.edge_src_node(invalidated_edge);
visitor.do_reset_node_arrival_tags_from_origin(node, src_node);
}
incr_arr_update_.enqueue_node(tg, node);
}
void enqueue_req_node(const TimingGraph& tg, NodeId node, EdgeId invalidated_edge, GraphVisitor& visitor) {
if (0) { //Block invalidation
visitor.do_reset_node_required_tags(node);
} else { //Edge invalidation
NodeId snk_node = tg.edge_sink_node(invalidated_edge);
visitor.do_reset_node_required_tags_from_origin(node, snk_node);
}
incr_req_update_.enqueue_node(tg, node);
}
struct t_incr_traversal_update {
std::vector<std::vector<NodeId>> nodes_to_process;
int min_level;
int max_level;
void enqueue_node(const TimingGraph& tg, NodeId node) {
int level = size_t(tg.node_level(node));
nodes_to_process[level].push_back(node);
min_level = std::min(min_level, level);
max_level = std::max(max_level, level);
}
size_t total_nodes_to_process() {
if (!min_level || !max_level) {
return 0;
}
size_t cnt = 0;
for (int level = min_level; level <= max_level; ++level) {
cnt += nodes_to_process[level].size();
}
return cnt;
}
size_t total_levels_to_process() {
return size_t(max_level) - size_t(min_level) + 1;
}
};
t_incr_traversal_update incr_arr_update_;
t_incr_traversal_update incr_req_update_;
std::vector<NodeId> nodes_to_update_slack_;
std::vector<EdgeId> invalidated_edges_;
size_t num_unconstrained_startpoints_ = 0;
size_t num_unconstrained_endpoints_ = 0;
};
} //namepsace
<commit_msg>Fix uninitialized level range<commit_after>#pragma once
#include "tatum/graph_walkers/TimingGraphWalker.hpp"
#include "tatum/TimingGraph.hpp"
#include "tatum/delay_calc/DelayCalculator.hpp"
#include "tatum/graph_visitors/GraphVisitor.hpp"
namespace tatum {
/**
* A simple serial graph walker which traverses the timing graph in a levelized
* manner.
*/
class SerialIncrWalker : public TimingGraphWalker {
protected:
void invalidate_edge_impl(const EdgeId edge) override {
invalidated_edges_.push_back(edge);
}
void clear_invalidated_edges_impl() override {
invalidated_edges_.clear();
}
void do_arrival_pre_traversal_impl(const TimingGraph& tg, const TimingConstraints& tc, GraphVisitor& visitor) override {
size_t num_unconstrained = 0;
LevelId first_level = *tg.levels().begin();
for(NodeId node_id : tg.level_nodes(first_level)) {
bool constrained = visitor.do_arrival_pre_traverse_node(tg, tc, node_id);
if(!constrained) {
++num_unconstrained;
}
}
num_unconstrained_startpoints_ = num_unconstrained;
}
void do_required_pre_traversal_impl(const TimingGraph& tg, const TimingConstraints& tc, GraphVisitor& visitor) override {
size_t num_unconstrained = 0;
for(NodeId node_id : tg.logical_outputs()) {
bool constrained = visitor.do_required_pre_traverse_node(tg, tc, node_id);
if(!constrained) {
++num_unconstrained;
}
}
num_unconstrained_endpoints_ = num_unconstrained;
}
void do_arrival_traversal_impl(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalculator& dc, GraphVisitor& visitor) override {
prepare_incr_arrival_update(tg, visitor);
std::cout << "Arr Levels " << incr_arr_update_.min_level << ": " << incr_arr_update_.max_level << "\n";
for(int level_idx = incr_arr_update_.min_level; level_idx <= incr_arr_update_.max_level; ++level_idx) {
LevelId level(level_idx);
auto& level_nodes = incr_arr_update_.nodes_to_process[level_idx];
uniquify(level_nodes);
std::cout << "Processing Arr Level " << size_t(level) << ": " << level_nodes.size() << " nodes\n";
for (NodeId node : level_nodes) {
//std::cout << " Processing Arr " << node << "\n";
bool node_updated = visitor.do_arrival_traverse_node(tg, tc, dc, node);
if (node_updated) {
//Record that this node was updated, for later efficient slack update
nodes_to_update_slack_.emplace_back(node);
//Queue this node's downstream dependencies for updating
for (EdgeId edge : tg.node_out_edges(node)) {
NodeId snk_node = tg.edge_sink_node(edge);
enqueue_arr_node(tg, snk_node, edge, visitor);
}
}
}
}
std::cout << "Arr Processed " << incr_arr_update_.total_levels_to_process() << " levels, " << incr_arr_update_.total_nodes_to_process() << " nodes\n";
}
void do_required_traversal_impl(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalculator& dc, GraphVisitor& visitor) override {
prepare_incr_required_update(tg, visitor);
std::cout << "Req Levels " << incr_req_update_.max_level << ": " << incr_req_update_.min_level << "\n";
for(int level_idx = incr_req_update_.max_level; level_idx >= incr_req_update_.min_level; --level_idx) {
LevelId level(level_idx);
auto& level_nodes = incr_req_update_.nodes_to_process[level_idx];
uniquify(level_nodes);
std::cout << "Processing Req Level " << size_t(level) << ": " << level_nodes.size() << " nodes\n";
for (NodeId node : level_nodes) {
//std::cout << " Processing Req " << node << "\n";
bool node_updated = visitor.do_required_traverse_node(tg, tc, dc, node);
if (node_updated) {
//Record that this node was updated, for later efficient slack update
nodes_to_update_slack_.emplace_back(node);
//Queue this node's downstream dependencies for updating
for (EdgeId edge : tg.node_in_edges(node)) {
NodeId src_node = tg.edge_src_node(edge);
enqueue_req_node(tg, src_node, edge, visitor);
}
}
}
}
std::cout << "Req Processed " << incr_req_update_.total_levels_to_process() << " levels, " << incr_req_update_.total_nodes_to_process() << " nodes\n";
}
void do_update_slack_impl(const TimingGraph& tg, const DelayCalculator& dc, GraphVisitor& visitor) override {
uniquify(nodes_to_update_slack_);
std::cout << "Processing slack updates for " << nodes_to_update_slack_.size() << " nodes\n";
for(NodeId node : nodes_to_update_slack_) {
visitor.do_slack_traverse_node(tg, dc, node);
}
nodes_to_update_slack_.clear();
}
void do_reset_impl(const TimingGraph& tg, GraphVisitor& visitor) override {
for(NodeId node_id : tg.nodes()) {
visitor.do_reset_node(node_id);
}
for(EdgeId edge_id : tg.edges()) {
visitor.do_reset_edge(edge_id);
}
}
size_t num_unconstrained_startpoints_impl() const override { return num_unconstrained_startpoints_; }
size_t num_unconstrained_endpoints_impl() const override { return num_unconstrained_endpoints_; }
private:
void uniquify(std::vector<NodeId>& nodes) {
std::sort(nodes.begin(), nodes.end());
nodes.erase(std::unique(nodes.begin(), nodes.end()),
nodes.end());
}
void prepare_incr_arrival_update(const TimingGraph& tg, GraphVisitor& visitor) {
incr_arr_update_.nodes_to_process.resize(tg.levels().size());
if (incr_arr_update_.min_level && incr_arr_update_.max_level) {
for (int level = incr_arr_update_.min_level; level <= incr_arr_update_.max_level; ++level) {
incr_arr_update_.nodes_to_process[level].clear();
}
}
incr_arr_update_.min_level = size_t(*(tg.levels().end() - 1));
incr_arr_update_.max_level = size_t(*tg.levels().begin());
/*
*for (LevelId level : tg.levels()) {
* TATUM_ASSERT_SAFE(inc_arr_update_.nodes_to_process[level].empty());
*}
*/
std::cout << "Invalidated Edges: " << invalidated_edges_.size() << " / " << tg.edges().size() << " (" << invalidated_edges_.size() / tg.edges().size() << ")\n";
for (EdgeId edge : invalidated_edges_) {
NodeId node = tg.edge_sink_node(edge);
enqueue_arr_node(tg, node, edge, visitor);
}
}
void prepare_incr_required_update(const TimingGraph& tg, GraphVisitor& visitor) {
incr_req_update_.nodes_to_process.resize(tg.levels().size());
if (incr_req_update_.min_level && incr_req_update_.max_level) {
for (int level = incr_req_update_.min_level; level <= incr_req_update_.max_level; ++level) {
incr_req_update_.nodes_to_process[level].clear();
}
}
incr_req_update_.min_level = size_t(*(tg.levels().end() - 1));
incr_req_update_.max_level = size_t(*tg.levels().begin());
/*
*for (LevelId level : tg.levels()) {
* TATUM_ASSERT_SAFE(inc_req_update_.nodes_to_process[level].empty());
*}
*/
for (EdgeId edge : invalidated_edges_) {
NodeId node = tg.edge_src_node(edge);
enqueue_req_node(tg, node, edge, visitor);
}
}
void enqueue_arr_node(const TimingGraph& tg, NodeId node, EdgeId invalidated_edge, GraphVisitor& visitor) {
if (0) { //Block invalidation
visitor.do_reset_node_arrival_tags(node);
} else { //Edge invalidation
NodeId src_node = tg.edge_src_node(invalidated_edge);
visitor.do_reset_node_arrival_tags_from_origin(node, src_node);
}
incr_arr_update_.enqueue_node(tg, node);
}
void enqueue_req_node(const TimingGraph& tg, NodeId node, EdgeId invalidated_edge, GraphVisitor& visitor) {
if (0) { //Block invalidation
visitor.do_reset_node_required_tags(node);
} else { //Edge invalidation
NodeId snk_node = tg.edge_sink_node(invalidated_edge);
visitor.do_reset_node_required_tags_from_origin(node, snk_node);
}
incr_req_update_.enqueue_node(tg, node);
}
struct t_incr_traversal_update {
std::vector<std::vector<NodeId>> nodes_to_process;
int min_level = 0;
int max_level = 0;
void enqueue_node(const TimingGraph& tg, NodeId node) {
int level = size_t(tg.node_level(node));
nodes_to_process[level].push_back(node);
min_level = std::min(min_level, level);
max_level = std::max(max_level, level);
}
size_t total_nodes_to_process() {
if (!min_level || !max_level) {
return 0;
}
size_t cnt = 0;
for (int level = min_level; level <= max_level; ++level) {
cnt += nodes_to_process[level].size();
}
return cnt;
}
size_t total_levels_to_process() {
return size_t(max_level) - size_t(min_level) + 1;
}
};
t_incr_traversal_update incr_arr_update_;
t_incr_traversal_update incr_req_update_;
std::vector<NodeId> nodes_to_update_slack_;
std::vector<EdgeId> invalidated_edges_;
size_t num_unconstrained_startpoints_ = 0;
size_t num_unconstrained_endpoints_ = 0;
};
} //namepsace
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbOGRDataResampler.h"
#include <string>
#include <fstream>
namespace otb
{
unsigned int
OGRDataResampler
::SelectN1(double per,unsigned int T)
{
if (!(T>0))
itkExceptionMacro(<< "In OGRDataResampler::SelectN1 : sizes of the sampling arrays must be non-negative (" << T << ")." << std::endl);
double dist = itk::NumericTraits<double>::max();
double d;
unsigned int N=0;
double p;
for(unsigned int n=0;n<=T;n++)
{
p=static_cast<double>(n)/static_cast<double>(T)*100.;
if (p<=per)
{
d = fabs(per-p);
if (d<dist)
{
N=n;
dist=d;
}
}
}
return N;
}
unsigned int
OGRDataResampler
::SelectN2(double per,unsigned int T)
{
if (!(T>0))
itkExceptionMacro(<< "In OGRDataResampler::SelectN2 : sizes of the sampling arrays must be non-negative (" << T << ")." << std::endl);
double dist = itk::NumericTraits<double>::max();
double d;
unsigned int N=0;
double p;
for(unsigned int n=0;n<=T;n++)
{
p=static_cast<double>(n)/static_cast<double>(T)*100.;
if (p>=per)
{
d = fabs(per-p);
if (d<dist)
{
N=n;
dist=d;
}
}
}
return N;
}
std::vector<bool>
OGRDataResampler::RandArray(unsigned int N,unsigned int T)
{
if (N>T)
itkExceptionMacro(<< "N must be <= to T (aka m_SamplingTabSize)." << std::endl);
std::vector<bool> res(T,0);
for(unsigned int i=0; i<N;i++)
res[i]=1;
std::random_shuffle ( res.begin(), res.end() );
return res;
}
unsigned int
OGRDataResampler::FindBestSize(unsigned int tot)
{
if (tot<m_MaxSamplingVecSize)
return tot;
for(unsigned int size=m_MaxSamplingVecSize; size>=2; size--)
if (tot%size == 0)
return size;
otbWarningMacro(<<"prime number > m_MaxSamplingVecSize (" << tot << ">" << m_MaxSamplingVecSize << ")."<< std::endl );
return tot;
}
void
OGRDataResampler::InputSamplingVectors()
{
m_ClassToBools.clear();
m_ClassToCurrentIndices.clear();
std::ifstream file(m_InputSamplingVectorsPath.c_str(),std::ios::in);
std::string line;
if (file)
{
std::string className;
int tabNum=1;
std::vector<bool> tab1,tab2;
while(getline(file,line))
{
std::size_t found1 = line.find_first_of("#");
std::size_t found2 = line.find_first_of(">");
if (found1 != std::string::npos)
{
className = line.substr(found1+1);
}
if (found2 != std::string::npos)
{
if (tabNum==1)
{
std::istringstream issBooleans(line.substr(found2+1));
std::list<std::string> tokens;
copy(std::istream_iterator<std::string>(issBooleans),
std::istream_iterator<std::string>(),
back_inserter(tokens));
std::list<std::string>::iterator it = tokens.begin();
for(; it != tokens.end(); ++it)
tab1.push_back( (it->find("1")!=std::string::npos) );
tabNum++;
}
else //tabNum==2
{
std::istringstream issBooleans(line.substr(found2+1));
std::list<std::string> tokens;
copy(std::istream_iterator<std::string>(issBooleans),
std::istream_iterator<std::string>(),
back_inserter(tokens));
std::list<std::string>::iterator it = tokens.begin();
for(; it != tokens.end(); ++it)
tab2.push_back( (it->find("1")!=std::string::npos) );
m_ClassToBools[className] = std::make_pair(tab1,tab2);
m_ClassToCurrentIndices[className] = std::make_pair(0,0);
tabNum=1;
className.erase();
tab1.clear();
tab2.clear();
}
}
}
}
else
itkExceptionMacro(<< "Could not open file " << m_InputSamplingVectorsPath << "." << std::endl);
}
void
OGRDataResampler::OutputSamplingVectors()
{
std::ofstream file(m_OutputSamplingVectorsPath.c_str(), std::ios::out | std::ios::trunc);
if(file)
{
ClassToBoolsType::iterator it = m_ClassToBools.begin();
for(; it!=m_ClassToBools.end(); ++it)
{
file << "#" << it->first << std::endl;
file << ">";
for(unsigned int i=0; i<it->second.first.size(); i++)
file << it->second.first[i] << " ";
file << std::endl;
file << ">";
for(unsigned int i=0; i<it->second.second.size(); i++)
file << it->second.second[i] << " ";
file << std::endl;
}
file.close();
}
else
itkExceptionMacro(<< "Could not open file " << m_OutputSamplingVectorsPath << "." << std::endl);
}
void
OGRDataResampler::Prepare()
{
if (!m_AlreadyPrepared)
{
if (m_RatesbyClass.empty())
{
itkGenericExceptionMacro("m_RatesbyClass is empty (otb::OGRDataResampler) ");
}
if (!m_InputSamplingVectorsPath.empty())
this->InputSamplingVectors();
else
{
SamplingRateCalculator::mapRateType::iterator itRates = m_RatesbyClass.begin();
for(;itRates !=m_RatesbyClass.end(); ++itRates)
{
//std::cout << "#" << itRates->first << " " << itRates->second.required << " " << itRates->second.tot << std::endl;
unsigned int T1 = FindBestSize(itRates->second.tot);
//std::cout << "*** " << itRates->second.tot << " " << T1 << " " << itRates->second.tot/T1 << std::endl;
double per = static_cast<double>(itRates->second.required) / static_cast<double>(itRates->second.tot)*100.;
unsigned int N1 = SelectN1(per,T1);
double selected_prct = static_cast<double>(N1)/static_cast<double>(T1)*100.;
unsigned int taken = static_cast<unsigned int>(selected_prct*static_cast<double>(itRates->second.tot)/100.);
unsigned int left = itRates->second.required - taken;
unsigned int newtot = itRates->second.tot - taken;
//std::cout << "##" << N1 << " " << per << " " << selected_prct << " " << taken << " " << left << " " << newtot << std::endl;
if ( !(per>=selected_prct) )
itkExceptionMacro(<< "In otb::OGRDataResampler::Prepare, per < selected_prct !" << std::endl);
unsigned int T2 = 0;
unsigned int N2 = 0;
if (left>0)
{
double per2;
if (newtot>0)
per2 = static_cast<double>(left)/static_cast<double>(newtot)*100.;
else
per2 = 0;
T2 = FindBestSize(itRates->second.tot/T1*(T1-N1));
/*std::cout << "*** " << itRates->second.tot << " " << T1 << " " << itRates->second.tot/T1 << " " << N1 << " "
<< itRates->second.tot/T1*(T1-N1) << " " << T2 << std::endl;*/
double selected_prct2 = 0.;
if (T2>0)
{
N2 = SelectN2(per2,T2);
selected_prct2 = static_cast<double>(N2)/static_cast<double>(T2)*100.;
}
//std::cout << "###" << N2 << " " << per2 << " " << selected_prct2 << std::endl;
if ( !(per2<=selected_prct2) )
itkExceptionMacro(<< "In otb::OGRDataResampler::Prepare, per2 > selected_prct2 !" << std::endl);
}
std::srand ( unsigned ( time(0) ) );
std::vector<bool> tab1 = RandArray(N1,T1);
std::vector<bool> tab2;
if (T2>0)
tab2 = RandArray(N2,T2);
unsigned int N=0;
for(unsigned int i=0;i<tab1.size();i++)
if (tab1[i])
N++;
if (N!=N1)
itkExceptionMacro(<< "N != N1." << std::endl);
N=0;
for(unsigned int i=0;i<tab2.size();i++)
if (tab2[i])
N++;
if (N!=N2)
itkExceptionMacro(<< "N != N2." << std::endl);
//itRates->first <=> className
m_ClassToBools[itRates->first] = std::make_pair(tab1,tab2);
m_ClassToCurrentIndices[itRates->first] = std::make_pair(0,0);
if (!m_OutputSamplingVectorsPath.empty())
this->OutputSamplingVectors();
}
}
}
m_AlreadyPrepared=true;
}
bool
OGRDataResampler::TakeSample(std::string className)
{
bool res=false;
if (m_ElmtsInClass[className] >= m_RatesbyClass[className].required)
return false;
unsigned int &ind1 = m_ClassToCurrentIndices[className].first; //first counter
std::vector<bool> &tab1 = m_ClassToBools[className].first; // First array
res = tab1[ind1];
ind1++;
if (ind1>=tab1.size())
ind1=0;
if(!res)
{
unsigned int &ind2 = m_ClassToCurrentIndices[className].second; // second counter
std::vector<bool> &tab2 = m_ClassToBools[className].second; // second array
if (tab2.size()>0)
{
res = tab2[ind2];
ind2++;
if (ind2>=tab2.size())
ind2=0;
}
}
return res;
}
void
OGRDataResampler
::Reset()
{
m_ElmtsInClass.clear();
}
} // end of namespace otb
<commit_msg>ENH: small gain if tot equals m_MaxSamplingVecSize<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbOGRDataResampler.h"
#include <string>
#include <fstream>
namespace otb
{
unsigned int
OGRDataResampler
::SelectN1(double per,unsigned int T)
{
if (!(T>0))
itkExceptionMacro(<< "In OGRDataResampler::SelectN1 : sizes of the sampling arrays must be non-negative (" << T << ")." << std::endl);
double dist = itk::NumericTraits<double>::max();
double d;
unsigned int N=0;
double p;
for(unsigned int n=0;n<=T;n++)
{
p=static_cast<double>(n)/static_cast<double>(T)*100.;
if (p<=per)
{
d = fabs(per-p);
if (d<dist)
{
N=n;
dist=d;
}
}
}
return N;
}
unsigned int
OGRDataResampler
::SelectN2(double per,unsigned int T)
{
if (!(T>0))
itkExceptionMacro(<< "In OGRDataResampler::SelectN2 : sizes of the sampling arrays must be non-negative (" << T << ")." << std::endl);
double dist = itk::NumericTraits<double>::max();
double d;
unsigned int N=0;
double p;
for(unsigned int n=0;n<=T;n++)
{
p=static_cast<double>(n)/static_cast<double>(T)*100.;
if (p>=per)
{
d = fabs(per-p);
if (d<dist)
{
N=n;
dist=d;
}
}
}
return N;
}
std::vector<bool>
OGRDataResampler::RandArray(unsigned int N,unsigned int T)
{
if (N>T)
itkExceptionMacro(<< "N must be <= to T (aka m_SamplingTabSize)." << std::endl);
std::vector<bool> res(T,0);
for(unsigned int i=0; i<N;i++)
res[i]=1;
std::random_shuffle ( res.begin(), res.end() );
return res;
}
unsigned int
OGRDataResampler::FindBestSize(unsigned int tot)
{
if (tot<=m_MaxSamplingVecSize)
return tot;
for(unsigned int size=m_MaxSamplingVecSize; size>=2; size--)
if (tot%size == 0)
return size;
otbWarningMacro(<<"prime number > m_MaxSamplingVecSize (" << tot << ">" << m_MaxSamplingVecSize << ")."<< std::endl );
return tot;
}
void
OGRDataResampler::InputSamplingVectors()
{
m_ClassToBools.clear();
m_ClassToCurrentIndices.clear();
std::ifstream file(m_InputSamplingVectorsPath.c_str(),std::ios::in);
std::string line;
if (file)
{
std::string className;
int tabNum=1;
std::vector<bool> tab1,tab2;
while(getline(file,line))
{
std::size_t found1 = line.find_first_of("#");
std::size_t found2 = line.find_first_of(">");
if (found1 != std::string::npos)
{
className = line.substr(found1+1);
}
if (found2 != std::string::npos)
{
if (tabNum==1)
{
std::istringstream issBooleans(line.substr(found2+1));
std::list<std::string> tokens;
copy(std::istream_iterator<std::string>(issBooleans),
std::istream_iterator<std::string>(),
back_inserter(tokens));
std::list<std::string>::iterator it = tokens.begin();
for(; it != tokens.end(); ++it)
tab1.push_back( (it->find("1")!=std::string::npos) );
tabNum++;
}
else //tabNum==2
{
std::istringstream issBooleans(line.substr(found2+1));
std::list<std::string> tokens;
copy(std::istream_iterator<std::string>(issBooleans),
std::istream_iterator<std::string>(),
back_inserter(tokens));
std::list<std::string>::iterator it = tokens.begin();
for(; it != tokens.end(); ++it)
tab2.push_back( (it->find("1")!=std::string::npos) );
m_ClassToBools[className] = std::make_pair(tab1,tab2);
m_ClassToCurrentIndices[className] = std::make_pair(0,0);
tabNum=1;
className.erase();
tab1.clear();
tab2.clear();
}
}
}
}
else
itkExceptionMacro(<< "Could not open file " << m_InputSamplingVectorsPath << "." << std::endl);
}
void
OGRDataResampler::OutputSamplingVectors()
{
std::ofstream file(m_OutputSamplingVectorsPath.c_str(), std::ios::out | std::ios::trunc);
if(file)
{
ClassToBoolsType::iterator it = m_ClassToBools.begin();
for(; it!=m_ClassToBools.end(); ++it)
{
file << "#" << it->first << std::endl;
file << ">";
for(unsigned int i=0; i<it->second.first.size(); i++)
file << it->second.first[i] << " ";
file << std::endl;
file << ">";
for(unsigned int i=0; i<it->second.second.size(); i++)
file << it->second.second[i] << " ";
file << std::endl;
}
file.close();
}
else
itkExceptionMacro(<< "Could not open file " << m_OutputSamplingVectorsPath << "." << std::endl);
}
void
OGRDataResampler::Prepare()
{
if (!m_AlreadyPrepared)
{
if (m_RatesbyClass.empty())
{
itkGenericExceptionMacro("m_RatesbyClass is empty (otb::OGRDataResampler) ");
}
if (!m_InputSamplingVectorsPath.empty())
this->InputSamplingVectors();
else
{
SamplingRateCalculator::mapRateType::iterator itRates = m_RatesbyClass.begin();
for(;itRates !=m_RatesbyClass.end(); ++itRates)
{
//std::cout << "#" << itRates->first << " " << itRates->second.required << " " << itRates->second.tot << std::endl;
unsigned int T1 = FindBestSize(itRates->second.tot);
//std::cout << "*** " << itRates->second.tot << " " << T1 << " " << itRates->second.tot/T1 << std::endl;
double per = static_cast<double>(itRates->second.required) / static_cast<double>(itRates->second.tot)*100.;
unsigned int N1 = SelectN1(per,T1);
double selected_prct = static_cast<double>(N1)/static_cast<double>(T1)*100.;
unsigned int taken = static_cast<unsigned int>(selected_prct*static_cast<double>(itRates->second.tot)/100.);
unsigned int left = itRates->second.required - taken;
unsigned int newtot = itRates->second.tot - taken;
//std::cout << "##" << N1 << " " << per << " " << selected_prct << " " << taken << " " << left << " " << newtot << std::endl;
if ( !(per>=selected_prct) )
itkExceptionMacro(<< "In otb::OGRDataResampler::Prepare, per < selected_prct !" << std::endl);
unsigned int T2 = 0;
unsigned int N2 = 0;
if (left>0)
{
double per2;
if (newtot>0)
per2 = static_cast<double>(left)/static_cast<double>(newtot)*100.;
else
per2 = 0;
T2 = FindBestSize(itRates->second.tot/T1*(T1-N1));
/*std::cout << "*** " << itRates->second.tot << " " << T1 << " " << itRates->second.tot/T1 << " " << N1 << " "
<< itRates->second.tot/T1*(T1-N1) << " " << T2 << std::endl;*/
double selected_prct2 = 0.;
if (T2>0)
{
N2 = SelectN2(per2,T2);
selected_prct2 = static_cast<double>(N2)/static_cast<double>(T2)*100.;
}
//std::cout << "###" << N2 << " " << per2 << " " << selected_prct2 << std::endl;
if ( !(per2<=selected_prct2) )
itkExceptionMacro(<< "In otb::OGRDataResampler::Prepare, per2 > selected_prct2 !" << std::endl);
}
std::srand ( unsigned ( time(0) ) );
std::vector<bool> tab1 = RandArray(N1,T1);
std::vector<bool> tab2;
if (T2>0)
tab2 = RandArray(N2,T2);
unsigned int N=0;
for(unsigned int i=0;i<tab1.size();i++)
if (tab1[i])
N++;
if (N!=N1)
itkExceptionMacro(<< "N != N1." << std::endl);
N=0;
for(unsigned int i=0;i<tab2.size();i++)
if (tab2[i])
N++;
if (N!=N2)
itkExceptionMacro(<< "N != N2." << std::endl);
//itRates->first <=> className
m_ClassToBools[itRates->first] = std::make_pair(tab1,tab2);
m_ClassToCurrentIndices[itRates->first] = std::make_pair(0,0);
if (!m_OutputSamplingVectorsPath.empty())
this->OutputSamplingVectors();
}
}
}
m_AlreadyPrepared=true;
}
bool
OGRDataResampler::TakeSample(std::string className)
{
bool res=false;
if (m_ElmtsInClass[className] >= m_RatesbyClass[className].required)
return false;
unsigned int &ind1 = m_ClassToCurrentIndices[className].first; //first counter
std::vector<bool> &tab1 = m_ClassToBools[className].first; // First array
res = tab1[ind1];
ind1++;
if (ind1>=tab1.size())
ind1=0;
if(!res)
{
unsigned int &ind2 = m_ClassToCurrentIndices[className].second; // second counter
std::vector<bool> &tab2 = m_ClassToBools[className].second; // second array
if (tab2.size()>0)
{
res = tab2[ind2];
ind2++;
if (ind2>=tab2.size())
ind2=0;
}
}
return res;
}
void
OGRDataResampler
::Reset()
{
m_ElmtsInClass.clear();
}
} // end of namespace otb
<|endoftext|>
|
<commit_before>#include "CryFuse.h"
#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <cassert>
#include "cryfs_lib/CryNode.h"
#include "cryfs_lib/CryErrnoException.h"
#define UNUSED(expr) (void)(expr)
using fusepp::path;
namespace cryfs {
namespace {
int errcode_map(int exit_status) {
if (exit_status < 0) {
return -errno;
}
return exit_status;
}
}
CryFuse::CryFuse(CryDevice *device)
:_device(device) {
}
int CryFuse::getattr(const path &path, struct stat *stbuf) {
try {
_device->LoadFromPath(path)->stat(stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {
//printf("fgetattr(%s, _, _)\n", path.c_str());
// On FreeBSD, trying to do anything with the mountpoint ends up
// opening it, and then using the FD for an fgetattr. So in the
// special case of a path of "/", I need to do a getattr on the
// underlying root directory instead of doing the fgetattr().
if (path.native() == "/") {
return getattr(path, stbuf);
}
int retstat = fstat(fileinfo->fh, stbuf);
return errcode_map(retstat);
}
int CryFuse::readlink(const path &path, char *buf, size_t size) {
//printf("readlink(%s, _, %zu)\n", path.c_str(), size);
auto real_path = _device->RootDir() / path;
//size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,
//but the posix version does not and also doesn't append one.
int real_size = ::readlink(real_path.c_str(), buf, size-1);
if (real_size < 0) {
return -errno;
}
//Terminate the string
buf[real_size] = '\0';
return 0;
}
int CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {
UNUSED(rdev);
//printf("Called non-implemented mknod(%s, %d, _)\n", path.c_str(), mode);
return 0;
}
int CryFuse::mkdir(const path &path, mode_t mode) {
//printf("mkdir(%s, %d)\n", path.c_str(), mode);
auto real_path = _device->RootDir() / path;
int retstat = ::mkdir(real_path.c_str(), mode);
return errcode_map(retstat);
}
int CryFuse::unlink(const path &path) {
//printf("unlink(%s)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::unlink(real_path.c_str());
return errcode_map(retstat);
}
int CryFuse::rmdir(const path &path) {
//printf("rmdir(%s)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::rmdir(real_path.c_str());
return errcode_map(retstat);
}
int CryFuse::symlink(const path &from, const path &to) {
//printf("symlink(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::symlink(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
int CryFuse::rename(const path &from, const path &to) {
//printf("rename(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::rename(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
int CryFuse::link(const path &from, const path &to) {
//printf("link(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::link(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
int CryFuse::chmod(const path &path, mode_t mode) {
//printf("chmod(%s, %d)\n", path.c_str(), mode);
auto real_path = _device->RootDir() / path;
int retstat = ::chmod(real_path.c_str(), mode);
return errcode_map(retstat);
}
int CryFuse::chown(const path &path, uid_t uid, gid_t gid) {
//printf("chown(%s, %d, %d)\n", path.c_str(), uid, gid);
auto real_path = _device->RootDir() / path;
int retstat = ::chown(real_path.c_str(), uid, gid);
return errcode_map(retstat);
}
int CryFuse::truncate(const path &path, off_t size) {
//printf("truncate(%s, %zu)\n", path.c_str(), size);
auto real_path = _device->RootDir() / path;
int retstat = ::truncate(real_path.c_str(), size);
return errcode_map(retstat);
}
int CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {
//printf("ftruncate(%s, %zu, _)\n", path.c_str(), size);
int retstat = ::ftruncate(fileinfo->fh, size);
return errcode_map(retstat);
}
int CryFuse::utimens(const path &path, const timespec times[2]) {
//printf("utimens(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
struct timeval tv[2];
tv[0].tv_sec = times[0].tv_sec;
tv[0].tv_usec = times[0].tv_nsec / 1000;
tv[1].tv_sec = times[1].tv_sec;
tv[1].tv_usec = times[1].tv_nsec / 1000;
int retstat = ::lutimes(real_path.c_str(), tv);
return errcode_map(retstat);
}
int CryFuse::open(const path &path, fuse_file_info *fileinfo) {
//printf("open(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int fd = ::open(real_path.c_str(), fileinfo->flags);
if (fd < 0) {
return -errno;
}
fileinfo->fh = fd;
return 0;
}
int CryFuse::release(const path &path, fuse_file_info *fileinfo) {
//printf("release(%s, _)\n", path.c_str());
int retstat = ::close(fileinfo->fh);
return errcode_map(retstat);
}
int CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("read(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
int retstat = ::pread(fileinfo->fh, buf, size, offset);
return errcode_map(retstat);
}
int CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("write(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
int retstat = ::pwrite(fileinfo->fh, buf, size, offset);
return errcode_map(retstat);
}
int CryFuse::statfs(const path &path, struct statvfs *fsstat) {
//printf("statfs(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::statvfs(real_path.c_str(), fsstat);
return errcode_map(retstat);
}
int CryFuse::flush(const path &path, fuse_file_info *fileinfo) {
//printf("Called non-implemented flush(%s, _)\n", path.c_str());
return 0;
}
int CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {
//printf("fsync(%s, %d, _)\n", path.c_str(), datasync);
int retstat = 0;
if (datasync) {
retstat = ::fdatasync(fileinfo->fh);
} else {
retstat = ::fsync(fileinfo->fh);
}
return errcode_map(retstat);
}
int CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {
//printf("opendir(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
DIR *dp = ::opendir(real_path.c_str());
if (dp == nullptr) {
return -errno;
}
fileinfo->fh = (intptr_t)dp;
return 0;
}
int CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {
//printf("readdir(%s, _, _, %zu, _)\n", path.c_str(), offset);
auto real_path = _device->RootDir() / path;
DIR *dp = (DIR*)(uintptr_t)fileinfo->fh;
struct dirent *de = ::readdir(dp);
if (de == nullptr) {
return -errno;
}
do {
if (filler(buf, de->d_name, nullptr, 0) != 0) {
return -ENOMEM;
}
} while ((de = ::readdir(dp)) != nullptr);
return 0;
}
int CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {
//printf("releasedir(%s, _)\n", path.c_str());
int retstat = closedir((DIR*)(uintptr_t)fileinfo->fh);
return errcode_map(retstat);
}
int CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {
UNUSED(fileinfo);
//printf("Called non-implemented fsyncdir(%s, %d, _)\n", path.c_str(), datasync);
return 0;
}
void CryFuse::init(fuse_conn_info *conn) {
UNUSED(conn);
//printf("init()\n");
}
void CryFuse::destroy() {
//printf("destroy()\n");
}
int CryFuse::access(const path &path, int mask) {
//printf("access(%s, %d)\n", path.c_str(), mask);
auto real_path = _device->RootDir() / path;
int retstat = ::access(real_path.c_str(), mask);
return errcode_map(retstat);
}
int CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {
//printf("create(%s, %d, _)\n", path.c_str(), mode);
auto real_path = _device->RootDir() / path;
int fd = ::creat(real_path.c_str(), mode);
if (fd < 0) {
return -errno;
}
fileinfo->fh = fd;
return 0;
}
} /* namespace cryfs */
<commit_msg>Added gtest framework and fixed compiler warnings<commit_after>#include "CryFuse.h"
#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <cassert>
#include "cryfs_lib/CryNode.h"
#include "cryfs_lib/CryErrnoException.h"
#define UNUSED(expr) (void)(expr)
using fusepp::path;
namespace cryfs {
namespace {
int errcode_map(int exit_status) {
if (exit_status < 0) {
return -errno;
}
return exit_status;
}
}
CryFuse::CryFuse(CryDevice *device)
:_device(device) {
}
int CryFuse::getattr(const path &path, struct stat *stbuf) {
try {
_device->LoadFromPath(path)->stat(stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {
//printf("fgetattr(%s, _, _)\n", path.c_str());
// On FreeBSD, trying to do anything with the mountpoint ends up
// opening it, and then using the FD for an fgetattr. So in the
// special case of a path of "/", I need to do a getattr on the
// underlying root directory instead of doing the fgetattr().
if (path.native() == "/") {
return getattr(path, stbuf);
}
int retstat = fstat(fileinfo->fh, stbuf);
return errcode_map(retstat);
}
int CryFuse::readlink(const path &path, char *buf, size_t size) {
//printf("readlink(%s, _, %zu)\n", path.c_str(), size);
auto real_path = _device->RootDir() / path;
//size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,
//but the posix version does not and also doesn't append one.
int real_size = ::readlink(real_path.c_str(), buf, size-1);
if (real_size < 0) {
return -errno;
}
//Terminate the string
buf[real_size] = '\0';
return 0;
}
int CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {
UNUSED(rdev);
UNUSED(mode);
UNUSED(path);
printf("Called non-implemented mknod(%s, %d, _)\n", path.c_str(), mode);
return 0;
}
int CryFuse::mkdir(const path &path, mode_t mode) {
//printf("mkdir(%s, %d)\n", path.c_str(), mode);
auto real_path = _device->RootDir() / path;
int retstat = ::mkdir(real_path.c_str(), mode);
return errcode_map(retstat);
}
int CryFuse::unlink(const path &path) {
//printf("unlink(%s)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::unlink(real_path.c_str());
return errcode_map(retstat);
}
int CryFuse::rmdir(const path &path) {
//printf("rmdir(%s)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::rmdir(real_path.c_str());
return errcode_map(retstat);
}
int CryFuse::symlink(const path &from, const path &to) {
//printf("symlink(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::symlink(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
int CryFuse::rename(const path &from, const path &to) {
//printf("rename(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::rename(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
int CryFuse::link(const path &from, const path &to) {
//printf("link(%s, %s)\n", from.c_str(), to.c_str());
auto real_from = _device->RootDir() / from;
auto real_to = _device->RootDir() / to;
int retstat = ::link(real_from.c_str(), real_to.c_str());
return errcode_map(retstat);
}
int CryFuse::chmod(const path &path, mode_t mode) {
//printf("chmod(%s, %d)\n", path.c_str(), mode);
auto real_path = _device->RootDir() / path;
int retstat = ::chmod(real_path.c_str(), mode);
return errcode_map(retstat);
}
int CryFuse::chown(const path &path, uid_t uid, gid_t gid) {
//printf("chown(%s, %d, %d)\n", path.c_str(), uid, gid);
auto real_path = _device->RootDir() / path;
int retstat = ::chown(real_path.c_str(), uid, gid);
return errcode_map(retstat);
}
int CryFuse::truncate(const path &path, off_t size) {
//printf("truncate(%s, %zu)\n", path.c_str(), size);
auto real_path = _device->RootDir() / path;
int retstat = ::truncate(real_path.c_str(), size);
return errcode_map(retstat);
}
int CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {
//printf("ftruncate(%s, %zu, _)\n", path.c_str(), size);
UNUSED(path);
int retstat = ::ftruncate(fileinfo->fh, size);
return errcode_map(retstat);
}
int CryFuse::utimens(const path &path, const timespec times[2]) {
//printf("utimens(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
struct timeval tv[2];
tv[0].tv_sec = times[0].tv_sec;
tv[0].tv_usec = times[0].tv_nsec / 1000;
tv[1].tv_sec = times[1].tv_sec;
tv[1].tv_usec = times[1].tv_nsec / 1000;
int retstat = ::lutimes(real_path.c_str(), tv);
return errcode_map(retstat);
}
int CryFuse::open(const path &path, fuse_file_info *fileinfo) {
//printf("open(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int fd = ::open(real_path.c_str(), fileinfo->flags);
if (fd < 0) {
return -errno;
}
fileinfo->fh = fd;
return 0;
}
int CryFuse::release(const path &path, fuse_file_info *fileinfo) {
//printf("release(%s, _)\n", path.c_str());
UNUSED(path);
int retstat = ::close(fileinfo->fh);
return errcode_map(retstat);
}
int CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("read(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
int retstat = ::pread(fileinfo->fh, buf, size, offset);
return errcode_map(retstat);
}
int CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("write(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
int retstat = ::pwrite(fileinfo->fh, buf, size, offset);
return errcode_map(retstat);
}
int CryFuse::statfs(const path &path, struct statvfs *fsstat) {
//printf("statfs(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
int retstat = ::statvfs(real_path.c_str(), fsstat);
return errcode_map(retstat);
}
int CryFuse::flush(const path &path, fuse_file_info *fileinfo) {
//printf("Called non-implemented flush(%s, _)\n", path.c_str());
UNUSED(path);
UNUSED(fileinfo);
return 0;
}
int CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {
//printf("fsync(%s, %d, _)\n", path.c_str(), datasync);
UNUSED(path);
int retstat = 0;
if (datasync) {
retstat = ::fdatasync(fileinfo->fh);
} else {
retstat = ::fsync(fileinfo->fh);
}
return errcode_map(retstat);
}
int CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {
//printf("opendir(%s, _)\n", path.c_str());
auto real_path = _device->RootDir() / path;
DIR *dp = ::opendir(real_path.c_str());
if (dp == nullptr) {
return -errno;
}
fileinfo->fh = (intptr_t)dp;
return 0;
}
int CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {
//printf("readdir(%s, _, _, %zu, _)\n", path.c_str(), offset);
UNUSED(offset);
auto real_path = _device->RootDir() / path;
DIR *dp = (DIR*)(uintptr_t)fileinfo->fh;
struct dirent *de = ::readdir(dp);
if (de == nullptr) {
return -errno;
}
do {
if (filler(buf, de->d_name, nullptr, 0) != 0) {
return -ENOMEM;
}
} while ((de = ::readdir(dp)) != nullptr);
return 0;
}
int CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {
//printf("releasedir(%s, _)\n", path.c_str());
UNUSED(path);
int retstat = closedir((DIR*)(uintptr_t)fileinfo->fh);
return errcode_map(retstat);
}
int CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {
UNUSED(fileinfo);
UNUSED(datasync);
UNUSED(path);
//printf("Called non-implemented fsyncdir(%s, %d, _)\n", path.c_str(), datasync);
return 0;
}
void CryFuse::init(fuse_conn_info *conn) {
UNUSED(conn);
//printf("init()\n");
}
void CryFuse::destroy() {
//printf("destroy()\n");
}
int CryFuse::access(const path &path, int mask) {
//printf("access(%s, %d)\n", path.c_str(), mask);
auto real_path = _device->RootDir() / path;
int retstat = ::access(real_path.c_str(), mask);
return errcode_map(retstat);
}
int CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {
//printf("create(%s, %d, _)\n", path.c_str(), mode);
auto real_path = _device->RootDir() / path;
int fd = ::creat(real_path.c_str(), mode);
if (fd < 0) {
return -errno;
}
fileinfo->fh = fd;
return 0;
}
} /* namespace cryfs */
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014 Srinath Ravichandran, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "curveobjectreader.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/math/sampling/mappings.h"
#include "foundation/math/aabb.h"
#include "foundation/math/qmc.h"
#include "foundation/math/rng.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/platform/defaulttimers.h"
#include "foundation/utility/searchpaths.h"
#include "foundation/utility/stopwatch.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <cassert>
#include <cmath>
#include <cstddef>
#include <fstream>
#include <string>
#include <vector>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// CurveObjectReader class implementation.
//
auto_release_ptr<CurveObject> CurveObjectReader::read(
const SearchPaths& search_paths,
const char* name,
const ParamArray& params)
{
const string filepath = params.get<string>("filepath");
if (filepath == "builtin:hairball")
return create_hair_ball(name, params);
else if (filepath == "builtin:furryball")
return create_furry_ball(name, params);
else return load_curve_file(search_paths, name, params);
}
namespace
{
template <typename RNG>
static Vector2d rand_vector2d(RNG& rng)
{
Vector2d v;
v[0] = rand_double2(rng);
v[1] = rand_double2(rng);
return v;
}
void split_and_store(CurveObject& object, const BezierCurve3d& curve, const size_t split_count)
{
if (split_count > 0)
{
BezierCurve3d child1, child2;
curve.split(child1, child2);
split_and_store(object, child1, split_count - 1);
split_and_store(object, child2, split_count - 1);
}
else object.push_curve(curve);
}
}
auto_release_ptr<CurveObject> CurveObjectReader::create_hair_ball(
const char* name,
const ParamArray& params)
{
auto_release_ptr<CurveObject> object = CurveObjectFactory::create(name, params);
const size_t ControlPointCount = 4;
const size_t curve_count = params.get_optional<size_t>("curves", 100);
const double curve_width = params.get_optional<double>("width", 0.002);
const size_t split_count = params.get_optional<size_t>("presplits", 0);
Vector3d points[ControlPointCount];
MersenneTwister rng;
object->reserve_curves(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
for (size_t p = 0; p < ControlPointCount; ++p)
{
// http://math.stackexchange.com/questions/87230/picking-random-points-in-the-volume-of-sphere-with-uniform-probability
const double r = pow(1.0 - rand_double2(rng), 1.0 / 3);
const Vector3d d = sample_sphere_uniform(rand_vector2d(rng));
points[p] = r * d;
}
const BezierCurve3d curve(&points[0], curve_width);
split_and_store(object.ref(), curve, split_count);
}
return object;
}
auto_release_ptr<CurveObject> CurveObjectReader::create_furry_ball(
const char* name,
const ParamArray& params)
{
auto_release_ptr<CurveObject> object = CurveObjectFactory::create(name, params);
const size_t ControlPointCount = 4;
const size_t curve_count = params.get_optional<size_t>("curves", 100);
const double curve_length = params.get_optional<double>("length", 0.1);
const double base_width = params.get_optional<double>("base_width", 0.001);
const double tip_width = params.get_optional<double>("tip_width", 0.0001);
const double length_fuzziness = params.get_optional<double>("length_fuzziness", 0.3);
const double curliness = params.get_optional<double>("curliness", 0.5);
const size_t split_count = params.get_optional<size_t>("presplits", 0);
Vector3d points[ControlPointCount];
double widths[ControlPointCount];
MersenneTwister rng;
object->reserve_curves(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
static const size_t Bases[] = { 2 };
const Vector2d s = hammersley_sequence<double, 2>(Bases, c, curve_count);
const Vector3d d = sample_sphere_uniform(s);
points[0] = d;
widths[0] = base_width;
const double f = rand_double1(rng, -length_fuzziness, +length_fuzziness);
const double length = curve_length * (1.0 + f);
for (size_t p = 1; p < ControlPointCount; ++p)
{
const double r = static_cast<double>(p) / (ControlPointCount - 1);
const Vector3d f = curliness * sample_sphere_uniform(rand_vector2d(rng));
points[p] = points[0] + length * (r * d + f);
widths[p] = lerp(base_width, tip_width, r);
}
const BezierCurve3d curve(&points[0], &widths[0]);
split_and_store(object.ref(), curve, split_count);
}
return object;
}
auto_release_ptr<CurveObject> CurveObjectReader::load_curve_file(
const SearchPaths& search_paths,
const char* name,
const ParamArray& params)
{
auto_release_ptr<CurveObject> object = CurveObjectFactory::create(name, params);
const string filepath = search_paths.qualify(params.get<string>("filepath"));
const size_t split_count = params.get_optional<size_t>("presplits", 0);
ifstream input;
input.open(filepath);
if (input.good())
{
Stopwatch<DefaultWallclockTimer> stopwatch;
stopwatch.start();
// Read the number of curves.
size_t curve_count;
input >> curve_count;
// Read the number of control points per curve.
size_t control_point_count;
input >> control_point_count;
if (control_point_count != 4)
{
RENDERER_LOG_ERROR(
"while loading curve file %s: only curves with 4 control points are currently supported.",
filepath.c_str());
return object;
}
vector<Vector3d> points(control_point_count);
vector<double> widths(control_point_count);
object->reserve_curves(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
for (size_t p = 0; p < control_point_count; ++p)
{
input >> points[p].x >> points[p].y >> points[p].z;
input >> widths[p];
}
const BezierCurve3d curve(&points[0], &widths[0]);
split_and_store(object.ref(), curve, split_count);
}
input.close();
stopwatch.measure();
RENDERER_LOG_INFO(
"loaded curve file %s (%s curves) in %s.",
filepath.c_str(),
pretty_uint(curve_count).c_str(),
pretty_time(stopwatch.get_seconds()).c_str());
}
else
{
RENDERER_LOG_ERROR("failed to load curve file %s.", filepath.c_str());
}
return object;
}
} // namespace renderer
<commit_msg>fixed build.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014 Srinath Ravichandran, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "curveobjectreader.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/math/sampling/mappings.h"
#include "foundation/math/aabb.h"
#include "foundation/math/qmc.h"
#include "foundation/math/rng.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/platform/defaulttimers.h"
#include "foundation/utility/searchpaths.h"
#include "foundation/utility/stopwatch.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <cassert>
#include <cmath>
#include <cstddef>
#include <fstream>
#include <string>
#include <vector>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// CurveObjectReader class implementation.
//
auto_release_ptr<CurveObject> CurveObjectReader::read(
const SearchPaths& search_paths,
const char* name,
const ParamArray& params)
{
const string filepath = params.get<string>("filepath");
if (filepath == "builtin:hairball")
return create_hair_ball(name, params);
else if (filepath == "builtin:furryball")
return create_furry_ball(name, params);
else return load_curve_file(search_paths, name, params);
}
namespace
{
template <typename RNG>
static Vector2d rand_vector2d(RNG& rng)
{
Vector2d v;
v[0] = rand_double2(rng);
v[1] = rand_double2(rng);
return v;
}
void split_and_store(CurveObject& object, const BezierCurve3d& curve, const size_t split_count)
{
if (split_count > 0)
{
BezierCurve3d child1, child2;
curve.split(child1, child2);
split_and_store(object, child1, split_count - 1);
split_and_store(object, child2, split_count - 1);
}
else object.push_curve(curve);
}
}
auto_release_ptr<CurveObject> CurveObjectReader::create_hair_ball(
const char* name,
const ParamArray& params)
{
auto_release_ptr<CurveObject> object = CurveObjectFactory::create(name, params);
const size_t ControlPointCount = 4;
const size_t curve_count = params.get_optional<size_t>("curves", 100);
const double curve_width = params.get_optional<double>("width", 0.002);
const size_t split_count = params.get_optional<size_t>("presplits", 0);
Vector3d points[ControlPointCount];
MersenneTwister rng;
object->reserve_curves(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
for (size_t p = 0; p < ControlPointCount; ++p)
{
// http://math.stackexchange.com/questions/87230/picking-random-points-in-the-volume-of-sphere-with-uniform-probability
const double r = pow(1.0 - rand_double2(rng), 1.0 / 3);
const Vector3d d = sample_sphere_uniform(rand_vector2d(rng));
points[p] = r * d;
}
const BezierCurve3d curve(&points[0], curve_width);
split_and_store(object.ref(), curve, split_count);
}
return object;
}
auto_release_ptr<CurveObject> CurveObjectReader::create_furry_ball(
const char* name,
const ParamArray& params)
{
auto_release_ptr<CurveObject> object = CurveObjectFactory::create(name, params);
const size_t ControlPointCount = 4;
const size_t curve_count = params.get_optional<size_t>("curves", 100);
const double curve_length = params.get_optional<double>("length", 0.1);
const double base_width = params.get_optional<double>("base_width", 0.001);
const double tip_width = params.get_optional<double>("tip_width", 0.0001);
const double length_fuzziness = params.get_optional<double>("length_fuzziness", 0.3);
const double curliness = params.get_optional<double>("curliness", 0.5);
const size_t split_count = params.get_optional<size_t>("presplits", 0);
Vector3d points[ControlPointCount];
double widths[ControlPointCount];
MersenneTwister rng;
object->reserve_curves(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
static const size_t Bases[] = { 2 };
const Vector2d s = hammersley_sequence<double, 2>(Bases, c, curve_count);
const Vector3d d = sample_sphere_uniform(s);
points[0] = d;
widths[0] = base_width;
const double f = rand_double1(rng, -length_fuzziness, +length_fuzziness);
const double length = curve_length * (1.0 + f);
for (size_t p = 1; p < ControlPointCount; ++p)
{
const double r = static_cast<double>(p) / (ControlPointCount - 1);
const Vector3d f = curliness * sample_sphere_uniform(rand_vector2d(rng));
points[p] = points[0] + length * (r * d + f);
widths[p] = lerp(base_width, tip_width, r);
}
const BezierCurve3d curve(&points[0], &widths[0]);
split_and_store(object.ref(), curve, split_count);
}
return object;
}
auto_release_ptr<CurveObject> CurveObjectReader::load_curve_file(
const SearchPaths& search_paths,
const char* name,
const ParamArray& params)
{
auto_release_ptr<CurveObject> object = CurveObjectFactory::create(name, params);
const string filepath = search_paths.qualify(params.get<string>("filepath"));
const size_t split_count = params.get_optional<size_t>("presplits", 0);
ifstream input;
input.open(filepath.c_str());
if (input.good())
{
Stopwatch<DefaultWallclockTimer> stopwatch;
stopwatch.start();
// Read the number of curves.
size_t curve_count;
input >> curve_count;
// Read the number of control points per curve.
size_t control_point_count;
input >> control_point_count;
if (control_point_count != 4)
{
RENDERER_LOG_ERROR(
"while loading curve file %s: only curves with 4 control points are currently supported.",
filepath.c_str());
return object;
}
vector<Vector3d> points(control_point_count);
vector<double> widths(control_point_count);
object->reserve_curves(curve_count);
for (size_t c = 0; c < curve_count; ++c)
{
for (size_t p = 0; p < control_point_count; ++p)
{
input >> points[p].x >> points[p].y >> points[p].z;
input >> widths[p];
}
const BezierCurve3d curve(&points[0], &widths[0]);
split_and_store(object.ref(), curve, split_count);
}
input.close();
stopwatch.measure();
RENDERER_LOG_INFO(
"loaded curve file %s (%s curves) in %s.",
filepath.c_str(),
pretty_uint(curve_count).c_str(),
pretty_time(stopwatch.get_seconds()).c_str());
}
else
{
RENDERER_LOG_ERROR("failed to load curve file %s.", filepath.c_str());
}
return object;
}
} // namespace renderer
<|endoftext|>
|
<commit_before><commit_msg>fix couple of lines on prim vtx<commit_after><|endoftext|>
|
<commit_before>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ViewShadowNode.h"
namespace facebook {
namespace react {
const char ViewComponentName[] = "View";
bool ViewShadowNode::isLayoutOnly() const {
const auto &viewProps = *std::static_pointer_cast<const ViewProps>(props_);
return viewProps.collapsable &&
// Event listeners
!viewProps.onLayout &&
// Generic Props
viewProps.nativeId.empty() &&
// Accessibility Props
!viewProps.accessible &&
// Style Props
viewProps.yogaStyle.overflow() == YGOverflowVisible &&
viewProps.opacity == 1.0 && !viewProps.backgroundColor &&
!viewProps.foregroundColor && !viewProps.shadowColor &&
viewProps.transform == Transform{} && viewProps.zIndex == 0 &&
// Layout Metrics
getLayoutMetrics().borderWidth == EdgeInsets{};
}
} // namespace react
} // namespace facebook
<commit_msg>Fabric: Optimizations in view flattening algorithm<commit_after>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ViewShadowNode.h"
namespace facebook {
namespace react {
const char ViewComponentName[] = "View";
bool ViewShadowNode::isLayoutOnly() const {
const auto &viewProps = *std::static_pointer_cast<const ViewProps>(props_);
return viewProps.collapsable &&
// Generic Props
viewProps.nativeId.empty() &&
// Accessibility Props
!viewProps.accessible &&
// Style Props
viewProps.yogaStyle.overflow() == YGOverflowVisible &&
viewProps.opacity == 1.0 && !viewProps.backgroundColor &&
!viewProps.foregroundColor && !viewProps.shadowColor &&
viewProps.transform == Transform{} && viewProps.zIndex == 0 &&
// Layout Metrics
getLayoutMetrics().borderWidth == EdgeInsets{};
}
} // namespace react
} // namespace facebook
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 BMW Car IT GmbH
*
* 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 "DltLogAppender/DltAdapter.h"
#include <dlt/dlt.h>
extern "C"
{
#include <dlt/dlt_filetransfer.h>
}
#define DLT_CHECK_ERROR(ERRCODE) \
if(status < 0) \
{ \
m_dltError=ERRCODE; \
} \
namespace capu
{
void* DltAdapter::s_fileContext = 0;
DltAdapter::DltAdapter()
: m_appName("")
, m_appDesc("")
, m_dltInitialized(false)
, m_dltError(DLT_ERROR_NO_ERROR)
{
int32_t status = 0;
dlt_init();
DLT_CHECK_ERROR(DLT_ERROR_INIT)
if(status>=0)
{
if(dlt_set_log_mode(DLT_USER_MODE_BOTH)>=0)
{
m_dltInitialized=true;
}
else
{
printf("No DLT daemon connected, DLT functionality is disabled\n");
}
}
}
DltAdapter::~DltAdapter()
{
getDltAdapter()->unregisterApplication();
int32_t status = dlt_free();
DLT_CHECK_ERROR(DLT_ERROR_DEINIT)
m_dltInitialized = false;
}
DltAdapter* DltAdapter::getDltAdapter()
{
static DltAdapter dltAdapter;
return &dltAdapter;
}
void DltAdapter::logMessage(const capu::LogMessage& msg)
{
int32_t status = 0;
if(!m_dltInitialized)
{
return;
}
if(&(msg.getContext()) == (void*)0)
{
m_dltError=DLT_ERROR_CONTEXT_INVALID;
return;
}
DltContext* dltContext = static_cast<DltContext*>(getDltContext(&(msg.getContext())).getPtr());
if(dltContext == (void*)0)
{
m_dltError=DLT_ERROR_MISSING_DLT_CONTEXT;
return;
}
//DLT_LOG_OFF indicates that message is not logged
//DLT_LOG_DEFAULT is unused here
DltLogLevelType ll=DLT_LOG_OFF;
switch(msg.getLogLevel())
{
case LL_TRACE:
case LL_ALL:
ll = DLT_LOG_VERBOSE;
break;
case LL_DEBUG:
ll = DLT_LOG_DEBUG;
break;
case LL_INFO:
ll = DLT_LOG_INFO;
break;
case LL_WARN:
ll = DLT_LOG_WARN;
break;
case LL_ERROR:
ll = DLT_LOG_ERROR;
break;
case LL_FATAL:
ll = DLT_LOG_FATAL;
break;
default:
//LL_OFF remains -> DLT_LOG_OFF is already set above
break;
}
if(ll == DLT_LOG_OFF)
{
return; // no need to continue
}
if(dltContext)
{
#ifdef DLT_CONTEXT_USE_LOG_LEVEL_PTR
void* log_level_ptr = dltContext->log_level_ptr;
if(log_level_ptr)
{
if(ll<=(uint8_t)*(dltContext->log_level_ptr) )
{
#endif
DltContextData ctxData;
status = dlt_user_log_write_start(dltContext,&ctxData,ll);
if (status >= 0)
{
status = dlt_user_log_write_string(&ctxData,msg.getLogMessage());
status = dlt_user_log_write_finish(&ctxData);
DLT_CHECK_ERROR(DLT_ERROR_USER_LOG)
}
else
{
DLT_CHECK_ERROR(DLT_ERROR_USER_LOG)
}
#if DLT_CONTEXT_USE_LOG_LEVEL_PTR
}
}
#endif
}
}
void DltAdapter::registerApplication(const String& id,const String& description)
{
int32_t status = 0;
if(!m_dltInitialized)
{
return;
}
if(m_appName == id)
{
return;
}
if(m_appName.getLength()>0)
{
unregisterApplication();
}
status = dlt_register_app(id.c_str(),description.c_str());
DLT_CHECK_ERROR(DLT_ERROR_REGISTER_APPLICATION_FAILED)
m_appName = id;
m_appName.truncate(4);//limit size of string to 4 chars, dlt cannot use more
m_appDesc = description;
s_fileContext = new DltContext;
m_dltContextList.push_back(s_fileContext);
status = dlt_register_context(static_cast<DltContext*>(s_fileContext),"FILE","File Transfer Context");
DLT_CHECK_ERROR(DLT_ERROR_REGISTER_CONTEXT_FAILED)
}
void DltAdapter::unregisterApplication()
{
int32_t status = 0;
if(!m_dltInitialized)
{
return;
}
if(s_fileContext)
{
status = dlt_unregister_context(static_cast<DltContext*>(s_fileContext));
}
for(uint32_t i = 0; i < m_dltContextList.size(); i++ )
{
delete (DltContext*)m_dltContextList[i];
}
DLT_CHECK_ERROR(DLT_ERROR_UNREGISTER_CONTEXT_FAILED)
status = dlt_unregister_app();
DLT_CHECK_ERROR(DLT_ERROR_UNREGISTER_APPLICATION_FAILED)
m_appName.truncate(0);
m_appDesc.truncate(0);
}
void* DltAdapter::registerContext(capu::LogContext* ctx,const capu::String& id)
{
int32_t status = 0;
if(!m_dltInitialized)
{
return (void*)0;
}
//if application name not set elsewhere use standard values so context can be created right here
if(m_appName.getLength()==0)
{
registerApplication("ADEF","Default Application");
}
DltContext* dltContext = static_cast<DltContext*>(getDltContext(ctx).getPtr());
if(dltContext)
{
return (void*)dltContext;//if pointer is set context is already initialized
}
dltContext = new DltContext;
m_dltContextList.push_back(dltContext);
String contextName = ctx->getContextName();
dlt_register_context(dltContext,id.c_str(),contextName.c_str());
DLT_CHECK_ERROR(DLT_ERROR_REGISTER_CONTEXT_FAILED)
ctx->setUserData(dltContext);
return dltContext;
}
void DltAdapter::unregisterContext(capu::LogContext* ctx)
{
int32_t status = 0;
if(!m_dltInitialized)
{
return;
}
DltContext* dltContext = static_cast<DltContext*>(getDltContext(ctx).getPtr());
if(dltContext)
{
ctx->setUserData((void*)0);
dlt_unregister_context(dltContext);
DLT_CHECK_ERROR(DLT_ERROR_UNREGISTER_CONTEXT_FAILED)
delete dltContext;
}
}
void DltAdapter::registerInjectionCallback(capu::LogContext* ctx,uint32_t sid,int (*dlt_injection_callback)(uint32_t service_id, void *data, uint32_t length))
{
int32_t status = 0;
if(!m_dltInitialized)
{
return;
}
DltContext* dltContext = static_cast<DltContext*>(getDltContext(ctx).getPtr());
if(dltContext)
{
dlt_register_injection_callback(dltContext,sid,dlt_injection_callback);
DLT_CHECK_ERROR(DLT_ERROR_INJECTION_CALLBACK_FAILURE)
}
}
void DltAdapter::transmitFile(const String& uri, int delFile, int timeout)
{
int32_t status=0;
if(!m_dltInitialized || uri.getLength() == 0 )
{
return;
}
dlt_user_log_file_infoAbout(static_cast<DltContext*>(s_fileContext),const_cast<const char*>(uri.c_str()));
status = dlt_user_log_file_complete(static_cast<DltContext*>(s_fileContext),const_cast<const char*>(uri.c_str()),delFile,timeout);
DLT_CHECK_ERROR(DLT_ERROR_FILETRANSFER_FAILURE)
}
DltContextPointer DltAdapter::getDltContext(const capu::LogContext* context)
{
return DltContextPointer(context->getUserData());
}
}
<commit_msg>valgrind : exclude static file transfer context from context list<commit_after>/*
* Copyright (C) 2015 BMW Car IT GmbH
*
* 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 "DltLogAppender/DltAdapter.h"
#include <dlt/dlt.h>
extern "C"
{
#include <dlt/dlt_filetransfer.h>
}
#define DLT_CHECK_ERROR(ERRCODE) \
if(status < 0) \
{ \
m_dltError=ERRCODE; \
} \
namespace capu
{
void* DltAdapter::s_fileContext = 0;
DltAdapter::DltAdapter()
: m_appName("")
, m_appDesc("")
, m_dltInitialized(false)
, m_dltError(DLT_ERROR_NO_ERROR)
{
int32_t status = 0;
dlt_init();
DLT_CHECK_ERROR(DLT_ERROR_INIT)
if(status>=0)
{
if(dlt_set_log_mode(DLT_USER_MODE_BOTH)>=0)
{
m_dltInitialized=true;
}
else
{
printf("No DLT daemon connected, DLT functionality is disabled\n");
}
}
}
DltAdapter::~DltAdapter()
{
getDltAdapter()->unregisterApplication();
int32_t status = dlt_free();
DLT_CHECK_ERROR(DLT_ERROR_DEINIT)
m_dltInitialized = false;
}
DltAdapter* DltAdapter::getDltAdapter()
{
static DltAdapter dltAdapter;
return &dltAdapter;
}
void DltAdapter::logMessage(const capu::LogMessage& msg)
{
int32_t status = 0;
if(!m_dltInitialized)
{
return;
}
if(&(msg.getContext()) == (void*)0)
{
m_dltError=DLT_ERROR_CONTEXT_INVALID;
return;
}
DltContext* dltContext = static_cast<DltContext*>(getDltContext(&(msg.getContext())).getPtr());
if(dltContext == (void*)0)
{
m_dltError=DLT_ERROR_MISSING_DLT_CONTEXT;
return;
}
//DLT_LOG_OFF indicates that message is not logged
//DLT_LOG_DEFAULT is unused here
DltLogLevelType ll=DLT_LOG_OFF;
switch(msg.getLogLevel())
{
case LL_TRACE:
case LL_ALL:
ll = DLT_LOG_VERBOSE;
break;
case LL_DEBUG:
ll = DLT_LOG_DEBUG;
break;
case LL_INFO:
ll = DLT_LOG_INFO;
break;
case LL_WARN:
ll = DLT_LOG_WARN;
break;
case LL_ERROR:
ll = DLT_LOG_ERROR;
break;
case LL_FATAL:
ll = DLT_LOG_FATAL;
break;
default:
//LL_OFF remains -> DLT_LOG_OFF is already set above
break;
}
if(ll == DLT_LOG_OFF)
{
return; // no need to continue
}
if(dltContext)
{
#ifdef DLT_CONTEXT_USE_LOG_LEVEL_PTR
void* log_level_ptr = dltContext->log_level_ptr;
if(log_level_ptr)
{
if(ll<=(uint8_t)*(dltContext->log_level_ptr) )
{
#endif
DltContextData ctxData;
status = dlt_user_log_write_start(dltContext,&ctxData,ll);
if (status >= 0)
{
status = dlt_user_log_write_string(&ctxData,msg.getLogMessage());
status = dlt_user_log_write_finish(&ctxData);
DLT_CHECK_ERROR(DLT_ERROR_USER_LOG)
}
else
{
DLT_CHECK_ERROR(DLT_ERROR_USER_LOG)
}
#if DLT_CONTEXT_USE_LOG_LEVEL_PTR
}
}
#endif
}
}
void DltAdapter::registerApplication(const String& id,const String& description)
{
int32_t status = 0;
if(!m_dltInitialized)
{
return;
}
if(m_appName == id)
{
return;
}
if(m_appName.getLength()>0)
{
unregisterApplication();
}
status = dlt_register_app(id.c_str(),description.c_str());
DLT_CHECK_ERROR(DLT_ERROR_REGISTER_APPLICATION_FAILED)
m_appName = id;
m_appName.truncate(4);//limit size of string to 4 chars, dlt cannot use more
m_appDesc = description;
s_fileContext = new DltContext;
status = dlt_register_context(static_cast<DltContext*>(s_fileContext),"FILE","File Transfer Context");
DLT_CHECK_ERROR(DLT_ERROR_REGISTER_CONTEXT_FAILED)
}
void DltAdapter::unregisterApplication()
{
int32_t status = 0;
if(!m_dltInitialized)
{
return;
}
if(s_fileContext)
{
status = dlt_unregister_context(static_cast<DltContext*>(s_fileContext));
}
for(uint32_t i = 0; i < m_dltContextList.size(); i++ )
{
delete (DltContext*)m_dltContextList[i];
}
delete (DltContext*)s_fileContext;
s_fileContext=0;
DLT_CHECK_ERROR(DLT_ERROR_UNREGISTER_CONTEXT_FAILED)
status = dlt_unregister_app();
DLT_CHECK_ERROR(DLT_ERROR_UNREGISTER_APPLICATION_FAILED)
m_appName.truncate(0);
m_appDesc.truncate(0);
}
void* DltAdapter::registerContext(capu::LogContext* ctx,const capu::String& id)
{
int32_t status = 0;
if(!m_dltInitialized)
{
return (void*)0;
}
//if application name not set elsewhere use standard values so context can be created right here
if(m_appName.getLength()==0)
{
registerApplication("ADEF","Default Application");
}
DltContext* dltContext = static_cast<DltContext*>(getDltContext(ctx).getPtr());
if(dltContext)
{
return (void*)dltContext;//if pointer is set context is already initialized
}
dltContext = new DltContext;
m_dltContextList.push_back(dltContext);
String contextName = ctx->getContextName();
dlt_register_context(dltContext,id.c_str(),contextName.c_str());
DLT_CHECK_ERROR(DLT_ERROR_REGISTER_CONTEXT_FAILED)
ctx->setUserData(dltContext);
return dltContext;
}
void DltAdapter::unregisterContext(capu::LogContext* ctx)
{
int32_t status = 0;
if(!m_dltInitialized)
{
return;
}
DltContext* dltContext = static_cast<DltContext*>(getDltContext(ctx).getPtr());
if(dltContext)
{
ctx->setUserData((void*)0);
dlt_unregister_context(dltContext);
for(uint32_t i = 0; i < m_dltContextList.size();i++)
{
if(m_dltContextList[i] == dltContext)
{
m_dltContextList.erase(i);
}
break;
}
DLT_CHECK_ERROR(DLT_ERROR_UNREGISTER_CONTEXT_FAILED)
delete dltContext;
}
}
void DltAdapter::registerInjectionCallback(capu::LogContext* ctx,uint32_t sid,int (*dlt_injection_callback)(uint32_t service_id, void *data, uint32_t length))
{
int32_t status = 0;
if(!m_dltInitialized)
{
return;
}
DltContext* dltContext = static_cast<DltContext*>(getDltContext(ctx).getPtr());
if(dltContext)
{
dlt_register_injection_callback(dltContext,sid,dlt_injection_callback);
DLT_CHECK_ERROR(DLT_ERROR_INJECTION_CALLBACK_FAILURE)
}
}
void DltAdapter::transmitFile(const String& uri, int delFile, int timeout)
{
int32_t status=0;
if(!m_dltInitialized || uri.getLength() == 0 )
{
return;
}
dlt_user_log_file_infoAbout(static_cast<DltContext*>(s_fileContext),const_cast<const char*>(uri.c_str()));
status = dlt_user_log_file_complete(static_cast<DltContext*>(s_fileContext),const_cast<const char*>(uri.c_str()),delFile,timeout);
DLT_CHECK_ERROR(DLT_ERROR_FILETRANSFER_FAILURE)
}
DltContextPointer DltAdapter::getDltContext(const capu::LogContext* context)
{
return DltContextPointer(context->getUserData());
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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.
*/
#include "amr_includes.H"
/* -----------------------------------------------------------------
Exchange corner and face information at same level
----------------------------------------------------------------- */
static
void cb_level_face_exchange(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
void *user)
{
// const int p4est_refineFactor = get_p4est_refineFactor(domain);
ClawPatch *this_cp = get_clawpatch(this_patch);
// Transform data needed at multi-block boundaries
const amr_options_t *gparms = get_domain_parms(domain);
fclaw2d_transform_data_t transform_data;
transform_data.mx = gparms->mx;
transform_data.my = gparms->my;
transform_data.based = 1; // cell-centered data in this routine.
transform_data.this_patch = this_patch;
transform_data.neighbor_patch = NULL; // gets filled in below.
// int numfaces = get_faces_per_patch(domain);
for (int iface = 0; iface < NumFaces; iface++)
{
// Output arguments
int neighbor_block_idx;
int ref_flag; // = -1, 0, 1
int *ref_flag_ptr = &ref_flag;
int fine_grid_pos;
int *fine_grid_pos_ptr = &fine_grid_pos;
fclaw2d_patch_t* ghost_patches[p4est_refineFactor];
transform_data.iface = iface;
get_face_neighbors(domain,
this_block_idx,
this_patch_idx,
iface,
&neighbor_block_idx,
ghost_patches,
&ref_flag_ptr,
&fine_grid_pos_ptr,
transform_data.transform);
if (ref_flag_ptr == NULL)
{
// No neighbors - we are at a physical boundary
}
else if (ref_flag == 0)
{
/* We have a neighbor patch at the same level */
fclaw2d_patch_t *neighbor_patch = ghost_patches[0];
ClawPatch *neighbor_cp = get_clawpatch(neighbor_patch);
/* This is now done for all boundaries */
transform_data.neighbor_patch = ghost_patches[0];
fclaw_cptr cptr; // unsigned long int
if (sizeof(cptr) != sizeof(&transform_data))
{
printf("amr_level_exchange : assumed size of ptr is incorrect; \
sizeof(cptr) = %u but sizeof(&transform_data) = %u\n",
sizeof(cptr), sizeof(&transform_data));
exit(0);
}
this_cp->exchange_face_ghost(iface,neighbor_cp,(fclaw_cptr) &transform_data);
/*
if (this_block_idx == neighbor_block_idx)
{
// Exchange between 'this_patch' and 'neighbor patch(es)' at face 'iface'
this_cp->exchange_face_ghost(iface,neighbor_cp);
}
else
{
// Initiate exchange from block 0
this_cp->mb_exchange_face_ghost(iface,neighbor_cp);
}
*/
} /* Check return from neighbor */
} /* loop over all faces */
}
static
void cb_level_corner_exchange(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
void *user)
{
// const int numfaces = get_faces_per_patch(domain);
fclaw_bool intersects_bc[NumFaces];
get_phys_boundary(domain,this_block_idx,this_patch_idx,
intersects_bc);
fclaw_bool intersects_block[NumFaces];
get_block_boundary(domain,this_block_idx,this_patch_idx,
intersects_block);
// Number of patch corners, not the number of corners in the domain!
// const int numcorners = get_corners_per_patch(domain);
for (int icorner = 0; icorner < NumCorners; icorner++)
{
// p4est has tons of lookup table like this, can be exposed similarly
int corner_faces[SpaceDim];
fclaw2d_domain_corner_faces(domain, icorner, corner_faces);
// Both faces are at a physical boundary
fclaw_bool is_phys_corner =
intersects_bc[corner_faces[0]] && intersects_bc[corner_faces[1]];
// Corner lies in interior of physical boundary edge.
fclaw_bool corner_on_phys_face = !is_phys_corner &&
(intersects_bc[corner_faces[0]] || intersects_bc[corner_faces[1]]);
// Either a corner at a block boundary (but not a physical boundary),
// or internal to a block
fclaw_bool interior_corner = !corner_on_phys_face && !is_phys_corner;
ClawPatch *this_cp = get_clawpatch(this_patch);
if (is_phys_corner)
{
// We don't have to worry about this now. It is
// now taken care of by smart sweeping in the bc2 routine.
}
else if (corner_on_phys_face)
{
// Again, smart sweeping on in the bc2 routine should take care of these
// corner cells.
}
else if (interior_corner)
{
// Both faces are at a block boundary
fclaw_bool is_block_corner =
intersects_block[corner_faces[0]] && intersects_block[corner_faces[1]];
// We know corner 'icorner' has an adjacent patch.
int corner_block_idx;
int ref_flag;
int *ref_flag_ptr = &ref_flag;
fclaw2d_patch_t *ghost_patch;
get_corner_neighbor(domain,
this_block_idx,
this_patch_idx,
icorner,
&corner_block_idx,
&ghost_patch,
&ref_flag_ptr,
is_block_corner);
if (ref_flag_ptr == NULL)
{
// We should never get here, since we only call 'get_corner_neighbors' in a
// situation in which we are sure we have neighbors.
}
else if (ref_flag == 0)
{
fclaw2d_patch_t* corner_patch = ghost_patch;
ClawPatch *corner_cp = get_clawpatch(corner_patch);
if (this_block_idx == corner_block_idx)
{
this_cp->exchange_corner_ghost(icorner,corner_cp);
}
else
{
// We are doing a corner exchange across blocks
this_cp->mb_exchange_corner_ghost(icorner,intersects_block,
corner_cp,is_block_corner);
}
}
}
}
}
/* -------------------------------------------------------------------
Main routine in this file
------------------------------------------------------------------- */
void level_exchange(fclaw2d_domain_t *domain, int level)
{
// Start exchanging
/* face exchanges */
fclaw2d_domain_iterate_level(domain, level,
cb_level_face_exchange, (void *) NULL);
/* Do corner exchange only after physical boundary conditions have
been set on all patches, since corners may overlap physical ghost
cell region of neighboring patch. ??? (where am I doing set_physbc?)
*/
fclaw2d_domain_iterate_level(domain, level, cb_level_corner_exchange,
(void *) NULL);
}
<commit_msg>Fix warnings in printf<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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.
*/
#include "amr_includes.H"
/* -----------------------------------------------------------------
Exchange corner and face information at same level
----------------------------------------------------------------- */
static
void cb_level_face_exchange(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
void *user)
{
// const int p4est_refineFactor = get_p4est_refineFactor(domain);
ClawPatch *this_cp = get_clawpatch(this_patch);
// Transform data needed at multi-block boundaries
const amr_options_t *gparms = get_domain_parms(domain);
fclaw2d_transform_data_t transform_data;
transform_data.mx = gparms->mx;
transform_data.my = gparms->my;
transform_data.based = 1; // cell-centered data in this routine.
transform_data.this_patch = this_patch;
transform_data.neighbor_patch = NULL; // gets filled in below.
// int numfaces = get_faces_per_patch(domain);
for (int iface = 0; iface < NumFaces; iface++)
{
// Output arguments
int neighbor_block_idx;
int ref_flag; // = -1, 0, 1
int *ref_flag_ptr = &ref_flag;
int fine_grid_pos;
int *fine_grid_pos_ptr = &fine_grid_pos;
fclaw2d_patch_t* ghost_patches[p4est_refineFactor];
transform_data.iface = iface;
get_face_neighbors(domain,
this_block_idx,
this_patch_idx,
iface,
&neighbor_block_idx,
ghost_patches,
&ref_flag_ptr,
&fine_grid_pos_ptr,
transform_data.transform);
if (ref_flag_ptr == NULL)
{
// No neighbors - we are at a physical boundary
}
else if (ref_flag == 0)
{
/* We have a neighbor patch at the same level */
fclaw2d_patch_t *neighbor_patch = ghost_patches[0];
ClawPatch *neighbor_cp = get_clawpatch(neighbor_patch);
/* This is now done for all boundaries */
transform_data.neighbor_patch = ghost_patches[0];
fclaw_cptr cptr; // unsigned long int
if (sizeof(cptr) != sizeof(&transform_data))
{
printf ("amr_level_exchange : assumed size of ptr is incorrect; "
"sizeof(cptr) = %llu but sizeof(&transform_data) = %llu\n",
(unsigned long long) sizeof(cptr),
(unsigned long long) sizeof(&transform_data));
exit(0);
}
this_cp->exchange_face_ghost(iface,neighbor_cp,(fclaw_cptr) &transform_data);
/*
if (this_block_idx == neighbor_block_idx)
{
// Exchange between 'this_patch' and 'neighbor patch(es)' at face 'iface'
this_cp->exchange_face_ghost(iface,neighbor_cp);
}
else
{
// Initiate exchange from block 0
this_cp->mb_exchange_face_ghost(iface,neighbor_cp);
}
*/
} /* Check return from neighbor */
} /* loop over all faces */
}
static
void cb_level_corner_exchange(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
void *user)
{
// const int numfaces = get_faces_per_patch(domain);
fclaw_bool intersects_bc[NumFaces];
get_phys_boundary(domain,this_block_idx,this_patch_idx,
intersects_bc);
fclaw_bool intersects_block[NumFaces];
get_block_boundary(domain,this_block_idx,this_patch_idx,
intersects_block);
// Number of patch corners, not the number of corners in the domain!
// const int numcorners = get_corners_per_patch(domain);
for (int icorner = 0; icorner < NumCorners; icorner++)
{
// p4est has tons of lookup table like this, can be exposed similarly
int corner_faces[SpaceDim];
fclaw2d_domain_corner_faces(domain, icorner, corner_faces);
// Both faces are at a physical boundary
fclaw_bool is_phys_corner =
intersects_bc[corner_faces[0]] && intersects_bc[corner_faces[1]];
// Corner lies in interior of physical boundary edge.
fclaw_bool corner_on_phys_face = !is_phys_corner &&
(intersects_bc[corner_faces[0]] || intersects_bc[corner_faces[1]]);
// Either a corner at a block boundary (but not a physical boundary),
// or internal to a block
fclaw_bool interior_corner = !corner_on_phys_face && !is_phys_corner;
ClawPatch *this_cp = get_clawpatch(this_patch);
if (is_phys_corner)
{
// We don't have to worry about this now. It is
// now taken care of by smart sweeping in the bc2 routine.
}
else if (corner_on_phys_face)
{
// Again, smart sweeping on in the bc2 routine should take care of these
// corner cells.
}
else if (interior_corner)
{
// Both faces are at a block boundary
fclaw_bool is_block_corner =
intersects_block[corner_faces[0]] && intersects_block[corner_faces[1]];
// We know corner 'icorner' has an adjacent patch.
int corner_block_idx;
int ref_flag;
int *ref_flag_ptr = &ref_flag;
fclaw2d_patch_t *ghost_patch;
get_corner_neighbor(domain,
this_block_idx,
this_patch_idx,
icorner,
&corner_block_idx,
&ghost_patch,
&ref_flag_ptr,
is_block_corner);
if (ref_flag_ptr == NULL)
{
// We should never get here, since we only call 'get_corner_neighbors' in a
// situation in which we are sure we have neighbors.
}
else if (ref_flag == 0)
{
fclaw2d_patch_t* corner_patch = ghost_patch;
ClawPatch *corner_cp = get_clawpatch(corner_patch);
if (this_block_idx == corner_block_idx)
{
this_cp->exchange_corner_ghost(icorner,corner_cp);
}
else
{
// We are doing a corner exchange across blocks
this_cp->mb_exchange_corner_ghost(icorner,intersects_block,
corner_cp,is_block_corner);
}
}
}
}
}
/* -------------------------------------------------------------------
Main routine in this file
------------------------------------------------------------------- */
void level_exchange(fclaw2d_domain_t *domain, int level)
{
// Start exchanging
/* face exchanges */
fclaw2d_domain_iterate_level(domain, level,
cb_level_face_exchange, (void *) NULL);
/* Do corner exchange only after physical boundary conditions have
been set on all patches, since corners may overlap physical ghost
cell region of neighboring patch. ??? (where am I doing set_physbc?)
*/
fclaw2d_domain_iterate_level(domain, level, cb_level_corner_exchange,
(void *) NULL);
}
<|endoftext|>
|
<commit_before>/** \file
*
* Copyright (c) 2016 by Travis Gockel. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
* as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* \author Travis Gockel (travis@gockelhut.com)
**/
#include "test.hpp"
#include "chrono_io.hpp"
#include "filesystem_util.hpp"
#include "stopwatch.hpp"
#include <jsonv/parse.hpp>
#include <jsonv/util.hpp>
#include <jsonv/value.hpp>
#include <fstream>
#include <iostream>
namespace jsonv_test
{
using namespace jsonv;
static const unsigned iterations = JSONV_DEBUG ? 1 : 100;
template <typename FLoadSource>
static void run_test(FLoadSource load, const std::string& from)
{
stopwatch timer;
for (unsigned cnt = 0; cnt < iterations; ++cnt)
{
auto src_data = load(from);
{
JSONV_TEST_TIME(timer);
parse(src_data);
}
}
std::cout << timer.get();
}
template <typename FLoadSource>
class benchmark_test :
public unit_test
{
public:
benchmark_test(FLoadSource load_source, std::string source_desc, std::string path) :
unit_test(std::string("benchmark/") + source_desc + "/" + filename(path)),
load_source(std::move(load_source)),
path(std::move(path))
{ }
virtual void run_impl() override
{
run_test(load_source, path);
}
private:
FLoadSource load_source;
std::string path;
};
class benchmark_test_initializer
{
public:
explicit benchmark_test_initializer(const std::string& rootpath)
{
using ifstream_loader = std::ifstream (*)(const std::string&);
ifstream_loader ifstream_load = [] (const std::string& p) { return std::ifstream(p); };
using string_loader = std::string (*)(const std::string&);
string_loader string_load = load_from_file;
recursive_directory_for_each(rootpath, ".json", [&, this] (const std::string& path)
{
_tests.emplace_back(new benchmark_test<ifstream_loader>(ifstream_load, "ifstream", path));
_tests.emplace_back(new benchmark_test<string_loader>(string_load, "string", path));
});
}
static std::string load_from_file(const std::string& path)
{
std::ifstream inputfile(path.c_str());
std::string out;
inputfile.seekg(0, std::ios::end);
out.reserve(inputfile.tellg());
inputfile.seekg(0, std::ios::beg);
out.assign(std::istreambuf_iterator<char>(inputfile), std::istreambuf_iterator<char>());
return out;
}
private:
std::deque<std::unique_ptr<unit_test>> _tests;
} benchmark_test_initializer_instance(test_path(""));
}
<commit_msg>Benchmarking: Fixes compilation for C++11 (pre-movable std::_stream).<commit_after>/** \file
*
* Copyright (c) 2016 by Travis Gockel. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
* as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* \author Travis Gockel (travis@gockelhut.com)
**/
#include "test.hpp"
#include "chrono_io.hpp"
#include "filesystem_util.hpp"
#include "stopwatch.hpp"
#include <jsonv/parse.hpp>
#include <jsonv/util.hpp>
#include <jsonv/value.hpp>
#include <fstream>
#include <iostream>
namespace jsonv_test
{
using namespace jsonv;
static const unsigned iterations = JSONV_DEBUG ? 1 : 100;
template <typename THolster, typename FLoader>
static void run_test(FLoader load, const std::string& from)
{
stopwatch timer;
for (unsigned cnt = 0; cnt < iterations; ++cnt)
{
THolster src_data{load(from)};
{
JSONV_TEST_TIME(timer);
parse(src_data);
}
}
std::cout << timer.get();
}
template <typename THolster>
class benchmark_test :
public unit_test
{
public:
using loader = std::string (*)(const std::string&);
public:
benchmark_test(loader load, std::string source_desc, std::string path) :
unit_test(std::string("benchmark/") + source_desc + "/" + filename(path)),
load(load),
path(std::move(path))
{ }
virtual void run_impl() override
{
run_test<THolster>(load, path);
}
private:
loader load;
std::string path;
};
class benchmark_test_initializer
{
public:
explicit benchmark_test_initializer(const std::string& rootpath)
{
recursive_directory_for_each(rootpath, ".json", [&, this] (const std::string& path)
{
_tests.emplace_back(new benchmark_test<std::ifstream>([] (const std::string& p) { return p; }, "ifstream", path));
_tests.emplace_back(new benchmark_test<std::string>(load_from_file, "string", path));
});
}
static std::string load_from_file(const std::string& path)
{
std::ifstream inputfile(path.c_str());
std::string out;
inputfile.seekg(0, std::ios::end);
out.reserve(inputfile.tellg());
inputfile.seekg(0, std::ios::beg);
out.assign(std::istreambuf_iterator<char>(inputfile), std::istreambuf_iterator<char>());
return out;
}
private:
std::deque<std::unique_ptr<unit_test>> _tests;
} benchmark_test_initializer_instance(test_path(""));
}
<|endoftext|>
|
<commit_before>#include <string.h>
#include "utest_helper.hpp"
static void compiler_fill_image_1d_array(void)
{
const size_t w = 64;
const size_t array = 8;
cl_image_format format;
cl_image_desc desc;
size_t origin[3] = { };
size_t region[3];
uint32_t* dst;
memset(&desc, 0x0, sizeof(cl_image_desc));
memset(&format, 0x0, sizeof(cl_image_format));
format.image_channel_order = CL_RGBA;
format.image_channel_data_type = CL_UNSIGNED_INT8;
desc.image_type = CL_MEM_OBJECT_IMAGE1D_ARRAY;
desc.image_width = w;
desc.image_row_pitch = 0;//w * sizeof(uint32_t);
desc.image_array_size = array;
// Setup kernel and images
OCL_CREATE_KERNEL("test_fill_image_1d_array");
OCL_CREATE_IMAGE(buf[0], 0, &format, &desc, NULL);
OCL_MAP_BUFFER_GTT(0);
memset(buf_data[0], 0, sizeof(uint32_t) * w * array);
OCL_UNMAP_BUFFER_GTT(0);
// Run the kernel
OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
globals[0] = w/2;
locals[0] = 16;
globals[1] = 8;
locals[1] = 8;
OCL_NDRANGE(2);
// Check result
region[0] = w;
region[1] = array;
region[2] = 1;
dst = (uint32_t*)malloc(w*array*sizeof(uint32_t));
OCL_READ_IMAGE(buf[0], origin, region, dst);
#if 0
printf("------ The image result is: -------\n");
for (uint32_t j = 0; j < array; j++) {
for (uint32_t i = 0; i < w; i++) {
printf(" %2x", dst[j*w + i]);
}
printf("\n");
}
#endif
for (uint32_t j = 0; j < array - 1; j++) {
for (uint32_t i = 0; i < w/2; i++) {
OCL_ASSERT(dst[j*w + i] == 0x03020100);
}
for (uint32_t i = w/2; i < w; i++) {
OCL_ASSERT(dst[j*w + i] == 0);
}
}
for (uint32_t i = 0; i < w; i++) {
OCL_ASSERT(dst[(array - 1)*w + i] == 0x0);
}
free(dst);
}
MAKE_UTEST_FROM_FUNCTION(compiler_fill_image_1d_array);
<commit_msg>Fix a bug of 1d image array test case.<commit_after>#include <string.h>
#include "utest_helper.hpp"
static void compiler_fill_image_1d_array(void)
{
const size_t w = 64;
const size_t array = 8;
cl_image_format format;
cl_image_desc desc;
size_t origin[3] = { };
size_t region[3];
uint32_t* dst;
uint32_t* src;
region[0] = w;
region[1] = array;
region[2] = 1;
memset(&desc, 0x0, sizeof(cl_image_desc));
memset(&format, 0x0, sizeof(cl_image_format));
format.image_channel_order = CL_RGBA;
format.image_channel_data_type = CL_UNSIGNED_INT8;
desc.image_type = CL_MEM_OBJECT_IMAGE1D_ARRAY;
desc.image_width = w;
desc.image_row_pitch = 0;//w * sizeof(uint32_t);
desc.image_array_size = array;
// Setup kernel and images
OCL_CREATE_KERNEL("test_fill_image_1d_array");
OCL_CREATE_IMAGE(buf[0], 0, &format, &desc, NULL);
src = (uint32_t*)malloc(w*array*sizeof(uint32_t));
memset(src, 0, sizeof(uint32_t) * w * array);
OCL_WRITE_IMAGE(buf[0], origin, region, src);
// Run the kernel
OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
globals[0] = w/2;
locals[0] = 16;
globals[1] = 8;
locals[1] = 8;
OCL_NDRANGE(2);
// Check result
dst = (uint32_t*)malloc(w*array*sizeof(uint32_t));
OCL_READ_IMAGE(buf[0], origin, region, dst);
#if 0
printf("------ The image result is: -------\n");
for (uint32_t j = 0; j < array; j++) {
for (uint32_t i = 0; i < w; i++) {
printf(" %2x", dst[j*w + i]);
}
printf("\n");
}
#endif
for (uint32_t j = 0; j < array - 1; j++) {
for (uint32_t i = 0; i < w/2; i++) {
OCL_ASSERT(dst[j*w + i] == 0x03020100);
}
for (uint32_t i = w/2; i < w; i++) {
OCL_ASSERT(dst[j*w + i] == 0);
}
}
for (uint32_t i = 0; i < w; i++) {
OCL_ASSERT(dst[(array - 1)*w + i] == 0x0);
}
free(dst);
}
MAKE_UTEST_FROM_FUNCTION(compiler_fill_image_1d_array);
<|endoftext|>
|
<commit_before>/*
* HMAC_DRBG
* (C) 2014,2015,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/hmac_drbg.h>
#include <algorithm>
namespace Botan {
namespace {
void check_limits(size_t reseed_interval,
size_t max_number_of_bytes_per_request)
{
// SP800-90A permits up to 2^48, but it is not usable on 32 bit
// platforms, so we only allow up to 2^24, which is still reasonably high
if(reseed_interval == 0 || reseed_interval > static_cast<size_t>(1) << 24)
{
throw Invalid_Argument("Invalid value for reseed_interval");
}
if(max_number_of_bytes_per_request == 0 || max_number_of_bytes_per_request > 64 * 1024)
{
throw Invalid_Argument("Invalid value for max_number_of_bytes_per_request");
}
}
}
HMAC_DRBG::HMAC_DRBG(std::unique_ptr<MessageAuthenticationCode> prf,
RandomNumberGenerator& underlying_rng,
size_t reseed_interval,
size_t max_number_of_bytes_per_request) :
Stateful_RNG(underlying_rng, reseed_interval),
m_mac(std::move(prf)),
m_max_number_of_bytes_per_request(max_number_of_bytes_per_request)
{
BOTAN_ASSERT_NONNULL(m_mac);
check_limits(reseed_interval, max_number_of_bytes_per_request);
clear();
}
HMAC_DRBG::HMAC_DRBG(std::unique_ptr<MessageAuthenticationCode> prf,
RandomNumberGenerator& underlying_rng,
Entropy_Sources& entropy_sources,
size_t reseed_interval,
size_t max_number_of_bytes_per_request) :
Stateful_RNG(underlying_rng, entropy_sources, reseed_interval),
m_mac(std::move(prf)),
m_max_number_of_bytes_per_request(max_number_of_bytes_per_request)
{
BOTAN_ASSERT_NONNULL(m_mac);
check_limits(reseed_interval, max_number_of_bytes_per_request);
clear();
}
HMAC_DRBG::HMAC_DRBG(std::unique_ptr<MessageAuthenticationCode> prf,
Entropy_Sources& entropy_sources,
size_t reseed_interval,
size_t max_number_of_bytes_per_request) :
Stateful_RNG(entropy_sources, reseed_interval),
m_mac(std::move(prf)),
m_max_number_of_bytes_per_request(max_number_of_bytes_per_request)
{
BOTAN_ASSERT_NONNULL(m_mac);
check_limits(reseed_interval, max_number_of_bytes_per_request);
clear();
}
HMAC_DRBG::HMAC_DRBG(std::unique_ptr<MessageAuthenticationCode> prf) :
Stateful_RNG(),
m_mac(std::move(prf)),
m_max_number_of_bytes_per_request(64*1024)
{
BOTAN_ASSERT_NONNULL(m_mac);
clear();
}
void HMAC_DRBG::clear()
{
Stateful_RNG::clear();
m_V.resize(m_mac->output_length());
for(size_t i = 0; i != m_V.size(); ++i)
m_V[i] = 0x01;
m_mac->set_key(std::vector<uint8_t>(m_mac->output_length(), 0x00));
}
std::string HMAC_DRBG::name() const
{
return "HMAC_DRBG(" + m_mac->name() + ")";
}
void HMAC_DRBG::randomize(uint8_t output[], size_t output_len)
{
randomize_with_input(output, output_len, nullptr, 0);
}
/*
* HMAC_DRBG generation
* See NIST SP800-90A section 10.1.2.5
*/
void HMAC_DRBG::randomize_with_input(uint8_t output[], size_t output_len,
const uint8_t input[], size_t input_len)
{
while(output_len > 0)
{
size_t this_req = std::min(m_max_number_of_bytes_per_request, output_len);
output_len -= this_req;
reseed_check();
if(input_len > 0)
{
update(input, input_len);
}
while(this_req)
{
const size_t to_copy = std::min(this_req, m_V.size());
m_mac->update(m_V.data(), m_V.size());
m_mac->final(m_V.data());
copy_mem(output, m_V.data(), to_copy);
output += to_copy;
this_req -= to_copy;
}
update(input, input_len);
}
}
/*
* Reset V and the mac key with new values
* See NIST SP800-90A section 10.1.2.2
*/
void HMAC_DRBG::update(const uint8_t input[], size_t input_len)
{
m_mac->update(m_V);
m_mac->update(0x00);
m_mac->update(input, input_len);
m_mac->set_key(m_mac->final());
m_mac->update(m_V.data(), m_V.size());
m_mac->final(m_V.data());
if(input_len > 0)
{
m_mac->update(m_V);
m_mac->update(0x01);
m_mac->update(input, input_len);
m_mac->set_key(m_mac->final());
m_mac->update(m_V.data(), m_V.size());
m_mac->final(m_V.data());
}
}
void HMAC_DRBG::add_entropy(const uint8_t input[], size_t input_len)
{
update(input, input_len);
if(8*input_len >= security_level())
{
reset_reseed_counter();
}
}
size_t HMAC_DRBG::security_level() const
{
// security strength of the hash function
// for pre-image resistance (see NIST SP 800-57)
// SHA-160: 128 bits, SHA-224, SHA-512/224: 192 bits,
// SHA-256, SHA-512/256, SHA-384, SHA-512: >= 256 bits
// NIST SP 800-90A only supports up to 256 bits though
if(m_mac->output_length() < 32)
{
return (m_mac->output_length() - 4) * 8;
}
else
{
return 32 * 8;
}
}
}
<commit_msg>Micro optimizations of HMAC_DRBG<commit_after>/*
* HMAC_DRBG
* (C) 2014,2015,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/hmac_drbg.h>
#include <algorithm>
namespace Botan {
namespace {
void check_limits(size_t reseed_interval,
size_t max_number_of_bytes_per_request)
{
// SP800-90A permits up to 2^48, but it is not usable on 32 bit
// platforms, so we only allow up to 2^24, which is still reasonably high
if(reseed_interval == 0 || reseed_interval > static_cast<size_t>(1) << 24)
{
throw Invalid_Argument("Invalid value for reseed_interval");
}
if(max_number_of_bytes_per_request == 0 || max_number_of_bytes_per_request > 64 * 1024)
{
throw Invalid_Argument("Invalid value for max_number_of_bytes_per_request");
}
}
}
HMAC_DRBG::HMAC_DRBG(std::unique_ptr<MessageAuthenticationCode> prf,
RandomNumberGenerator& underlying_rng,
size_t reseed_interval,
size_t max_number_of_bytes_per_request) :
Stateful_RNG(underlying_rng, reseed_interval),
m_mac(std::move(prf)),
m_max_number_of_bytes_per_request(max_number_of_bytes_per_request)
{
BOTAN_ASSERT_NONNULL(m_mac);
check_limits(reseed_interval, max_number_of_bytes_per_request);
clear();
}
HMAC_DRBG::HMAC_DRBG(std::unique_ptr<MessageAuthenticationCode> prf,
RandomNumberGenerator& underlying_rng,
Entropy_Sources& entropy_sources,
size_t reseed_interval,
size_t max_number_of_bytes_per_request) :
Stateful_RNG(underlying_rng, entropy_sources, reseed_interval),
m_mac(std::move(prf)),
m_max_number_of_bytes_per_request(max_number_of_bytes_per_request)
{
BOTAN_ASSERT_NONNULL(m_mac);
check_limits(reseed_interval, max_number_of_bytes_per_request);
clear();
}
HMAC_DRBG::HMAC_DRBG(std::unique_ptr<MessageAuthenticationCode> prf,
Entropy_Sources& entropy_sources,
size_t reseed_interval,
size_t max_number_of_bytes_per_request) :
Stateful_RNG(entropy_sources, reseed_interval),
m_mac(std::move(prf)),
m_max_number_of_bytes_per_request(max_number_of_bytes_per_request)
{
BOTAN_ASSERT_NONNULL(m_mac);
check_limits(reseed_interval, max_number_of_bytes_per_request);
clear();
}
HMAC_DRBG::HMAC_DRBG(std::unique_ptr<MessageAuthenticationCode> prf) :
Stateful_RNG(),
m_mac(std::move(prf)),
m_max_number_of_bytes_per_request(64*1024)
{
BOTAN_ASSERT_NONNULL(m_mac);
clear();
}
void HMAC_DRBG::clear()
{
Stateful_RNG::clear();
const size_t output_length = m_mac->output_length();
m_V.resize(output_length);
for(size_t i = 0; i != m_V.size(); ++i)
m_V[i] = 0x01;
m_mac->set_key(std::vector<uint8_t>(output_length, 0x00));
}
std::string HMAC_DRBG::name() const
{
return "HMAC_DRBG(" + m_mac->name() + ")";
}
void HMAC_DRBG::randomize(uint8_t output[], size_t output_len)
{
randomize_with_input(output, output_len, nullptr, 0);
}
/*
* HMAC_DRBG generation
* See NIST SP800-90A section 10.1.2.5
*/
void HMAC_DRBG::randomize_with_input(uint8_t output[], size_t output_len,
const uint8_t input[], size_t input_len)
{
while(output_len > 0)
{
size_t this_req = std::min(m_max_number_of_bytes_per_request, output_len);
output_len -= this_req;
reseed_check();
if(input_len > 0)
{
update(input, input_len);
}
while(this_req)
{
const size_t to_copy = std::min(this_req, m_V.size());
m_mac->update(m_V.data(), m_V.size());
m_mac->final(m_V.data());
copy_mem(output, m_V.data(), to_copy);
output += to_copy;
this_req -= to_copy;
}
update(input, input_len);
}
}
/*
* Reset V and the mac key with new values
* See NIST SP800-90A section 10.1.2.2
*/
void HMAC_DRBG::update(const uint8_t input[], size_t input_len)
{
secure_vector<uint8_t> T(m_V.size());
m_mac->update(m_V);
m_mac->update(0x00);
m_mac->update(input, input_len);
m_mac->final(T.data());
m_mac->set_key(T);
m_mac->update(m_V.data(), m_V.size());
m_mac->final(m_V.data());
if(input_len > 0)
{
m_mac->update(m_V);
m_mac->update(0x01);
m_mac->update(input, input_len);
m_mac->final(T.data());
m_mac->set_key(T);
m_mac->update(m_V.data(), m_V.size());
m_mac->final(m_V.data());
}
}
void HMAC_DRBG::add_entropy(const uint8_t input[], size_t input_len)
{
update(input, input_len);
if(8*input_len >= security_level())
{
reset_reseed_counter();
}
}
size_t HMAC_DRBG::security_level() const
{
// security strength of the hash function
// for pre-image resistance (see NIST SP 800-57)
// SHA-160: 128 bits, SHA-224, SHA-512/224: 192 bits,
// SHA-256, SHA-512/256, SHA-384, SHA-512: >= 256 bits
// NIST SP 800-90A only supports up to 256 bits though
const size_t output_length = m_mac->output_length();
if(output_length < 32)
{
return (output_length - 4) * 8;
}
else
{
return 32 * 8;
}
}
}
<|endoftext|>
|
<commit_before>///
/// @file EratBig.cpp
/// @brief Segmented sieve of Eratosthenes optimized for big sieving
/// primes. This is an optimized implementation of Tomas
/// Oliveira e Silva's cache-friendly bucket sieve algorithm:
/// http://www.ieeta.pt/~tos/software/prime_sieve.html
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/EratBig.hpp>
#include <primesieve/Bucket.hpp>
#include <primesieve/MemoryPool.hpp>
#include <primesieve/pmath.hpp>
#include <primesieve/primesieve_error.hpp>
#include <primesieve/types.hpp>
#include <primesieve/Wheel.hpp>
#include <stdint.h>
#include <cassert>
#include <algorithm>
#include <vector>
using std::rotate;
namespace primesieve {
/// @stop: Upper bound for sieving
/// @sieveSize: Sieve size in bytes
/// @maxPrime: Sieving primes <= maxPrime
///
void EratBig::init(uint64_t stop, uint64_t sieveSize, uint64_t maxPrime)
{
// '>> log2SieveSize' requires power of 2 sieveSize
if (!isPow2(sieveSize))
throw primesieve_error("EratBig: sieveSize is not a power of 2");
enabled_ = true;
maxPrime_ = maxPrime;
log2SieveSize_ = ilog2(sieveSize);
moduloSieveSize_ = sieveSize - 1;
Wheel::init(stop, sieveSize);
init(sieveSize);
}
void EratBig::init(uint64_t sieveSize)
{
uint64_t maxSievingPrime = maxPrime_ / 30;
uint64_t maxNextMultiple = maxSievingPrime * getMaxFactor() + getMaxFactor();
uint64_t maxMultipleIndex = sieveSize - 1 + maxNextMultiple;
uint64_t maxSegmentCount = maxMultipleIndex >> log2SieveSize_;
uint64_t size = maxSegmentCount + 1;
lists_.resize(size, nullptr);
for (Bucket*& list : lists_)
memoryPool_.addBucket(list);
}
/// Add a new sieving prime to EratBig
void EratBig::storeSievingPrime(uint64_t prime, uint64_t multipleIndex, uint64_t wheelIndex)
{
assert(prime <= maxPrime_);
uint64_t sievingPrime = prime / 30;
uint64_t segment = multipleIndex >> log2SieveSize_;
multipleIndex &= moduloSieveSize_;
if (!lists_[segment]->store(sievingPrime, multipleIndex, wheelIndex))
memoryPool_.addBucket(lists_[segment]);
}
/// Get the bucket list related to the current
/// segment, then iterate over its buckets
/// and call crossOff() for each bucket.
///
void EratBig::crossOff(byte_t* sieve)
{
while (lists_[0]->hasNext() ||
!lists_[0]->empty())
{
Bucket* bucket = lists_[0];
lists_[0] = nullptr;
memoryPool_.addBucket(lists_[0]);
while (bucket)
{
crossOff(sieve, bucket->begin(), bucket->end());
Bucket* processed = bucket;
bucket = bucket->next();
memoryPool_.freeBucket(processed);
}
}
rotate(lists_.begin(), lists_.begin() + 1, lists_.end());
}
/// Segmented sieve of Eratosthenes with wheel factorization
/// optimized for big sieving primes that have very few
/// multiples per segment. Cross-off the next multiple of
/// each sieving prime in the current bucket.
///
void EratBig::crossOff(byte_t* sieve, SievingPrime* primes, SievingPrime* end)
{
Bucket** lists = &lists_[0];
uint64_t moduloSieveSize = moduloSieveSize_;
uint64_t log2SieveSize = log2SieveSize_;
// 2 sieving primes are processed per loop iteration
// to increase instruction level parallelism
for (; primes + 2 <= end; primes += 2)
{
uint64_t multipleIndex0 = primes[0].getMultipleIndex();
uint64_t wheelIndex0 = primes[0].getWheelIndex();
uint64_t sievingPrime0 = primes[0].getSievingPrime();
uint64_t multipleIndex1 = primes[1].getMultipleIndex();
uint64_t wheelIndex1 = primes[1].getWheelIndex();
uint64_t sievingPrime1 = primes[1].getSievingPrime();
// cross-off the current multiple (unset bit)
// and calculate the next multiple
unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0);
unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1);
uint64_t segment0 = multipleIndex0 >> log2SieveSize;
uint64_t segment1 = multipleIndex1 >> log2SieveSize;
multipleIndex0 &= moduloSieveSize;
multipleIndex1 &= moduloSieveSize;
// move the 2 sieving primes to the list related
// to their next multiple
if (!lists[segment0]->store(sievingPrime0, multipleIndex0, wheelIndex0))
memoryPool_.addBucket(lists_[segment0]);
if (!lists[segment1]->store(sievingPrime1, multipleIndex1, wheelIndex1))
memoryPool_.addBucket(lists_[segment1]);
}
if (primes != end)
{
uint64_t multipleIndex = primes->getMultipleIndex();
uint64_t wheelIndex = primes->getWheelIndex();
uint64_t sievingPrime = primes->getSievingPrime();
unsetBit(sieve, sievingPrime, &multipleIndex, &wheelIndex);
uint64_t segment = multipleIndex >> log2SieveSize;
multipleIndex &= moduloSieveSize;
if (!lists[segment]->store(sievingPrime, multipleIndex, wheelIndex))
memoryPool_.addBucket(lists_[segment]);
}
}
} // namespace
<commit_msg>Refactor<commit_after>///
/// @file EratBig.cpp
/// @brief Segmented sieve of Eratosthenes optimized for big sieving
/// primes. This is an optimized implementation of Tomas
/// Oliveira e Silva's cache-friendly bucket sieve algorithm:
/// http://www.ieeta.pt/~tos/software/prime_sieve.html
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/EratBig.hpp>
#include <primesieve/Bucket.hpp>
#include <primesieve/MemoryPool.hpp>
#include <primesieve/pmath.hpp>
#include <primesieve/primesieve_error.hpp>
#include <primesieve/types.hpp>
#include <primesieve/Wheel.hpp>
#include <stdint.h>
#include <cassert>
#include <algorithm>
#include <vector>
using std::rotate;
namespace primesieve {
/// @stop: Upper bound for sieving
/// @sieveSize: Sieve size in bytes
/// @maxPrime: Sieving primes <= maxPrime
///
void EratBig::init(uint64_t stop, uint64_t sieveSize, uint64_t maxPrime)
{
// '>> log2SieveSize' requires power of 2 sieveSize
if (!isPow2(sieveSize))
throw primesieve_error("EratBig: sieveSize is not a power of 2");
enabled_ = true;
maxPrime_ = maxPrime;
log2SieveSize_ = ilog2(sieveSize);
moduloSieveSize_ = sieveSize - 1;
Wheel::init(stop, sieveSize);
init(sieveSize);
}
void EratBig::init(uint64_t sieveSize)
{
uint64_t maxSievingPrime = maxPrime_ / 30;
uint64_t maxNextMultiple = maxSievingPrime * getMaxFactor() + getMaxFactor();
uint64_t maxMultipleIndex = sieveSize - 1 + maxNextMultiple;
uint64_t maxSegmentCount = maxMultipleIndex >> log2SieveSize_;
uint64_t size = maxSegmentCount + 1;
lists_.resize(size, nullptr);
for (Bucket*& list : lists_)
memoryPool_.addBucket(list);
}
/// Add a new sieving prime to EratBig
void EratBig::storeSievingPrime(uint64_t prime, uint64_t multipleIndex, uint64_t wheelIndex)
{
assert(prime <= maxPrime_);
uint64_t sievingPrime = prime / 30;
uint64_t segment = multipleIndex >> log2SieveSize_;
multipleIndex &= moduloSieveSize_;
if (!lists_[segment]->store(sievingPrime, multipleIndex, wheelIndex))
memoryPool_.addBucket(lists_[segment]);
}
/// Get the bucket list related to the current
/// segment, then iterate over its buckets
/// and call crossOff() for each bucket.
///
void EratBig::crossOff(byte_t* sieve)
{
while (lists_[0]->hasNext() ||
!lists_[0]->empty())
{
Bucket* bucket = lists_[0];
lists_[0] = nullptr;
memoryPool_.addBucket(lists_[0]);
while (bucket)
{
crossOff(sieve, bucket->begin(), bucket->end());
Bucket* processed = bucket;
bucket = bucket->next();
memoryPool_.freeBucket(processed);
}
}
rotate(lists_.begin(), lists_.begin() + 1, lists_.end());
}
/// Segmented sieve of Eratosthenes with wheel factorization
/// optimized for big sieving primes that have very few
/// multiples per segment. Cross-off the next multiple of
/// each sieving prime in the current bucket.
///
void EratBig::crossOff(byte_t* sieve, SievingPrime* primes, SievingPrime* end)
{
Bucket** lists = &lists_[0];
uint64_t moduloSieveSize = moduloSieveSize_;
uint64_t log2SieveSize = log2SieveSize_;
// 2 sieving primes are processed per loop iteration
// to increase instruction level parallelism
for (; primes + 2 <= end; primes += 2)
{
uint64_t multipleIndex0 = primes[0].getMultipleIndex();
uint64_t wheelIndex0 = primes[0].getWheelIndex();
uint64_t sievingPrime0 = primes[0].getSievingPrime();
uint64_t multipleIndex1 = primes[1].getMultipleIndex();
uint64_t wheelIndex1 = primes[1].getWheelIndex();
uint64_t sievingPrime1 = primes[1].getSievingPrime();
// cross-off the current multiple (unset bit)
// and calculate the next multiple
unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0);
unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1);
uint64_t segment0 = multipleIndex0 >> log2SieveSize;
uint64_t segment1 = multipleIndex1 >> log2SieveSize;
multipleIndex0 &= moduloSieveSize;
multipleIndex1 &= moduloSieveSize;
// move the 2 sieving primes to the list related
// to their next multiple
if (!lists[segment0]->store(sievingPrime0, multipleIndex0, wheelIndex0))
memoryPool_.addBucket(lists_[segment0]);
if (!lists[segment1]->store(sievingPrime1, multipleIndex1, wheelIndex1))
memoryPool_.addBucket(lists_[segment1]);
}
if (primes != end)
{
uint64_t multipleIndex = primes->getMultipleIndex();
uint64_t wheelIndex = primes->getWheelIndex();
uint64_t sievingPrime = primes->getSievingPrime();
unsetBit(sieve, sievingPrime, &multipleIndex, &wheelIndex);
uint64_t segment = multipleIndex >> log2SieveSize;
multipleIndex &= moduloSieveSize;
if (!lists[segment]->store(sievingPrime, multipleIndex, wheelIndex))
memoryPool_.addBucket(lists_[segment]);
}
}
} // namespace
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <assert.h>
#include <stdio.h>
#include <vector>
#include "google/gflags.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/modules/audio_coding/neteq/tools/packet.h"
#include "webrtc/modules/audio_coding/neteq/tools/rtp_file_source.h"
// Flag validator.
static bool ValidatePayloadType(const char* flagname, int32_t value) {
if (value >= 0 && value <= 127) // Value is ok.
return true;
printf("Invalid value for --%s: %d\n", flagname, static_cast<int>(value));
return false;
}
static bool ValidateExtensionId(const char* flagname, int32_t value) {
if (value > 0 && value <= 255) // Value is ok.
return true;
printf("Invalid value for --%s: %d\n", flagname, static_cast<int>(value));
return false;
}
// Define command line flags.
DEFINE_int32(red, 117, "RTP payload type for RED");
static const bool red_dummy =
google::RegisterFlagValidator(&FLAGS_red, &ValidatePayloadType);
DEFINE_int32(audio_level, 1, "Extension ID for audio level (RFC 6464)");
static const bool audio_level_dummy =
google::RegisterFlagValidator(&FLAGS_audio_level, &ValidateExtensionId);
int main(int argc, char* argv[]) {
std::string program_name = argv[0];
std::string usage =
"Tool for parsing an RTP dump file to text output.\n"
"Run " +
program_name +
" --helpshort for usage.\n"
"Example usage:\n" +
program_name + " input.rtp output.txt\n\n" +
"Output is sent to stdout if no output file is given." +
"Note that this tool can read files with our without payloads.";
google::SetUsageMessage(usage);
google::ParseCommandLineFlags(&argc, &argv, true);
if (argc != 2 && argc != 3) {
// Print usage information.
printf("%s", google::ProgramUsage());
return 0;
}
printf("Input file: %s\n", argv[1]);
rtc::scoped_ptr<webrtc::test::RtpFileSource> file_source(
webrtc::test::RtpFileSource::Create(argv[1]));
assert(file_source.get());
// Set RTP extension ID.
bool print_audio_level = false;
if (!google::GetCommandLineFlagInfoOrDie("audio_level").is_default) {
print_audio_level = true;
file_source->RegisterRtpHeaderExtension(webrtc::kRtpExtensionAudioLevel,
FLAGS_audio_level);
}
FILE* out_file;
if (argc == 3) {
out_file = fopen(argv[2], "wt");
if (!out_file) {
printf("Cannot open output file %s\n", argv[2]);
return -1;
}
printf("Output file: %s\n\n", argv[2]);
} else {
out_file = stdout;
}
// Print file header.
fprintf(out_file, "SeqNo TimeStamp SendTime Size PT M SSRC");
if (print_audio_level) {
fprintf(out_file, " AuLvl (V)");
}
fprintf(out_file, "\n");
rtc::scoped_ptr<webrtc::test::Packet> packet;
while (true) {
packet.reset(file_source->NextPacket());
if (!packet.get()) {
// End of file reached.
break;
}
// Write packet data to file.
fprintf(out_file,
"%5u %10u %10u %5i %5i %2i %#08X",
packet->header().sequenceNumber,
packet->header().timestamp,
static_cast<unsigned int>(packet->time_ms()),
static_cast<int>(packet->packet_length_bytes()),
packet->header().payloadType,
packet->header().markerBit,
packet->header().ssrc);
if (print_audio_level && packet->header().extension.hasAudioLevel) {
// |audioLevel| consists of one bit for "V" and then 7 bits level.
fprintf(out_file,
" %5u (%1i)",
packet->header().extension.audioLevel & 0x7F,
(packet->header().extension.audioLevel & 0x80) == 0 ? 0 : 1);
}
fprintf(out_file, "\n");
if (packet->header().payloadType == FLAGS_red) {
std::list<webrtc::RTPHeader*> red_headers;
packet->ExtractRedHeaders(&red_headers);
while (!red_headers.empty()) {
webrtc::RTPHeader* red = red_headers.front();
assert(red);
fprintf(out_file,
"* %5u %10u %10u %5i\n",
red->sequenceNumber,
red->timestamp,
static_cast<unsigned int>(packet->time_ms()),
red->payloadType);
red_headers.pop_front();
delete red;
}
}
}
fclose(out_file);
return 0;
}
<commit_msg>Let rtp_analyze parse absolute sender time<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <assert.h>
#include <stdio.h>
#include <vector>
#include "google/gflags.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/modules/audio_coding/neteq/tools/packet.h"
#include "webrtc/modules/audio_coding/neteq/tools/rtp_file_source.h"
// Flag validator.
static bool ValidatePayloadType(const char* flagname, int32_t value) {
if (value >= 0 && value <= 127) // Value is ok.
return true;
printf("Invalid value for --%s: %d\n", flagname, static_cast<int>(value));
return false;
}
static bool ValidateExtensionId(const char* flagname, int32_t value) {
if (value > 0 && value <= 255) // Value is ok.
return true;
printf("Invalid value for --%s: %d\n", flagname, static_cast<int>(value));
return false;
}
// Define command line flags.
DEFINE_int32(red, 117, "RTP payload type for RED");
static const bool red_dummy =
google::RegisterFlagValidator(&FLAGS_red, &ValidatePayloadType);
DEFINE_int32(audio_level, 1, "Extension ID for audio level (RFC 6464)");
static const bool audio_level_dummy =
google::RegisterFlagValidator(&FLAGS_audio_level, &ValidateExtensionId);
DEFINE_int32(abs_send_time, 3, "Extension ID for absolute sender time");
static const bool abs_send_time_dummy =
google::RegisterFlagValidator(&FLAGS_abs_send_time, &ValidateExtensionId);
int main(int argc, char* argv[]) {
std::string program_name = argv[0];
std::string usage =
"Tool for parsing an RTP dump file to text output.\n"
"Run " +
program_name +
" --helpshort for usage.\n"
"Example usage:\n" +
program_name + " input.rtp output.txt\n\n" +
"Output is sent to stdout if no output file is given." +
"Note that this tool can read files with our without payloads.";
google::SetUsageMessage(usage);
google::ParseCommandLineFlags(&argc, &argv, true);
if (argc != 2 && argc != 3) {
// Print usage information.
printf("%s", google::ProgramUsage());
return 0;
}
printf("Input file: %s\n", argv[1]);
rtc::scoped_ptr<webrtc::test::RtpFileSource> file_source(
webrtc::test::RtpFileSource::Create(argv[1]));
assert(file_source.get());
// Set RTP extension IDs.
bool print_audio_level = false;
if (!google::GetCommandLineFlagInfoOrDie("audio_level").is_default) {
print_audio_level = true;
file_source->RegisterRtpHeaderExtension(webrtc::kRtpExtensionAudioLevel,
FLAGS_audio_level);
}
bool print_abs_send_time = false;
if (!google::GetCommandLineFlagInfoOrDie("abs_send_time").is_default) {
print_abs_send_time = true;
file_source->RegisterRtpHeaderExtension(
webrtc::kRtpExtensionAbsoluteSendTime, FLAGS_abs_send_time);
}
FILE* out_file;
if (argc == 3) {
out_file = fopen(argv[2], "wt");
if (!out_file) {
printf("Cannot open output file %s\n", argv[2]);
return -1;
}
printf("Output file: %s\n\n", argv[2]);
} else {
out_file = stdout;
}
// Print file header.
fprintf(out_file, "SeqNo TimeStamp SendTime Size PT M SSRC");
if (print_audio_level) {
fprintf(out_file, " AuLvl (V)");
}
if (print_abs_send_time) {
fprintf(out_file, " AbsSendTime");
}
fprintf(out_file, "\n");
uint32_t max_abs_send_time = 0;
int cycles = -1;
rtc::scoped_ptr<webrtc::test::Packet> packet;
while (true) {
packet.reset(file_source->NextPacket());
if (!packet.get()) {
// End of file reached.
break;
}
// Write packet data to file. Use virtual_packet_length_bytes so that the
// correct packet sizes are printed also for RTP header-only dumps.
fprintf(out_file,
"%5u %10u %10u %5i %5i %2i %#08X",
packet->header().sequenceNumber,
packet->header().timestamp,
static_cast<unsigned int>(packet->time_ms()),
static_cast<int>(packet->virtual_packet_length_bytes()),
packet->header().payloadType,
packet->header().markerBit,
packet->header().ssrc);
if (print_audio_level && packet->header().extension.hasAudioLevel) {
// |audioLevel| consists of one bit for "V" and then 7 bits level.
fprintf(out_file,
" %5u (%1i)",
packet->header().extension.audioLevel & 0x7F,
(packet->header().extension.audioLevel & 0x80) == 0 ? 0 : 1);
}
if (print_abs_send_time && packet->header().extension.hasAbsoluteSendTime) {
if (cycles == -1) {
// Initialize.
max_abs_send_time = packet->header().extension.absoluteSendTime;
cycles = 0;
}
// Abs sender time is 24 bit 6.18 fixed point. Shift by 8 to normalize to
// 32 bits (unsigned). Calculate the difference between this packet's
// send time and the maximum observed. Cast to signed 32-bit to get the
// desired wrap-around behavior.
if (static_cast<int32_t>(
(packet->header().extension.absoluteSendTime << 8) -
(max_abs_send_time << 8)) >= 0) {
// The difference is non-negative, meaning that this packet is newer
// than the previously observed maximum absolute send time.
if (packet->header().extension.absoluteSendTime < max_abs_send_time) {
// Wrap detected.
cycles++;
}
max_abs_send_time = packet->header().extension.absoluteSendTime;
}
// Abs sender time is 24 bit 6.18 fixed point. Divide by 2^18 to convert
// to floating point representation.
double send_time_seconds =
static_cast<double>(packet->header().extension.absoluteSendTime) /
262144 +
64.0 * cycles;
fprintf(out_file, " %11f", send_time_seconds);
}
fprintf(out_file, "\n");
if (packet->header().payloadType == FLAGS_red) {
std::list<webrtc::RTPHeader*> red_headers;
packet->ExtractRedHeaders(&red_headers);
while (!red_headers.empty()) {
webrtc::RTPHeader* red = red_headers.front();
assert(red);
fprintf(out_file,
"* %5u %10u %10u %5i\n",
red->sequenceNumber,
red->timestamp,
static_cast<unsigned int>(packet->time_ms()),
red->payloadType);
red_headers.pop_front();
delete red;
}
}
}
fclose(out_file);
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <private/qdrawhelper_p.h>
#include <private/qgl_p.h>
#include "qglgradientcache_p.h"
void QGL2GradientCache::cleanCache() {
QGLGradientColorTableHash::const_iterator it = cache.constBegin();
for (; it != cache.constEnd(); ++it) {
const CacheInfo &cache_info = it.value();
glDeleteTextures(1, &cache_info.texId);
}
cache.clear();
}
GLuint QGL2GradientCache::getBuffer(const QGradient &gradient, qreal opacity, const QGLContext *ctx)
{
if (buffer_ctx && !qgl_share_reg()->checkSharing(buffer_ctx, ctx))
cleanCache();
buffer_ctx = ctx;
quint64 hash_val = 0;
QGradientStops stops = gradient.stops();
for (int i = 0; i < stops.size() && i <= 2; i++)
hash_val += stops[i].second.rgba();
QGLGradientColorTableHash::const_iterator it = cache.constFind(hash_val);
if (it == cache.constEnd())
return addCacheElement(hash_val, gradient, opacity);
else {
do {
const CacheInfo &cache_info = it.value();
if (cache_info.stops == stops && cache_info.opacity == opacity && cache_info.interpolationMode == gradient.interpolationMode()) {
return cache_info.texId;
}
++it;
} while (it != cache.constEnd() && it.key() == hash_val);
// an exact match for these stops and opacity was not found, create new cache
return addCacheElement(hash_val, gradient, opacity);
}
}
GLuint QGL2GradientCache::addCacheElement(quint64 hash_val, const QGradient &gradient, qreal opacity)
{
if (cache.size() == maxCacheSize()) {
int elem_to_remove = qrand() % maxCacheSize();
quint64 key = cache.keys()[elem_to_remove];
// need to call glDeleteTextures on each removed cache entry:
QGLGradientColorTableHash::const_iterator it = cache.constFind(key);
do {
glDeleteTextures(1, &it.value().texId);
} while (++it != cache.constEnd() && it.key() == key);
cache.remove(key); // may remove more than 1, but OK
}
CacheInfo cache_entry(gradient.stops(), opacity, gradient.interpolationMode());
uint buffer[1024];
generateGradientColorTable(gradient, buffer, paletteSize(), opacity);
glGenTextures(1, &cache_entry.texId);
glBindTexture(GL_TEXTURE_2D, cache_entry.texId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, paletteSize(), 1,
0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
return cache.insert(hash_val, cache_entry).value().texId;
}
// GL's expects pixels in RGBA, bin-endian (ABGR on x86).
// Qt stores in ARGB using whatever byte-order the mancine uses.
static inline uint qtToGlColor(uint c)
{
uint o;
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
o = c & 0xFF00FF00; // alpha & green already in the right place
o |= (c >> 16) & 0x000000FF; // red
o |= (c << 16) & 0x00FF0000; // blue
#else //Q_BIG_ENDIAN
o = c & 0x00FF00FF; // alpha & green already in the right place
o |= (c << 16) & 0xFF000000; // red
o |= (c >> 16) & 0x0000FF00; // blue
#error big endian not tested with QGLGraphicsContext
#endif // Q_BYTE_ORDER
return o;
}
//TODO: Let GL generate the texture using an FBO
void QGL2GradientCache::generateGradientColorTable(const QGradient& gradient, uint *colorTable, int size, qreal opacity) const
{
int pos = 0;
QGradientStops s = gradient.stops();
QVector<uint> colors(s.size());
for (int i = 0; i < s.size(); ++i)
colors[i] = s[i].second.rgba(); // Qt LIES! It returns ARGB
bool colorInterpolation = (gradient.interpolationMode() == QGradient::ColorInterpolation);
uint alpha = qRound(opacity * 256);
uint current_color = ARGB_COMBINE_ALPHA(colors[0], alpha);
qreal incr = 1.0 / qreal(size);
qreal fpos = 1.5 * incr;
colorTable[pos++] = qtToGlColor(PREMUL(current_color));
while (fpos <= s.first().first) {
colorTable[pos] = colorTable[pos - 1];
pos++;
fpos += incr;
}
if (colorInterpolation)
current_color = PREMUL(current_color);
for (int i = 0; i < s.size() - 1; ++i) {
qreal delta = 1/(s[i+1].first - s[i].first);
uint next_color = ARGB_COMBINE_ALPHA(colors[i+1], alpha);
if (colorInterpolation)
next_color = PREMUL(next_color);
while (fpos < s[i+1].first && pos < size) {
int dist = int(256 * ((fpos - s[i].first) * delta));
int idist = 256 - dist;
if (colorInterpolation)
colorTable[pos] = qtToGlColor(INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist));
else
colorTable[pos] = qtToGlColor(PREMUL(INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist)));
++pos;
fpos += incr;
}
current_color = next_color;
}
Q_ASSERT(s.size() > 0);
uint last_color = qtToGlColor(PREMUL(ARGB_COMBINE_ALPHA(colors[s.size() - 1], alpha)));
for (;pos < size; ++pos)
colorTable[pos] = last_color;
// Make sure the last color stop is represented at the end of the table
colorTable[size-1] = last_color;
}
<commit_msg>Fix GL2 paint engine builds on Big-endian machines<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <private/qdrawhelper_p.h>
#include <private/qgl_p.h>
#include "qglgradientcache_p.h"
void QGL2GradientCache::cleanCache() {
QGLGradientColorTableHash::const_iterator it = cache.constBegin();
for (; it != cache.constEnd(); ++it) {
const CacheInfo &cache_info = it.value();
glDeleteTextures(1, &cache_info.texId);
}
cache.clear();
}
GLuint QGL2GradientCache::getBuffer(const QGradient &gradient, qreal opacity, const QGLContext *ctx)
{
if (buffer_ctx && !qgl_share_reg()->checkSharing(buffer_ctx, ctx))
cleanCache();
buffer_ctx = ctx;
quint64 hash_val = 0;
QGradientStops stops = gradient.stops();
for (int i = 0; i < stops.size() && i <= 2; i++)
hash_val += stops[i].second.rgba();
QGLGradientColorTableHash::const_iterator it = cache.constFind(hash_val);
if (it == cache.constEnd())
return addCacheElement(hash_val, gradient, opacity);
else {
do {
const CacheInfo &cache_info = it.value();
if (cache_info.stops == stops && cache_info.opacity == opacity && cache_info.interpolationMode == gradient.interpolationMode()) {
return cache_info.texId;
}
++it;
} while (it != cache.constEnd() && it.key() == hash_val);
// an exact match for these stops and opacity was not found, create new cache
return addCacheElement(hash_val, gradient, opacity);
}
}
GLuint QGL2GradientCache::addCacheElement(quint64 hash_val, const QGradient &gradient, qreal opacity)
{
if (cache.size() == maxCacheSize()) {
int elem_to_remove = qrand() % maxCacheSize();
quint64 key = cache.keys()[elem_to_remove];
// need to call glDeleteTextures on each removed cache entry:
QGLGradientColorTableHash::const_iterator it = cache.constFind(key);
do {
glDeleteTextures(1, &it.value().texId);
} while (++it != cache.constEnd() && it.key() == key);
cache.remove(key); // may remove more than 1, but OK
}
CacheInfo cache_entry(gradient.stops(), opacity, gradient.interpolationMode());
uint buffer[1024];
generateGradientColorTable(gradient, buffer, paletteSize(), opacity);
glGenTextures(1, &cache_entry.texId);
glBindTexture(GL_TEXTURE_2D, cache_entry.texId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, paletteSize(), 1,
0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
return cache.insert(hash_val, cache_entry).value().texId;
}
// GL's expects pixels in RGBA (when using GL_RGBA), bin-endian (ABGR on x86).
// Qt always stores in ARGB reguardless of the byte-order the mancine uses.
static inline uint qtToGlColor(uint c)
{
uint o;
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
o = (c & 0xff00ff00) // alpha & green already in the right place
| ((c >> 16) & 0x000000ff) // red
| ((c << 16) & 0x00ff0000); // blue
#else //Q_BIG_ENDIAN
o = (c << 8)
| ((c >> 24) & 0x000000ff);
#endif // Q_BYTE_ORDER
return o;
}
//TODO: Let GL generate the texture using an FBO
void QGL2GradientCache::generateGradientColorTable(const QGradient& gradient, uint *colorTable, int size, qreal opacity) const
{
int pos = 0;
QGradientStops s = gradient.stops();
QVector<uint> colors(s.size());
for (int i = 0; i < s.size(); ++i)
colors[i] = s[i].second.rgba(); // Qt LIES! It returns ARGB (on little-endian AND on big-endian)
bool colorInterpolation = (gradient.interpolationMode() == QGradient::ColorInterpolation);
uint alpha = qRound(opacity * 256);
uint current_color = ARGB_COMBINE_ALPHA(colors[0], alpha);
qreal incr = 1.0 / qreal(size);
qreal fpos = 1.5 * incr;
colorTable[pos++] = qtToGlColor(PREMUL(current_color));
while (fpos <= s.first().first) {
colorTable[pos] = colorTable[pos - 1];
pos++;
fpos += incr;
}
if (colorInterpolation)
current_color = PREMUL(current_color);
for (int i = 0; i < s.size() - 1; ++i) {
qreal delta = 1/(s[i+1].first - s[i].first);
uint next_color = ARGB_COMBINE_ALPHA(colors[i+1], alpha);
if (colorInterpolation)
next_color = PREMUL(next_color);
while (fpos < s[i+1].first && pos < size) {
int dist = int(256 * ((fpos - s[i].first) * delta));
int idist = 256 - dist;
if (colorInterpolation)
colorTable[pos] = qtToGlColor(INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist));
else
colorTable[pos] = qtToGlColor(PREMUL(INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist)));
++pos;
fpos += incr;
}
current_color = next_color;
}
Q_ASSERT(s.size() > 0);
uint last_color = qtToGlColor(PREMUL(ARGB_COMBINE_ALPHA(colors[s.size() - 1], alpha)));
for (;pos < size; ++pos)
colorTable[pos] = last_color;
// Make sure the last color stop is represented at the end of the table
colorTable[size-1] = last_color;
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2016 by Contributors
* \file broadcast_reduce_op_value.cc
* \brief CPU Implementation of broadcast and reduce functions based on value.
*/
#include "./broadcast_reduce_op.h"
namespace mxnet {
namespace op {
DMLC_REGISTER_PARAMETER(ReduceAxesParam);
DMLC_REGISTER_PARAMETER(ReduceAxisParam);
DMLC_REGISTER_PARAMETER(BroadcastAxesParam);
DMLC_REGISTER_PARAMETER(BroadcastToParam);
DMLC_REGISTER_PARAMETER(BroadcastLikeParam);
template<typename DType>
void BroadcastAxisKer(DType* src,
DType* dst,
index_t outer,
index_t inner,
index_t size) {
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (index_t i = 0; i < outer * size; i++) {
const index_t m = i / size;
const index_t n = i % size;
void* offset = reinterpret_cast<void*>(dst + m * size * inner + n * inner);
memcpy(offset, reinterpret_cast<void*>(src + m * inner), inner * sizeof (DType));
}
}
inline void BroadcastAxisComputeCPU(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const BroadcastAxesParam& param = nnvm::get<BroadcastAxesParam>(attrs.parsed);
if (param.axis.ndim() == 1 && inputs[0].shape_[param.axis[0]] == 1 && req[0] == kWriteTo) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
auto dst = outputs[0].dptr<DType>();
auto src = inputs[0].dptr<DType>();
index_t outer = inputs[0].shape_.ProdShape(0, param.axis[0]);
index_t inner = inputs[0].shape_.ProdShape(param.axis[0], inputs[0].shape_.ndim());
BroadcastAxisKer(src, dst, outer, inner, param.size[0]);
});
} else {
BroadcastComputeImpl<cpu>(attrs, ctx, inputs, req, outputs, inputs[0].shape_);
}
}
MXNET_OPERATOR_REGISTER_BROADCAST(broadcast_axis)
.add_alias("broadcast_axes")
.describe(R"code(Broadcasts the input array over particular axes.
Broadcasting is allowed on axes with size 1, such as from `(2,1,3,1)` to
`(2,8,3,9)`. Elements will be duplicated on the broadcasted axes.
`broadcast_axes` is an alias to the function `broadcast_axis`.
Example::
// given x of shape (1,2,1)
x = [[[ 1.],
[ 2.]]]
// broadcast x on on axis 2
broadcast_axis(x, axis=2, size=3) = [[[ 1., 1., 1.],
[ 2., 2., 2.]]]
// broadcast x on on axes 0 and 2
broadcast_axis(x, axis=(0,2), size=(2,3)) = [[[ 1., 1., 1.],
[ 2., 2., 2.]],
[[ 1., 1., 1.],
[ 2., 2., 2.]]]
)code" ADD_FILELINE)
.set_attr_parser(ParamParser<BroadcastAxesParam>)
.add_arguments(BroadcastAxesParam::__FIELDS__())
.set_attr<mxnet::FInferShape>("FInferShape", BroadcastAxesShape)
.set_attr<FCompute>("FCompute<cpu>", BroadcastAxisComputeCPU);
MXNET_OPERATOR_REGISTER_BROADCAST(broadcast_to)
.describe(R"code(Broadcasts the input array to a new shape.
Broadcasting is a mechanism that allows NDArrays to perform arithmetic operations
with arrays of different shapes efficiently without creating multiple copies of arrays.
Also see, `Broadcasting <https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html>`_ for more explanation.
Broadcasting is allowed on axes with size 1, such as from `(2,1,3,1)` to
`(2,8,3,9)`. Elements will be duplicated on the broadcasted axes.
For example::
broadcast_to([[1,2,3]], shape=(2,3)) = [[ 1., 2., 3.],
[ 1., 2., 3.]])
The dimension which you do not want to change can also be kept as `0` which means copy the original value.
So with `shape=(2,0)`, we will obtain the same result as in the above example.
)code" ADD_FILELINE)
.set_attr_parser(ParamParser<BroadcastToParam>)
.add_arguments(BroadcastToParam::__FIELDS__())
.set_attr<mxnet::FInferShape>("FInferShape", BroadcastToShape)
.set_attr<FCompute>("FCompute<cpu>", BroadcastCompute<cpu>);
// backward op for broadcast.
NNVM_REGISTER_OP(_broadcast_backward)
.set_attr_parser(ParamParser<ReduceAxesParam>)
.set_attr<nnvm::TIsBackward>("TIsBackward", true)
.set_attr<FCompute>("FCompute<cpu>", ReduceAxesCompute<cpu, mshadow::red::sum>)
.set_attr<FResourceRequest>("FResourceRequest",
[](const NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
});
NNVM_REGISTER_OP(broadcast_like)
.set_num_inputs(2)
.set_num_outputs(1)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
return std::vector<std::string>{"lhs", "rhs"};
})
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>)
.set_attr<nnvm::FGradient>("FGradient",
[](const nnvm::ObjectPtr& n,
const std::vector<nnvm::NodeEntry>& ograds) {
if (CheckGradAllZero(ograds))
return MakeZeroGradNodes(n, ograds);
std::vector<nnvm::NodeEntry> lhs = MakeNonlossGradNode("_broadcast_backward", n, ograds, {},
{{"keepdims", "true"}});
lhs.emplace_back(MakeNode("zeros_like", n->attrs.name + "_rhs_backward",
{n->inputs[1]}, nullptr, &n));
return lhs;
})
.add_argument("lhs", "NDArray-or-Symbol", "First input.")
.add_argument("rhs", "NDArray-or-Symbol", "Second input.")
.describe(R"code(Broadcasts lhs to have the same shape as rhs.
Broadcasting is a mechanism that allows NDArrays to perform arithmetic operations
with arrays of different shapes efficiently without creating multiple copies of arrays.
Also see, `Broadcasting <https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html>`_ for more explanation.
Broadcasting is allowed on axes with size 1, such as from `(2,1,3,1)` to
`(2,8,3,9)`. Elements will be duplicated on the broadcasted axes.
For example::
broadcast_like([[1,2,3]], [[5,6,7],[7,8,9]]) = [[ 1., 2., 3.],
[ 1., 2., 3.]])
broadcast_like([9], [1,2,3,4,5], lhs_axes=(0,), rhs_axes=(-1,)) = [9,9,9,9,9]
)code" ADD_FILELINE)
.set_attr_parser(ParamParser<BroadcastLikeParam>)
.add_arguments(BroadcastLikeParam::__FIELDS__())
.set_attr<mxnet::FInferShape>("FInferShape", BroadcastLikeShape)
.set_attr<FCompute>("FCompute<cpu>", BroadcastCompute<cpu>);
} // namespace op
} // namespace mxnet
<commit_msg>add npx.broadcast_like (#17605)<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2016 by Contributors
* \file broadcast_reduce_op_value.cc
* \brief CPU Implementation of broadcast and reduce functions based on value.
*/
#include "./broadcast_reduce_op.h"
namespace mxnet {
namespace op {
DMLC_REGISTER_PARAMETER(ReduceAxesParam);
DMLC_REGISTER_PARAMETER(ReduceAxisParam);
DMLC_REGISTER_PARAMETER(BroadcastAxesParam);
DMLC_REGISTER_PARAMETER(BroadcastToParam);
DMLC_REGISTER_PARAMETER(BroadcastLikeParam);
template<typename DType>
void BroadcastAxisKer(DType* src,
DType* dst,
index_t outer,
index_t inner,
index_t size) {
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (index_t i = 0; i < outer * size; i++) {
const index_t m = i / size;
const index_t n = i % size;
void* offset = reinterpret_cast<void*>(dst + m * size * inner + n * inner);
memcpy(offset, reinterpret_cast<void*>(src + m * inner), inner * sizeof (DType));
}
}
inline void BroadcastAxisComputeCPU(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const BroadcastAxesParam& param = nnvm::get<BroadcastAxesParam>(attrs.parsed);
if (param.axis.ndim() == 1 && inputs[0].shape_[param.axis[0]] == 1 && req[0] == kWriteTo) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
auto dst = outputs[0].dptr<DType>();
auto src = inputs[0].dptr<DType>();
index_t outer = inputs[0].shape_.ProdShape(0, param.axis[0]);
index_t inner = inputs[0].shape_.ProdShape(param.axis[0], inputs[0].shape_.ndim());
BroadcastAxisKer(src, dst, outer, inner, param.size[0]);
});
} else {
BroadcastComputeImpl<cpu>(attrs, ctx, inputs, req, outputs, inputs[0].shape_);
}
}
MXNET_OPERATOR_REGISTER_BROADCAST(broadcast_axis)
.add_alias("broadcast_axes")
.describe(R"code(Broadcasts the input array over particular axes.
Broadcasting is allowed on axes with size 1, such as from `(2,1,3,1)` to
`(2,8,3,9)`. Elements will be duplicated on the broadcasted axes.
`broadcast_axes` is an alias to the function `broadcast_axis`.
Example::
// given x of shape (1,2,1)
x = [[[ 1.],
[ 2.]]]
// broadcast x on on axis 2
broadcast_axis(x, axis=2, size=3) = [[[ 1., 1., 1.],
[ 2., 2., 2.]]]
// broadcast x on on axes 0 and 2
broadcast_axis(x, axis=(0,2), size=(2,3)) = [[[ 1., 1., 1.],
[ 2., 2., 2.]],
[[ 1., 1., 1.],
[ 2., 2., 2.]]]
)code" ADD_FILELINE)
.set_attr_parser(ParamParser<BroadcastAxesParam>)
.add_arguments(BroadcastAxesParam::__FIELDS__())
.set_attr<mxnet::FInferShape>("FInferShape", BroadcastAxesShape)
.set_attr<FCompute>("FCompute<cpu>", BroadcastAxisComputeCPU);
MXNET_OPERATOR_REGISTER_BROADCAST(broadcast_to)
.describe(R"code(Broadcasts the input array to a new shape.
Broadcasting is a mechanism that allows NDArrays to perform arithmetic operations
with arrays of different shapes efficiently without creating multiple copies of arrays.
Also see, `Broadcasting <https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html>`_ for more explanation.
Broadcasting is allowed on axes with size 1, such as from `(2,1,3,1)` to
`(2,8,3,9)`. Elements will be duplicated on the broadcasted axes.
For example::
broadcast_to([[1,2,3]], shape=(2,3)) = [[ 1., 2., 3.],
[ 1., 2., 3.]])
The dimension which you do not want to change can also be kept as `0` which means copy the original value.
So with `shape=(2,0)`, we will obtain the same result as in the above example.
)code" ADD_FILELINE)
.set_attr_parser(ParamParser<BroadcastToParam>)
.add_arguments(BroadcastToParam::__FIELDS__())
.set_attr<mxnet::FInferShape>("FInferShape", BroadcastToShape)
.set_attr<FCompute>("FCompute<cpu>", BroadcastCompute<cpu>);
// backward op for broadcast.
NNVM_REGISTER_OP(_broadcast_backward)
.set_attr_parser(ParamParser<ReduceAxesParam>)
.set_attr<nnvm::TIsBackward>("TIsBackward", true)
.set_attr<FCompute>("FCompute<cpu>", ReduceAxesCompute<cpu, mshadow::red::sum>)
.set_attr<FResourceRequest>("FResourceRequest",
[](const NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
});
NNVM_REGISTER_OP(broadcast_like)
.add_alias("_npx_broadcast_like")
.set_num_inputs(2)
.set_num_outputs(1)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
return std::vector<std::string>{"lhs", "rhs"};
})
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>)
.set_attr<nnvm::FGradient>("FGradient",
[](const nnvm::ObjectPtr& n,
const std::vector<nnvm::NodeEntry>& ograds) {
if (CheckGradAllZero(ograds))
return MakeZeroGradNodes(n, ograds);
std::vector<nnvm::NodeEntry> lhs = MakeNonlossGradNode("_broadcast_backward", n, ograds, {},
{{"keepdims", "true"}});
lhs.emplace_back(MakeNode("zeros_like", n->attrs.name + "_rhs_backward",
{n->inputs[1]}, nullptr, &n));
return lhs;
})
.add_argument("lhs", "NDArray-or-Symbol", "First input.")
.add_argument("rhs", "NDArray-or-Symbol", "Second input.")
.describe(R"code(Broadcasts lhs to have the same shape as rhs.
Broadcasting is a mechanism that allows NDArrays to perform arithmetic operations
with arrays of different shapes efficiently without creating multiple copies of arrays.
Also see, `Broadcasting <https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html>`_ for more explanation.
Broadcasting is allowed on axes with size 1, such as from `(2,1,3,1)` to
`(2,8,3,9)`. Elements will be duplicated on the broadcasted axes.
For example::
broadcast_like([[1,2,3]], [[5,6,7],[7,8,9]]) = [[ 1., 2., 3.],
[ 1., 2., 3.]])
broadcast_like([9], [1,2,3,4,5], lhs_axes=(0,), rhs_axes=(-1,)) = [9,9,9,9,9]
)code" ADD_FILELINE)
.set_attr_parser(ParamParser<BroadcastLikeParam>)
.add_arguments(BroadcastLikeParam::__FIELDS__())
.set_attr<mxnet::FInferShape>("FInferShape", BroadcastLikeShape)
.set_attr<FCompute>("FCompute<cpu>", BroadcastCompute<cpu>);
} // namespace op
} // namespace mxnet
<|endoftext|>
|
<commit_before>#pragma once
#include <bitset>
#include <cstring>
#include <iostream>
namespace bitwise {
using std::cout;
using std::ostream;
template <typename A>
class binary final {
template <typename B>
using conref = const B&;
constexpr static size_t sz{sizeof(A)};
constexpr static size_t szB{sz << 3};
using bitA = std::bitset<szB>;
using byte = unsigned char;
using bit = bool;
public:
explicit binary(void) = delete;
explicit binary(conref<A> a) noexcept {
byte* ptr = new byte[sz];
memcpy((void *) ptr, (const void* const) &a, sz);
for (size_t i = 0; i < sz; ++i) {
static byte ch;
ch = ptr[i];
for (size_t j = 0; j < 8; ++j) {
static bool bitVal;
bitVal = binary<A>::getBitFromByte(ch, j);
this->bits[binary<A>::getBitIdx(i, j)] = bitVal;
}
}
delete [] ptr;
}
explicit binary(A&& a) noexcept : binary(a) {}
template <typename... B>
explicit binary(B... b) = delete;
inline ~binary(void) noexcept{
bits.~bitA();
}
inline void print(void) const noexcept {
binary<A>::print(std::cout, *this);
}
inline bool getBit(conref<size_t> idx) const noexcept {
return bits[idx];
}
inline bool getBit(conref<byte> byteIdx, conref<byte> bitIdx) const noexcept {
return binary<A>::getBit(*this, byteIdx, bitIdx);
}
template <typename B>
friend inline ostream& operator<<(ostream& os, conref<binary<B>> a) noexcept {
a.print();
return os;
}
template <typename B>
friend inline ostream& operator<<(ostream& os, binary<B>&& a) noexcept {
a.print();
return os;
}
private:
static inline void print(std::ostream& os, conref<binary<A>> a) noexcept {
constexpr static size_t szOneLess{sz - 1};
for (size_t i = 0; i < sz; ++i) {
for (size_t j = 0; j < 8; ++j) {
static bit bitIdx;
bitIdx = (bit) a.bits[getBitIdx(i, j)];
os << bitIdx;
}
if (szOneLess != i) {
os << ' ';
}
}
}
static inline bit getBitFromByte(conref<byte> data, conref<byte> bitIdx) noexcept {
return data & (1 << bitIdx);
}
static inline size_t getBitIdx(conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept {
return (byteIdx << 3) + bitIdx;
}
static inline bit getBit(conref<binary<A>> bits, conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept {
return bits[getBitIdx(byteIdx, bitIdx)];
}
bitA bits;
};
}<commit_msg>attempt at being type safe - fail when using something other than size_t<commit_after>#pragma once
#include <bitset>
#include <cstring>
#include <iostream>
namespace bitwise {
using std::cout;
using std::ostream;
template <typename A>
class binary final {
template <typename B>
using conref = const B&;
constexpr static size_t sz{sizeof(A)};
constexpr static size_t szB{sz << 3};
using bitA = std::bitset<szB>;
using byte = unsigned char;
using bit = bool;
public:
explicit binary(void) = delete;
explicit binary(conref<A> a) noexcept {
byte* ptr = new byte[sz];
memcpy((void *) ptr, (const void* const) &a, sz);
for (size_t i = 0; i < sz; ++i) {
static byte ch;
ch = ptr[i];
for (size_t j = 0; j < 8; ++j) {
static bool bitVal;
bitVal = binary<A>::getBitFromByte(ch, j);
this->bits[binary<A>::getBitIdx(i, j)] = bitVal;
}
}
delete [] ptr;
}
explicit binary(A&& a) noexcept : binary(a) {}
template <typename... B>
explicit binary(B... b) = delete;
inline ~binary(void) noexcept{
bits.~bitA();
}
inline void print(void) const noexcept {
binary<A>::print(std::cout, *this);
}
inline bool getBit(conref<size_t> idx) const noexcept {
return bits[idx];
}
inline bool getBit(conref<byte> byteIdx, conref<byte> bitIdx) const noexcept {
return binary<A>::getBit(*this, byteIdx, bitIdx);
}
template <typename... B>
inline bool getBit(B... b) const noexcept = delete;
template <typename B>
friend inline ostream& operator<<(ostream& os, conref<binary<B>> a) noexcept {
a.print();
return os;
}
template <typename B>
friend inline ostream& operator<<(ostream& os, binary<B>&& a) noexcept {
a.print();
return os;
}
private:
static inline void print(std::ostream& os, conref<binary<A>> a) noexcept {
constexpr static size_t szOneLess{sz - 1};
for (size_t i = 0; i < sz; ++i) {
for (size_t j = 0; j < 8; ++j) {
static bit bitIdx;
bitIdx = (bit) a.bits[getBitIdx(i, j)];
os << bitIdx;
}
if (szOneLess != i) {
os << ' ';
}
}
}
static inline bit getBitFromByte(conref<byte> data, conref<byte> bitIdx) noexcept {
return data & (1 << bitIdx);
}
static inline size_t getBitIdx(conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept {
return (byteIdx << 3) + bitIdx;
}
static inline bit getBit(conref<binary<A>> bits, conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept {
return bits[getBitIdx(byteIdx, bitIdx)];
}
bitA bits;
};
}<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.