text
stringlengths 54
60.6k
|
|---|
<commit_before>//Implementation of a Forest Fire Simulation
#ifndef FOREST_HPP_DEFINED
#define FOREST_HPP_DEFINED
#include <string>
#include <vector>
#include <memory>
#include <random>
#include "warped.hpp"
WARPED_DEFINE_LP_STATE_STRUCT(ForestState) {
enum burning_status_{
UNBURNT,
GROWTH,
DECAY,
BURNT_OUT
};
unsigned int heat_content_;
};
enum forest_event_t {
RADIATION_IN,
RADIATION_OUT,
IGNITION,
PEAK
};
enum direction_t { //The direction of the spread of fire from the currently burning LP
NORTH,
NORTH_WEST,
NORTH_EAST,
SOUTH,
SOUTH_WEST,
SOUTH_EAST,
EAST,
WEST,
};
class ForestEvent : public warped::Event { //Class Definition of a forest fire event
public:
ForestEvent() = default;
ForestEvent(const std::string& receiver_name, const forest_event_t type,
const unsigned int timestamp)
: receiver_name_(receiver_name), type_(type), ts_(timestamp) {} //Initializing Class Components
const std::string& receiverName() const { return receiver_name_; }
unsigned int timestamp() const { return ts_; }
std::string receiver_name_;
forest_event_t type_;
unsigned int ts_;
WARPED_REGISTER_SERIALIZABLE_MEMBERS(cereal::base_class<warped::Event>(this), receiver_name_, type_, ts_)
};
class Forest : public warped::LogicalProcess{
public:
Forest( const std::string& name,
const unsigned int size_x,
const unsigned int size_y,
const unsigned int ignition_threshold,
const unsigned int heat_rate,
const unsigned int peak_threshold,
const unsigned int radiation_percent,
const unsigned int burnout_threshold,
const unsigned int index)
: LogicalProcess(name),
state_(),
rng_(new std::default_random_engine(index)),
size_x_(size_x),
size_y_(size_y),
ignition_threshold_(ignition_threshold),
peak_threshold_(peak_threshold),
radiation_percent_(radiation_percent),
burnout_threshold_(burnout_threshold),
index_(index){
state_.burning_status_ = UNBURNT;
heat_content_ = 0;
}
virtual std::vector<std::shared_ptr<warped::Event> > initializeLP() override;
virtual std::vector<std::shared_ptr<warped::Event> > receiveEvent(const warped::Event&);
virtual warped::LPState& getState() { return this->state_; }
ForestState state_;
static inline std::string lp_name(const unsigned int);
protected:
std::shared_ptr<std::default_random_engine> rng_;
const unsigned int size_x_; //the x coordinate of the LP on the picture
const unsigned int size_y_; //the y coordinate of the LP on the picture
const unsigned int ignition_threshold_; // threshold of heat that the LP needs to ignite
const unsigned int peak_threshold_; //threshold of heat reached by the fire before it stops growing
const unsigned int radiation_percent_; //Percent of heat radiation released at each event
const unsigned int burnout_threshold_; //Threshold of Heat that the lp needs to reach to burn out
const unsigned int index_; //The identifier used by the model to distinguish between LPs
std::string compute_move(direction_t direction);
}
#endif
<commit_msg>Changed compute_move to compute_spread<commit_after>//Implementation of a Forest Fire Simulation
#ifndef FOREST_HPP_DEFINED
#define FOREST_HPP_DEFINED
#include <string>
#include <vector>
#include <memory>
#include <random>
#include "warped.hpp"
WARPED_DEFINE_LP_STATE_STRUCT(ForestState) {
enum burning_status_{
UNBURNT,
GROWTH,
DECAY,
BURNT_OUT
};
unsigned int heat_content_;
};
enum forest_event_t {
RADIATION_IN,
RADIATION_OUT,
IGNITION,
PEAK
};
enum direction_t { //The direction of the spread of fire from the currently burning LP
NORTH,
NORTH_WEST,
NORTH_EAST,
SOUTH,
SOUTH_WEST,
SOUTH_EAST,
EAST,
WEST,
};
class ForestEvent : public warped::Event { //Class Definition of a forest fire event
public:
ForestEvent() = default;
ForestEvent(const std::string& receiver_name, const forest_event_t type,
const unsigned int timestamp)
: receiver_name_(receiver_name), type_(type), ts_(timestamp) {} //Initializing Class Components
const std::string& receiverName() const { return receiver_name_; }
unsigned int timestamp() const { return ts_; }
std::string receiver_name_;
forest_event_t type_;
unsigned int ts_;
WARPED_REGISTER_SERIALIZABLE_MEMBERS(cereal::base_class<warped::Event>(this), receiver_name_, type_, ts_)
};
class Forest : public warped::LogicalProcess{
public:
Forest( const std::string& name,
const unsigned int size_x,
const unsigned int size_y,
const unsigned int ignition_threshold,
const unsigned int heat_rate,
const unsigned int peak_threshold,
const unsigned int radiation_percent,
const unsigned int burnout_threshold,
const unsigned int index)
: LogicalProcess(name),
state_(),
rng_(new std::default_random_engine(index)),
size_x_(size_x),
size_y_(size_y),
ignition_threshold_(ignition_threshold),
peak_threshold_(peak_threshold),
radiation_percent_(radiation_percent),
burnout_threshold_(burnout_threshold),
index_(index){
state_.burning_status_ = UNBURNT;
heat_content_ = 0;
}
virtual std::vector<std::shared_ptr<warped::Event> > initializeLP() override;
virtual std::vector<std::shared_ptr<warped::Event> > receiveEvent(const warped::Event&);
virtual warped::LPState& getState() { return this->state_; }
ForestState state_;
static inline std::string lp_name(const unsigned int);
protected:
std::shared_ptr<std::default_random_engine> rng_;
const unsigned int size_x_; //the x coordinate of the LP on the picture
const unsigned int size_y_; //the y coordinate of the LP on the picture
const unsigned int ignition_threshold_; // threshold of heat that the LP needs to ignite
const unsigned int peak_threshold_; //threshold of heat reached by the fire before it stops growing
const unsigned int radiation_percent_; //Percent of heat radiation released at each event
const unsigned int burnout_threshold_; //Threshold of Heat that the lp needs to reach to burn out
const unsigned int index_; //The identifier used by the model to distinguish between LPs
std::string compute_spread(); //Function to Spread the heat to adjacent cells
}
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
#include <thread>
#include <sstream>
#include <franka/gripper.h>
#include <franka/gripper_state.h>
int main(int argc, char** argv) {
if (argc != 4) {
std::cerr << "Usage: ./grasp_object <gripper-hostname> <homing> <object-width>" << std::endl;
return -1;
}
try {
franka::Gripper gripper(argv[1]);
double grasping_width = atof(argv[3]);
std::stringstream ss(argv[2]);
bool homing;
if(!(ss >> homing)) {
std::cerr << "<homing> can be 0 or 1." << std::endl;
return -1;
}
if(homing) {
// Do a homing in order to estimate the maximum grasping width with the current fingers.
gripper.homing();
}
// Check for the maximum grasping width.
franka::GripperState gripper_state = gripper.readOnce();
if (gripper_state.max_opening_width < grasping_width) {
std::cout << "Object is too large for the current fingers on the gripper." << std::endl;
return -1;
}
// Grasp the object.
if (!gripper.grasp(grasping_width, 0.1, 300)) {
std::cout << "Failed to grasp object." << std::endl;
return -1;
}
// Wait 2s and check afterwards, if the object is still grasped.
std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(3000));
gripper_state = gripper.readOnce();
if (!gripper_state.object_grasped) {
std::cout << "Object lost." << std::endl;
return -1;
}
std::cout << "Grasped object, will release it now." << std::endl;
gripper.stop();
} catch (franka::Exception const& e) {
std::cout << e.what() << std::endl;
return -1;
}
return 0;
}
<commit_msg>Clang format.<commit_after>#include <iostream>
#include <sstream>
#include <thread>
#include <franka/gripper.h>
#include <franka/gripper_state.h>
int main(int argc, char** argv) {
if (argc != 4) {
std::cerr << "Usage: ./grasp_object <gripper-hostname> <homing> <object-width>" << std::endl;
return -1;
}
try {
franka::Gripper gripper(argv[1]);
double grasping_width = atof(argv[3]);
std::stringstream ss(argv[2]);
bool homing;
if (!(ss >> homing)) {
std::cerr << "<homing> can be 0 or 1." << std::endl;
return -1;
}
if (homing) {
// Do a homing in order to estimate the maximum grasping width with the current fingers.
gripper.homing();
}
// Check for the maximum grasping width.
franka::GripperState gripper_state = gripper.readOnce();
if (gripper_state.max_opening_width < grasping_width) {
std::cout << "Object is too large for the current fingers on the gripper." << std::endl;
return -1;
}
// Grasp the object.
if (!gripper.grasp(grasping_width, 0.1, 300)) {
std::cout << "Failed to grasp object." << std::endl;
return -1;
}
// Wait 2s and check afterwards, if the object is still grasped.
std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(3000));
gripper_state = gripper.readOnce();
if (!gripper_state.object_grasped) {
std::cout << "Object lost." << std::endl;
return -1;
}
std::cout << "Grasped object, will release it now." << std::endl;
gripper.stop();
} catch (franka::Exception const& e) {
std::cout << e.what() << std::endl;
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/v8/V8PerContextData.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8ObjectConstructor.h"
#include "wtf/StringExtras.h"
#include <stdlib.h>
namespace WebCore {
template<typename Map>
static void disposeMapWithUnsafePersistentValues(Map* map)
{
typename Map::iterator it = map->begin();
for (; it != map->end(); ++it)
it->value.dispose();
map->clear();
}
class V8PerContextDataHolder {
WTF_MAKE_NONCOPYABLE(V8PerContextDataHolder);
public:
static void install(v8::Handle<v8::Context> context, PassRefPtr<DOMWrapperWorld> world)
{
new V8PerContextDataHolder(context, world);
}
static V8PerContextDataHolder* from(v8::Handle<v8::Context> context)
{
V8PerContextDataHolder* holder = static_cast<V8PerContextDataHolder*>(context->GetAlignedPointerFromEmbedderData(v8ContextPerContextDataIndex));
// |holder| must not be 0 because V8PerContextDataHolder is kept alive as long as the |context| is alive.
// Here we have a handle to the |context|, which means that the V8PerContextDataHolder is alive.
ASSERT(holder);
return holder;
}
V8PerContextData* perContextData() const { return m_perContextData; }
void setPerContextData(V8PerContextData* data) { m_perContextData = data; }
DOMWrapperWorld* world() const { return m_world.get(); }
private:
V8PerContextDataHolder(v8::Handle<v8::Context> context, PassRefPtr<DOMWrapperWorld> world)
: m_context(v8::Isolate::GetCurrent(), context)
, m_perContextData(0)
, m_world(world)
{
m_context.setWeak(this, &V8PerContextDataHolder::weakCallback);
context->SetAlignedPointerInEmbedderData(v8ContextPerContextDataIndex, this);
}
~V8PerContextDataHolder() { }
static void weakCallback(const v8::WeakCallbackData<v8::Context, V8PerContextDataHolder>& data)
{
data.GetValue()->SetAlignedPointerInEmbedderData(v8ContextPerContextDataIndex, 0);
delete data.GetParameter();
}
ScopedPersistent<v8::Context> m_context;
V8PerContextData* m_perContextData;
RefPtr<DOMWrapperWorld> m_world;
};
V8PerContextData::V8PerContextData(v8::Handle<v8::Context> context, PassRefPtr<DOMWrapperWorld> world)
: m_activityLogger(0)
, m_isolate(context->GetIsolate())
, m_contextHolder(adoptPtr(new gin::ContextHolder(context->GetIsolate())))
, m_context(m_isolate, context)
, m_customElementBindings(adoptPtr(new CustomElementBindingMap()))
{
m_contextHolder->SetContext(context);
V8PerContextDataHolder::install(context, world);
V8PerContextDataHolder::from(context)->setPerContextData(this);
v8::Context::Scope contextScope(context);
ASSERT(m_errorPrototype.isEmpty());
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(context->Global()->Get(v8AtomicString(m_isolate, "Error")));
ASSERT(!object.IsEmpty());
v8::Handle<v8::Value> prototypeValue = object->Get(v8AtomicString(m_isolate, "prototype"));
ASSERT(!prototypeValue.IsEmpty());
m_errorPrototype.set(m_isolate, prototypeValue);
}
V8PerContextData::~V8PerContextData()
{
v8::HandleScope handleScope(m_isolate);
V8PerContextDataHolder::from(m_context.newLocal(m_isolate))->setPerContextData(0);
disposeMapWithUnsafePersistentValues(&m_wrapperBoilerplates);
disposeMapWithUnsafePersistentValues(&m_constructorMap);
}
V8PerContextData* V8PerContextData::from(v8::Handle<v8::Context> context)
{
return V8PerContextDataHolder::from(context)->perContextData();
}
DOMWrapperWorld* V8PerContextData::world(v8::Handle<v8::Context> context)
{
DOMWrapperWorld* world = V8PerContextDataHolder::from(context)->world();
ASSERT(world);
return world;
}
v8::Local<v8::Object> V8PerContextData::createWrapperFromCacheSlowCase(const WrapperTypeInfo* type)
{
ASSERT(!m_errorPrototype.isEmpty());
v8::Context::Scope scope(context());
v8::Local<v8::Function> function = constructorForType(type);
v8::Local<v8::Object> instanceTemplate = V8ObjectConstructor::newInstance(function);
if (!instanceTemplate.IsEmpty()) {
m_wrapperBoilerplates.set(type, UnsafePersistent<v8::Object>(m_isolate, instanceTemplate));
return instanceTemplate->Clone();
}
return v8::Local<v8::Object>();
}
v8::Local<v8::Function> V8PerContextData::constructorForTypeSlowCase(const WrapperTypeInfo* type)
{
ASSERT(!m_errorPrototype.isEmpty());
v8::Context::Scope scope(context());
v8::Handle<v8::FunctionTemplate> functionTemplate = type->domTemplate(m_isolate);
// Getting the function might fail if we're running out of stack or memory.
v8::TryCatch tryCatch;
v8::Local<v8::Function> function = functionTemplate->GetFunction();
if (function.IsEmpty())
return v8::Local<v8::Function>();
if (type->parentClass) {
v8::Local<v8::Object> prototypeTemplate = constructorForType(type->parentClass);
if (prototypeTemplate.IsEmpty())
return v8::Local<v8::Function>();
function->SetPrototype(prototypeTemplate);
}
v8::Local<v8::Value> prototypeValue = function->Get(v8AtomicString(m_isolate, "prototype"));
if (!prototypeValue.IsEmpty() && prototypeValue->IsObject()) {
v8::Local<v8::Object> prototypeObject = v8::Local<v8::Object>::Cast(prototypeValue);
if (prototypeObject->InternalFieldCount() == v8PrototypeInternalFieldcount
&& type->wrapperTypePrototype == WrapperTypeObjectPrototype)
prototypeObject->SetAlignedPointerInInternalField(v8PrototypeTypeIndex, const_cast<WrapperTypeInfo*>(type));
type->installPerContextEnabledMethods(prototypeObject, m_isolate);
if (type->wrapperTypePrototype == WrapperTypeExceptionPrototype)
prototypeObject->SetPrototype(m_errorPrototype.newLocal(m_isolate));
}
m_constructorMap.set(type, UnsafePersistent<v8::Function>(m_isolate, function));
return function;
}
v8::Local<v8::Object> V8PerContextData::prototypeForType(const WrapperTypeInfo* type)
{
v8::Local<v8::Object> constructor = constructorForType(type);
if (constructor.IsEmpty())
return v8::Local<v8::Object>();
return constructor->Get(v8String(m_isolate, "prototype")).As<v8::Object>();
}
void V8PerContextData::addCustomElementBinding(CustomElementDefinition* definition, PassOwnPtr<CustomElementBinding> binding)
{
ASSERT(!m_customElementBindings->contains(definition));
m_customElementBindings->add(definition, binding);
}
void V8PerContextData::clearCustomElementBinding(CustomElementDefinition* definition)
{
CustomElementBindingMap::iterator it = m_customElementBindings->find(definition);
ASSERT_WITH_SECURITY_IMPLICATION(it != m_customElementBindings->end());
m_customElementBindings->remove(it);
}
CustomElementBinding* V8PerContextData::customElementBinding(CustomElementDefinition* definition)
{
CustomElementBindingMap::const_iterator it = m_customElementBindings->find(definition);
ASSERT_WITH_SECURITY_IMPLICATION(it != m_customElementBindings->end());
return it->value.get();
}
static v8::Handle<v8::Value> createDebugData(const char* worldName, int debugId, v8::Isolate* isolate)
{
char buffer[32];
unsigned wanted;
if (debugId == -1)
wanted = snprintf(buffer, sizeof(buffer), "%s", worldName);
else
wanted = snprintf(buffer, sizeof(buffer), "%s,%d", worldName, debugId);
if (wanted < sizeof(buffer))
return v8AtomicString(isolate, buffer);
return v8::Undefined(isolate);
}
static v8::Handle<v8::Value> debugData(v8::Handle<v8::Context> context)
{
v8::Context::Scope contextScope(context);
return context->GetEmbedderData(v8ContextDebugIdIndex);
}
static void setDebugData(v8::Handle<v8::Context> context, v8::Handle<v8::Value> value)
{
v8::Context::Scope contextScope(context);
context->SetEmbedderData(v8ContextDebugIdIndex, value);
}
bool V8PerContextDebugData::setContextDebugData(v8::Handle<v8::Context> context, const char* worldName, int debugId)
{
if (!debugData(context)->IsUndefined())
return false;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::Value> debugData = createDebugData(worldName, debugId, context->GetIsolate());
setDebugData(context, debugData);
return true;
}
int V8PerContextDebugData::contextDebugId(v8::Handle<v8::Context> context)
{
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::Value> data = debugData(context);
if (!data->IsString())
return -1;
v8::String::Utf8Value utf8(data);
char* comma = strnstr(*utf8, ",", utf8.length());
if (!comma)
return -1;
return atoi(comma + 1);
}
} // namespace WebCore
<commit_msg>Add security checks to verify that V8PerContextData is not accessed from a wrong context<commit_after>/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/v8/V8PerContextData.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8ObjectConstructor.h"
#include "wtf/StringExtras.h"
#include <stdlib.h>
namespace WebCore {
template<typename Map>
static void disposeMapWithUnsafePersistentValues(Map* map)
{
typename Map::iterator it = map->begin();
for (; it != map->end(); ++it)
it->value.dispose();
map->clear();
}
class V8PerContextDataHolder {
WTF_MAKE_NONCOPYABLE(V8PerContextDataHolder);
public:
static void install(v8::Handle<v8::Context> context, PassRefPtr<DOMWrapperWorld> world)
{
new V8PerContextDataHolder(context, world);
}
static V8PerContextDataHolder* from(v8::Handle<v8::Context> context)
{
V8PerContextDataHolder* holder = static_cast<V8PerContextDataHolder*>(context->GetAlignedPointerFromEmbedderData(v8ContextPerContextDataIndex));
// V8PerContextDataHolder::from() must not be called for a context that does not have
// valid embedder data in the embedder field.
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(holder);
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(holder->context() == context);
return holder;
}
V8PerContextData* perContextData() const { return m_perContextData; }
void setPerContextData(V8PerContextData* data) { m_perContextData = data; }
DOMWrapperWorld* world() const { return m_world.get(); }
v8::Handle<v8::Context> context() const { return m_context.newLocal(m_isolate); }
private:
V8PerContextDataHolder(v8::Handle<v8::Context> context, PassRefPtr<DOMWrapperWorld> world)
: m_isolate(context->GetIsolate())
, m_context(m_isolate, context)
, m_perContextData(0)
, m_world(world)
{
m_context.setWeak(this, &V8PerContextDataHolder::weakCallback);
context->SetAlignedPointerInEmbedderData(v8ContextPerContextDataIndex, this);
}
~V8PerContextDataHolder() { }
static void weakCallback(const v8::WeakCallbackData<v8::Context, V8PerContextDataHolder>& data)
{
data.GetValue()->SetAlignedPointerInEmbedderData(v8ContextPerContextDataIndex, 0);
delete data.GetParameter();
}
v8::Isolate* m_isolate;
ScopedPersistent<v8::Context> m_context;
V8PerContextData* m_perContextData;
RefPtr<DOMWrapperWorld> m_world;
};
V8PerContextData::V8PerContextData(v8::Handle<v8::Context> context, PassRefPtr<DOMWrapperWorld> world)
: m_activityLogger(0)
, m_isolate(context->GetIsolate())
, m_contextHolder(adoptPtr(new gin::ContextHolder(context->GetIsolate())))
, m_context(m_isolate, context)
, m_customElementBindings(adoptPtr(new CustomElementBindingMap()))
{
m_contextHolder->SetContext(context);
V8PerContextDataHolder::install(context, world);
V8PerContextDataHolder::from(context)->setPerContextData(this);
v8::Context::Scope contextScope(context);
ASSERT(m_errorPrototype.isEmpty());
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(context->Global()->Get(v8AtomicString(m_isolate, "Error")));
ASSERT(!object.IsEmpty());
v8::Handle<v8::Value> prototypeValue = object->Get(v8AtomicString(m_isolate, "prototype"));
ASSERT(!prototypeValue.IsEmpty());
m_errorPrototype.set(m_isolate, prototypeValue);
}
V8PerContextData::~V8PerContextData()
{
v8::HandleScope handleScope(m_isolate);
V8PerContextDataHolder::from(m_context.newLocal(m_isolate))->setPerContextData(0);
disposeMapWithUnsafePersistentValues(&m_wrapperBoilerplates);
disposeMapWithUnsafePersistentValues(&m_constructorMap);
}
V8PerContextData* V8PerContextData::from(v8::Handle<v8::Context> context)
{
return V8PerContextDataHolder::from(context)->perContextData();
}
DOMWrapperWorld* V8PerContextData::world(v8::Handle<v8::Context> context)
{
DOMWrapperWorld* world = V8PerContextDataHolder::from(context)->world();
ASSERT(world);
return world;
}
v8::Local<v8::Object> V8PerContextData::createWrapperFromCacheSlowCase(const WrapperTypeInfo* type)
{
ASSERT(!m_errorPrototype.isEmpty());
v8::Context::Scope scope(context());
v8::Local<v8::Function> function = constructorForType(type);
v8::Local<v8::Object> instanceTemplate = V8ObjectConstructor::newInstance(function);
if (!instanceTemplate.IsEmpty()) {
m_wrapperBoilerplates.set(type, UnsafePersistent<v8::Object>(m_isolate, instanceTemplate));
return instanceTemplate->Clone();
}
return v8::Local<v8::Object>();
}
v8::Local<v8::Function> V8PerContextData::constructorForTypeSlowCase(const WrapperTypeInfo* type)
{
ASSERT(!m_errorPrototype.isEmpty());
v8::Context::Scope scope(context());
v8::Handle<v8::FunctionTemplate> functionTemplate = type->domTemplate(m_isolate);
// Getting the function might fail if we're running out of stack or memory.
v8::TryCatch tryCatch;
v8::Local<v8::Function> function = functionTemplate->GetFunction();
if (function.IsEmpty())
return v8::Local<v8::Function>();
if (type->parentClass) {
v8::Local<v8::Object> prototypeTemplate = constructorForType(type->parentClass);
if (prototypeTemplate.IsEmpty())
return v8::Local<v8::Function>();
function->SetPrototype(prototypeTemplate);
}
v8::Local<v8::Value> prototypeValue = function->Get(v8AtomicString(m_isolate, "prototype"));
if (!prototypeValue.IsEmpty() && prototypeValue->IsObject()) {
v8::Local<v8::Object> prototypeObject = v8::Local<v8::Object>::Cast(prototypeValue);
if (prototypeObject->InternalFieldCount() == v8PrototypeInternalFieldcount
&& type->wrapperTypePrototype == WrapperTypeObjectPrototype)
prototypeObject->SetAlignedPointerInInternalField(v8PrototypeTypeIndex, const_cast<WrapperTypeInfo*>(type));
type->installPerContextEnabledMethods(prototypeObject, m_isolate);
if (type->wrapperTypePrototype == WrapperTypeExceptionPrototype)
prototypeObject->SetPrototype(m_errorPrototype.newLocal(m_isolate));
}
m_constructorMap.set(type, UnsafePersistent<v8::Function>(m_isolate, function));
return function;
}
v8::Local<v8::Object> V8PerContextData::prototypeForType(const WrapperTypeInfo* type)
{
v8::Local<v8::Object> constructor = constructorForType(type);
if (constructor.IsEmpty())
return v8::Local<v8::Object>();
return constructor->Get(v8String(m_isolate, "prototype")).As<v8::Object>();
}
void V8PerContextData::addCustomElementBinding(CustomElementDefinition* definition, PassOwnPtr<CustomElementBinding> binding)
{
ASSERT(!m_customElementBindings->contains(definition));
m_customElementBindings->add(definition, binding);
}
void V8PerContextData::clearCustomElementBinding(CustomElementDefinition* definition)
{
CustomElementBindingMap::iterator it = m_customElementBindings->find(definition);
ASSERT_WITH_SECURITY_IMPLICATION(it != m_customElementBindings->end());
m_customElementBindings->remove(it);
}
CustomElementBinding* V8PerContextData::customElementBinding(CustomElementDefinition* definition)
{
CustomElementBindingMap::const_iterator it = m_customElementBindings->find(definition);
ASSERT_WITH_SECURITY_IMPLICATION(it != m_customElementBindings->end());
return it->value.get();
}
static v8::Handle<v8::Value> createDebugData(const char* worldName, int debugId, v8::Isolate* isolate)
{
char buffer[32];
unsigned wanted;
if (debugId == -1)
wanted = snprintf(buffer, sizeof(buffer), "%s", worldName);
else
wanted = snprintf(buffer, sizeof(buffer), "%s,%d", worldName, debugId);
if (wanted < sizeof(buffer))
return v8AtomicString(isolate, buffer);
return v8::Undefined(isolate);
}
static v8::Handle<v8::Value> debugData(v8::Handle<v8::Context> context)
{
v8::Context::Scope contextScope(context);
return context->GetEmbedderData(v8ContextDebugIdIndex);
}
static void setDebugData(v8::Handle<v8::Context> context, v8::Handle<v8::Value> value)
{
v8::Context::Scope contextScope(context);
context->SetEmbedderData(v8ContextDebugIdIndex, value);
}
bool V8PerContextDebugData::setContextDebugData(v8::Handle<v8::Context> context, const char* worldName, int debugId)
{
if (!debugData(context)->IsUndefined())
return false;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::Value> debugData = createDebugData(worldName, debugId, context->GetIsolate());
setDebugData(context, debugData);
return true;
}
int V8PerContextDebugData::contextDebugId(v8::Handle<v8::Context> context)
{
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::Value> data = debugData(context);
if (!data->IsString())
return -1;
v8::String::Utf8Value utf8(data);
char* comma = strnstr(*utf8, ",", utf8.length());
if (!comma)
return -1;
return atoi(comma + 1);
}
} // namespace WebCore
<|endoftext|>
|
<commit_before>#include "HM3Pointers.h"
HM3Pointers::HM3Pointers(HM3Version version)
{
Setup(version);
}
HM3Pointers::~HM3Pointers()
{
}
void HM3Pointers::Setup(HM3Version version)
{
uint8_t** difficultyPtr = nullptr;
uint8_t** timePtr = nullptr;
switch (version)
{
case HM3_GOG:
m_Stats = (HM3Stats*)0x009B3B38;
difficultyPtr = (uint8_t**)0x0082083C;
timePtr = (uint8_t**)0x00820820;
break;
case HM3_STEAM:
m_Stats = (HM3Stats*)0x009B2538;
difficultyPtr = (uint8_t**)0x0081F83C;
timePtr = (uint8_t**)0x0081F820;
break;
case HM3_UNKNOWN:
m_Stats = nullptr;
break;
}
m_Difficulty = difficultyPtr != nullptr ? *difficultyPtr + 0x6664 : nullptr;
m_Time = timePtr != nullptr ? *timePtr + 0x48 : nullptr;
}<commit_msg>Improve structure of encoding different version addresses<commit_after>#include "HM3Pointers.h"
struct DataAddresses
{
uint32_t Stats;
uint32_t DifficultyPtr;
uint32_t TimePtr;
};
static const DataAddresses DataVersions[]
{
{ 0x00000000, 0x00000000, 0x00000000 }, // Unknown version
{ 0x009B2538, 0x0081F83C, 0x0081F820 }, // Steam
{ 0x009B3B38, 0x0082083C, 0x00820820 } // GOG
};
HM3Pointers::HM3Pointers(HM3Version version)
{
Setup(version);
}
HM3Pointers::~HM3Pointers()
{
}
void HM3Pointers::Setup(HM3Version version)
{
const DataAddresses& addresses(DataVersions[version]);
m_Stats = (HM3Stats*)addresses.Stats;
uint8_t** difficultyPtr = (uint8_t**)addresses.DifficultyPtr;
uint8_t** timePtr = (uint8_t**)addresses.TimePtr;
m_Difficulty = difficultyPtr != nullptr ? *difficultyPtr + 0x6664 : nullptr;
m_Time = timePtr != nullptr ? *timePtr + 0x48 : nullptr;
}<|endoftext|>
|
<commit_before>#include "mbed.h"
#include "greentea-client/test_env.h"
#include "rtos.h"
#if defined(MBED_RTOS_SINGLE_THREAD)
#error [NOT_SUPPORTED] test not supported
#endif
typedef struct {
float voltage; /* AD result of measured voltage */
float current; /* AD result of measured current */
uint32_t counter; /* A counter value */
} mail_t;
#define CREATE_VOLTAGE(COUNTER) (COUNTER * 0.1) * 33
#define CREATE_CURRENT(COUNTER) (COUNTER * 0.1) * 11
#define QUEUE_SIZE 16
#define QUEUE_PUT_DELAY 100
#define STACK_SIZE 1024
Mail<mail_t, QUEUE_SIZE> mail_box;
void send_thread (void const *argument) {
static uint32_t i = 10;
while (true) {
i++; // fake data update
mail_t *mail = mail_box.alloc();
mail->voltage = CREATE_VOLTAGE(i);
mail->current = CREATE_CURRENT(i);
mail->counter = i;
mail_box.put(mail);
Thread::wait(QUEUE_PUT_DELAY);
}
}
int main (void) {
GREENTEA_SETUP(20, "default_auto");
Thread thread(send_thread, NULL, osPriorityNormal, STACK_SIZE);
bool result = true;
int result_counter = 0;
while (true) {
osEvent evt = mail_box.get();
if (evt.status == osEventMail) {
mail_t *mail = (mail_t*)evt.value.p;
const float expected_voltage = CREATE_VOLTAGE(mail->counter);
const float expected_current = CREATE_CURRENT(mail->counter);
// Check using macros if received values correspond to values sent via queue
bool expected_values = (expected_voltage == mail->voltage) &&
(expected_current == mail->current);
result = result && expected_values;
const char *result_msg = expected_values ? "OK" : "FAIL";
printf("%3d %.2fV %.2fA ... [%s]\r\n", mail->counter,
mail->voltage,
mail->current,
result_msg);
mail_box.free(mail);
if (result == false || ++result_counter == QUEUE_SIZE) {
break;
}
}
}
GREENTEA_TESTSUITE_RESULT(result);
return 0;
}
<commit_msg>Remove deprecated Thread constructor usage<commit_after>#include "mbed.h"
#include "greentea-client/test_env.h"
#include "rtos.h"
#if defined(MBED_RTOS_SINGLE_THREAD)
#error [NOT_SUPPORTED] test not supported
#endif
typedef struct {
float voltage; /* AD result of measured voltage */
float current; /* AD result of measured current */
uint32_t counter; /* A counter value */
} mail_t;
#define CREATE_VOLTAGE(COUNTER) (COUNTER * 0.1) * 33
#define CREATE_CURRENT(COUNTER) (COUNTER * 0.1) * 11
#define QUEUE_SIZE 16
#define QUEUE_PUT_DELAY 100
#define STACK_SIZE 1024
Mail<mail_t, QUEUE_SIZE> mail_box;
void send_thread () {
static uint32_t i = 10;
while (true) {
i++; // fake data update
mail_t *mail = mail_box.alloc();
mail->voltage = CREATE_VOLTAGE(i);
mail->current = CREATE_CURRENT(i);
mail->counter = i;
mail_box.put(mail);
Thread::wait(QUEUE_PUT_DELAY);
}
}
int main (void) {
GREENTEA_SETUP(20, "default_auto");
Thread thread(osPriorityNormal, STACK_SIZE);
thread.start(send_thread);
bool result = true;
int result_counter = 0;
while (true) {
osEvent evt = mail_box.get();
if (evt.status == osEventMail) {
mail_t *mail = (mail_t*)evt.value.p;
const float expected_voltage = CREATE_VOLTAGE(mail->counter);
const float expected_current = CREATE_CURRENT(mail->counter);
// Check using macros if received values correspond to values sent via queue
bool expected_values = (expected_voltage == mail->voltage) &&
(expected_current == mail->current);
result = result && expected_values;
const char *result_msg = expected_values ? "OK" : "FAIL";
printf("%3d %.2fV %.2fA ... [%s]\r\n", mail->counter,
mail->voltage,
mail->current,
result_msg);
mail_box.free(mail);
if (result == false || ++result_counter == QUEUE_SIZE) {
break;
}
}
}
GREENTEA_TESTSUITE_RESULT(result);
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <map>
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "net/base/net_util.h"
#include "ui/gfx/gl/gl_switches.h"
namespace {
enum FrameRateTestFlags {
kMakeBodyComposited = 1 << 0,
kDisableVsync = 1 << 1,
kDisableGpu = 1 << 2,
kUseReferenceBuild = 1 << 3,
kInternal = 1 << 4,
};
std::string GetSuffixForTestFlags(int flags) {
std::string suffix;
if (flags & kMakeBodyComposited)
suffix += "_comp";
if (flags & kDisableVsync)
suffix += "_novsync";
if (flags & kDisableGpu)
suffix += "_nogpu";
if (flags & kUseReferenceBuild)
suffix += "_ref";
return suffix;
}
class FrameRateTest
: public UIPerfTest
, public ::testing::WithParamInterface<int> {
public:
FrameRateTest() {
show_window_ = true;
dom_automation_enabled_ = true;
}
virtual FilePath GetDataPath(const std::string& name) {
// Make sure the test data is checked out.
FilePath test_path;
PathService::Get(chrome::DIR_TEST_DATA, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("perf"));
test_path = test_path.Append(FILE_PATH_LITERAL("frame_rate"));
if (GetParam() & kInternal) {
test_path = test_path.Append(FILE_PATH_LITERAL("private"));
} else {
test_path = test_path.Append(FILE_PATH_LITERAL("content"));
}
test_path = test_path.AppendASCII(name);
return test_path;
}
virtual void SetUp() {
if (GetParam() & kUseReferenceBuild) {
UseReferenceBuild();
}
// UI tests boot up render views starting from about:blank. This causes
// the renderer to start up thinking it cannot use the GPU. To work
// around that, and allow the frame rate test to use the GPU, we must
// pass kAllowWebUICompositing.
launch_arguments_.AppendSwitch(switches::kAllowWebUICompositing);
if (GetParam() & kDisableGpu) {
launch_arguments_.AppendSwitch(switches::kDisableAcceleratedCompositing);
launch_arguments_.AppendSwitch(switches::kDisableExperimentalWebGL);
}
if (GetParam() & kDisableVsync) {
launch_arguments_.AppendSwitch(switches::kDisableGpuVsync);
}
UIPerfTest::SetUp();
}
void RunTest(const std::string& name) {
FilePath test_path = GetDataPath(name);
ASSERT_TRUE(file_util::DirectoryExists(test_path))
<< "Missing test directory: " << test_path.value();
test_path = test_path.Append(FILE_PATH_LITERAL("test.html"));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(net::FilePathToFileURL(test_path)));
if (GetParam() & kMakeBodyComposited) {
ASSERT_TRUE(tab->NavigateToURLAsync(
GURL("javascript:__make_body_composited();")));
}
// Block until initialization completes.
ASSERT_TRUE(WaitUntilJavaScriptCondition(
tab, L"", L"window.domAutomationController.send(__initialized);",
TestTimeouts::large_test_timeout_ms()));
// Start the tests.
ASSERT_TRUE(tab->NavigateToURLAsync(GURL("javascript:__start_all();")));
// Block until the tests completes.
ASSERT_TRUE(WaitUntilJavaScriptCondition(
tab, L"", L"window.domAutomationController.send(!__running_all);",
TestTimeouts::large_test_timeout_ms()));
// Read out the results.
std::wstring json;
ASSERT_TRUE(tab->ExecuteAndExtractString(
L"",
L"window.domAutomationController.send("
L"JSON.stringify(__calc_results_total()));",
&json));
std::map<std::string, std::string> results;
ASSERT_TRUE(JsonDictionaryToMap(WideToUTF8(json), &results));
ASSERT_TRUE(results.find("mean") != results.end());
ASSERT_TRUE(results.find("sigma") != results.end());
ASSERT_TRUE(results.find("gestures") != results.end());
ASSERT_TRUE(results.find("means") != results.end());
ASSERT_TRUE(results.find("sigmas") != results.end());
std::string trace_name = "fps";
trace_name += GetSuffixForTestFlags(GetParam());
printf("GESTURES %s: %s= [%s] [%s] [%s]\n", name.c_str(),
trace_name.c_str(),
results["gestures"].c_str(),
results["means"].c_str(),
results["sigmas"].c_str());
std::string mean_and_error = results["mean"] + "," + results["sigma"];
PrintResultMeanAndError(name, "", trace_name, mean_and_error,
"frames-per-second", true);
}
};
// Must use a different class name to avoid test instantiation conflicts
// with FrameRateTest. An alias is good enough. The alias names must match
// the pattern FrameRate*Test* for them to get picked up by the test bots.
typedef FrameRateTest FrameRateCompositingTest;
// Tests that trigger compositing with a -webkit-translateZ(0)
#define FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(content) \
TEST_P(FrameRateCompositingTest, content) { \
RunTest(#content); \
}
INSTANTIATE_TEST_CASE_P(, FrameRateCompositingTest, ::testing::Values(
0,
kMakeBodyComposited,
kUseReferenceBuild,
kUseReferenceBuild | kMakeBodyComposited));
FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(blank);
FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(googleblog);
typedef FrameRateTest FrameRateCanvasInternalTest;
// Tests for animated 2D canvas content
#define INTERNAL_FRAME_RATE_TEST_CANVAS(content) \
TEST_P(FrameRateCanvasInternalTest, content) { \
RunTest(#content); \
} \
INSTANTIATE_TEST_CASE_P(, FrameRateCanvasInternalTest, ::testing::Values(
kInternal,
kInternal | kDisableGpu,
kInternal | kUseReferenceBuild));
// Fails on all platforms. See http://crbug.com/102428
//INTERNAL_FRAME_RATE_TEST_CANVAS(fireflies)
//INTERNAL_FRAME_RATE_TEST_CANVAS(FishIE)
typedef FrameRateTest FrameRateNoVsyncCanvasInternalTest;
// Tests for animated 2D canvas content with and without disabling vsync
#define INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(content) \
TEST_P(FrameRateNoVsyncCanvasInternalTest, content) { \
RunTest(#content); \
} \
INSTANTIATE_TEST_CASE_P(, FrameRateNoVsyncCanvasInternalTest, ::testing::Values(
kInternal,
kInternal | kDisableVsync,
kInternal | kDisableGpu,
kInternal | kUseReferenceBuild,
kInternal | kDisableVsync | kUseReferenceBuild));
// Fails on all platforms. See http://crbug.com/102428
//INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(fishbowl)
//INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(speedreading)
} // namespace
<commit_msg>Fixing frame_rate test so that it will not fail the perf and GPU waterfalls.<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 <map>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "net/base/net_util.h"
#include "ui/gfx/gl/gl_switches.h"
namespace {
enum FrameRateTestFlags {
kRequiresGpu = 1 << 0, // only execute test if --enable-gpu
kDisableGpu = 1 << 1, // run test without gpu acceleration
kMakeBodyComposited = 1 << 2, // force the test to use the compositor
kDisableVsync = 1 << 3, // do not lock animation on vertical refresh
kUseReferenceBuild = 1 << 4, // run test using the reference chrome build
kInternal = 1 << 5, // Test uses internal test data
kHasRedirect = 1 << 6, // Test page contains an HTML redirect
};
std::string GetSuffixForTestFlags(int flags) {
std::string suffix;
if (flags & kMakeBodyComposited)
suffix += "_comp";
if (flags & kDisableVsync)
suffix += "_novsync";
if (flags & kDisableGpu)
suffix += "_nogpu";
if (flags & kUseReferenceBuild)
suffix += "_ref";
return suffix;
}
class FrameRateTest
: public UIPerfTest
, public ::testing::WithParamInterface<int> {
public:
FrameRateTest() {
show_window_ = true;
dom_automation_enabled_ = true;
// Since this is a performance test, try to use the host machine's GPU
// instead of falling back to software-rendering.
force_use_osmesa_ = false;
disable_accelerated_compositing_ = false;
}
virtual FilePath GetDataPath(const std::string& name) {
// Make sure the test data is checked out.
FilePath test_path;
PathService::Get(chrome::DIR_TEST_DATA, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("perf"));
test_path = test_path.Append(FILE_PATH_LITERAL("frame_rate"));
if (GetParam() & kInternal) {
test_path = test_path.Append(FILE_PATH_LITERAL("private"));
} else {
test_path = test_path.Append(FILE_PATH_LITERAL("content"));
}
test_path = test_path.AppendASCII(name);
return test_path;
}
virtual void SetUp() {
if (GetParam() & kUseReferenceBuild) {
UseReferenceBuild();
}
// UI tests boot up render views starting from about:blank. This causes
// the renderer to start up thinking it cannot use the GPU. To work
// around that, and allow the frame rate test to use the GPU, we must
// pass kAllowWebUICompositing.
launch_arguments_.AppendSwitch(switches::kAllowWebUICompositing);
// Some of the tests may launch http requests through JSON or AJAX
// which causes a security error (cross domain request) when the page
// is loaded from the local file system ( file:// ). The following switch
// fixes that error.
launch_arguments_.AppendSwitch(switches::kAllowFileAccessFromFiles);
if (GetParam() & kDisableGpu) {
launch_arguments_.AppendSwitch(switches::kDisableAcceleratedCompositing);
launch_arguments_.AppendSwitch(switches::kDisableExperimentalWebGL);
} else {
// This switch is required for enabling the accelerated 2d canvas on
// Chrome versions prior to Chrome 15, which may be the case for the
// reference build.
launch_arguments_.AppendSwitch(switches::kEnableAccelerated2dCanvas);
}
if (GetParam() & kDisableVsync) {
launch_arguments_.AppendSwitch(switches::kDisableGpuVsync);
}
UIPerfTest::SetUp();
}
void RunTest(const std::string& name) {
if ((GetParam() & kRequiresGpu) &&
!CommandLine::ForCurrentProcess()->HasSwitch("enable-gpu")) {
printf("Test skipped: requires gpu\n");
return;
}
FilePath test_path = GetDataPath(name);
ASSERT_TRUE(file_util::DirectoryExists(test_path))
<< "Missing test directory: " << test_path.value();
test_path = test_path.Append(FILE_PATH_LITERAL("test.html"));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
if (GetParam() & kHasRedirect) {
// If the test file is known to contain an html redirect, we must block
// until the second navigation is complete and reacquire the active tab
// in order to avoid a race condition.
// If the following assertion is triggered due to a timeout, it is
// possible that the current test does not re-direct and therefore should
// not have the kHasRedirect flag turned on.
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURLBlockUntilNavigationsComplete(
net::FilePathToFileURL(test_path), 2));
tab = GetActiveTab();
ASSERT_TRUE(tab.get());
} else {
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(net::FilePathToFileURL(test_path)));
}
// Block until initialization completes
// If the following assertion fails intermittently, it could be due to a
// race condition caused by an html redirect. If that is the case, verify
// that flag kHasRedirect is enabled for the current test.
ASSERT_TRUE(WaitUntilJavaScriptCondition(
tab, L"", L"window.domAutomationController.send(__initialized);",
TestTimeouts::large_test_timeout_ms()));
if (GetParam() & kMakeBodyComposited) {
ASSERT_TRUE(tab->NavigateToURLAsync(
GURL("javascript:__make_body_composited();")));
}
// Start the tests.
ASSERT_TRUE(tab->NavigateToURLAsync(GURL("javascript:__start_all();")));
// Block until the tests completes.
ASSERT_TRUE(WaitUntilJavaScriptCondition(
tab, L"", L"window.domAutomationController.send(!__running_all);",
TestTimeouts::large_test_timeout_ms()));
// Read out the results.
std::wstring json;
ASSERT_TRUE(tab->ExecuteAndExtractString(
L"",
L"window.domAutomationController.send("
L"JSON.stringify(__calc_results_total()));",
&json));
std::map<std::string, std::string> results;
ASSERT_TRUE(JsonDictionaryToMap(WideToUTF8(json), &results));
ASSERT_TRUE(results.find("mean") != results.end());
ASSERT_TRUE(results.find("sigma") != results.end());
ASSERT_TRUE(results.find("gestures") != results.end());
ASSERT_TRUE(results.find("means") != results.end());
ASSERT_TRUE(results.find("sigmas") != results.end());
std::string trace_name = "fps";
trace_name += GetSuffixForTestFlags(GetParam());
printf("GESTURES %s: %s= [%s] [%s] [%s]\n", name.c_str(),
trace_name.c_str(),
results["gestures"].c_str(),
results["means"].c_str(),
results["sigmas"].c_str());
std::string mean_and_error = results["mean"] + "," + results["sigma"];
PrintResultMeanAndError(name, "", trace_name, mean_and_error,
"frames-per-second", true);
}
};
// Must use a different class name to avoid test instantiation conflicts
// with FrameRateTest. An alias is good enough. The alias names must match
// the pattern FrameRate*Test* for them to get picked up by the test bots.
typedef FrameRateTest FrameRateCompositingTest;
// Tests that trigger compositing with a -webkit-translateZ(0)
#define FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(content) \
TEST_P(FrameRateCompositingTest, content) { \
RunTest(#content); \
}
INSTANTIATE_TEST_CASE_P(, FrameRateCompositingTest, ::testing::Values(
0,
kMakeBodyComposited,
kUseReferenceBuild,
kUseReferenceBuild | kMakeBodyComposited));
FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(blank);
FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(googleblog);
typedef FrameRateTest FrameRateNoVsyncCanvasInternalTest;
// Tests for animated 2D canvas content with and without disabling vsync
#define INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(content) \
TEST_P(FrameRateNoVsyncCanvasInternalTest, content) { \
RunTest(#content); \
} \
INSTANTIATE_TEST_CASE_P(, FrameRateNoVsyncCanvasInternalTest, ::testing::Values(
kInternal | kHasRedirect | kRequiresGpu,
kInternal | kHasRedirect | kDisableVsync |
kRequiresGpu,
kInternal | kHasRedirect | kDisableGpu,
kInternal | kHasRedirect | kDisableGpu |
kUseReferenceBuild,
kInternal | kHasRedirect | kUseReferenceBuild |
kRequiresGpu,
kInternal | kHasRedirect | kDisableVsync |
kRequiresGpu | kUseReferenceBuild));
INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(speedreading)
INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(fishbowl)
typedef FrameRateTest FrameRateGpuCanvasInternalTest;
// Tests for animated 2D canvas content to be tested only with GPU
// acceleration.
// tests are run with and without Vsync
#define INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(content) \
TEST_P(FrameRateGpuCanvasInternalTest, content) { \
RunTest(#content); \
} \
INSTANTIATE_TEST_CASE_P(, FrameRateGpuCanvasInternalTest, ::testing::Values(
kInternal | kHasRedirect | kRequiresGpu,
kInternal | kHasRedirect | kDisableVsync |
kRequiresGpu,
kInternal | kHasRedirect | kUseReferenceBuild |
kRequiresGpu,
kInternal | kHasRedirect | kDisableVsync |
kRequiresGpu | kUseReferenceBuild));
INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(fireflies)
INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(FishIE)
} // namespace
<|endoftext|>
|
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file InputMapper.h
* @brief Registers an InputContext from the Naali Input subsystem and uses it to translate
* given set of keys to Entity Actions on the entity the component is part of.
*/
#include "StableHeaders.h"
#include "EC_InputMapper.h"
#include "IAttribute.h"
#include "Input.h"
#include "Entity.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_InputMapper")
EC_InputMapper::~EC_InputMapper()
{
input_.reset();
}
void EC_InputMapper::RegisterMapping(const QKeySequence &keySeq, const QString &action, int eventType, int executionType)
{
ActionInvocation invocation;
invocation.name = action;
invocation.executionType = executionType;
mappings_[qMakePair(keySeq, (KeyEvent::EventType)eventType)] = invocation;
}
void EC_InputMapper::RegisterMapping(const QString &keySeq, const QString &action, int eventType, int executionType)
{
ActionInvocation invocation;
invocation.name = action;
invocation.executionType = executionType;
QKeySequence key(keySeq);
if(!key.isEmpty())
{
mappings_[qMakePair(key, (KeyEvent::EventType)eventType)] = invocation;
}
}
void EC_InputMapper::RemoveMapping(const QKeySequence &keySeq, int eventType)
{
Mappings_t::iterator it = mappings_.find(qMakePair(keySeq, (KeyEvent::EventType)eventType));
if (it != mappings_.end())
mappings_.erase(it);
}
void EC_InputMapper::RemoveMapping(const QString &keySeq, int eventType)
{
Mappings_t::iterator it = mappings_.find(qMakePair(QKeySequence(keySeq), (KeyEvent::EventType)eventType));
if (it != mappings_.end())
mappings_.erase(it);
}
EC_InputMapper::EC_InputMapper(IModule *module):
IComponent(module->GetFramework()),
contextName(this, "Input context name", "EC_InputMapper"),
contextPriority(this, "Input context priority", 90),
takeKeyboardEventsOverQt(this, "Take keyboard events over Qt", false),
takeMouseEventsOverQt(this, "Take mouse events over Qt", false),
mappings(this, "Mappings"),
executionType(this, "Action execution type", 1),
modifiersEnabled(this, "Key modifiers enable", true),
enabled(this, "Enable actions", true),
keyrepeatTrigger(this, "Trigger on keyrepeats", true)
{
static AttributeMetadata executionAttrData;
static bool metadataInitialized = false;
if(!metadataInitialized)
{
executionAttrData.enums[EntityAction::Local] = "Local";
executionAttrData.enums[EntityAction::Server] = "Server";
executionAttrData.enums[EntityAction::Server | EntityAction::Local] = "Local+Server";
executionAttrData.enums[EntityAction::Peers] = "Peers";
executionAttrData.enums[EntityAction::Peers | EntityAction::Local] = "Local+Peers";
executionAttrData.enums[EntityAction::Peers | EntityAction::Server] = "Local+Server";
executionAttrData.enums[EntityAction::Peers | EntityAction::Server | EntityAction::Local] = "Local+Server+Peers";
metadataInitialized = true;
}
executionType.SetMetadata(&executionAttrData);
connect(this, SIGNAL(OnAttributeChanged(IAttribute *, AttributeChange::Type)),
SLOT(AttributeUpdated(IAttribute *, AttributeChange::Type)));
input_ = GetFramework()->GetInput()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get());
input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get());
input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get());
connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *)));
}
void EC_InputMapper::AttributeUpdated(IAttribute *attribute, AttributeChange::Type change)
{
if(attribute == &contextName || attribute == &contextPriority)
{
input_.reset();
input_ = GetFramework()->GetInput()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get());
connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *)));
}
else if(attribute == &takeKeyboardEventsOverQt)
{
input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get());
}
else if(attribute == &takeMouseEventsOverQt)
{
input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get());
}
else if(attribute == &mappings)
{
}
}
void EC_InputMapper::HandleKeyEvent(KeyEvent *e)
{
if (!enabled.Get())
return;
if ( !keyrepeatTrigger.Get() )
{
// Now we do not repeat keypressed events.
if ( e != 0 && e->eventType == KeyEvent::KeyPressed && e->keyPressCount > 1 )
return;
}
Mappings_t::iterator it;
if (modifiersEnabled.Get())
it = mappings_.find(qMakePair(QKeySequence(e->keyCode | e->modifiers), e->eventType));
else
it = mappings_.find(qMakePair(QKeySequence(e->keyCode), e->eventType));
if (it == mappings_.end())
return;
Scene::Entity *entity = GetParentEntity();
if (!entity)
{
LogWarning("Parent entity not set. Cannot execute action.");
return;
}
ActionInvocation& invocation = it.value();
QString &action = invocation.name;
int execType = invocation.executionType;
// If zero executiontype, use default
if (!execType)
execType = executionType.Get();
// LogDebug("Invoking action " + action.toStdString() + " for entity " + ToString(entity->GetId()));
// If the action has parameters, parse them from the action string.
int idx = action.indexOf('(');
if (idx != -1)
{
QString act = action.left(idx);
QString parsedAction = action.mid(idx + 1);
parsedAction.remove('(');
parsedAction.remove(')');
QStringList parameters = parsedAction.split(',');
entity->Exec((EntityAction::ExecutionType)execType, act, parameters);
}
else
entity->Exec((EntityAction::ExecutionType)execType, action);
}
void EC_InputMapper::HandleMouseEvent(MouseEvent *e)
{
if (!enabled.Get())
return;
if (!GetParentEntity())
return;
//! \todo this hardcoding of look button logic (similar to RexMovementInput) is not nice!
if ((e->IsButtonDown(MouseEvent::RightButton)) && (!GetFramework()->GetInput()->IsMouseCursorVisible()))
{
if (e->relativeX != 0)
{
GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookX" , QString::number(e->relativeX));
}
if (e->relativeY != 0)
{
GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookY" , QString::number(e->relativeY));
}
}
}
<commit_msg>EC_InputMapper: Execute MouseScroll entity action with relative scroll amount as param, ignores -1 which seems to be the default.<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file InputMapper.h
* @brief Registers an InputContext from the Naali Input subsystem and uses it to translate
* given set of keys to Entity Actions on the entity the component is part of.
*/
#include "StableHeaders.h"
#include "EC_InputMapper.h"
#include "IAttribute.h"
#include "Input.h"
#include "Entity.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_InputMapper")
EC_InputMapper::~EC_InputMapper()
{
input_.reset();
}
void EC_InputMapper::RegisterMapping(const QKeySequence &keySeq, const QString &action, int eventType, int executionType)
{
ActionInvocation invocation;
invocation.name = action;
invocation.executionType = executionType;
mappings_[qMakePair(keySeq, (KeyEvent::EventType)eventType)] = invocation;
}
void EC_InputMapper::RegisterMapping(const QString &keySeq, const QString &action, int eventType, int executionType)
{
ActionInvocation invocation;
invocation.name = action;
invocation.executionType = executionType;
QKeySequence key(keySeq);
if(!key.isEmpty())
{
mappings_[qMakePair(key, (KeyEvent::EventType)eventType)] = invocation;
}
}
void EC_InputMapper::RemoveMapping(const QKeySequence &keySeq, int eventType)
{
Mappings_t::iterator it = mappings_.find(qMakePair(keySeq, (KeyEvent::EventType)eventType));
if (it != mappings_.end())
mappings_.erase(it);
}
void EC_InputMapper::RemoveMapping(const QString &keySeq, int eventType)
{
Mappings_t::iterator it = mappings_.find(qMakePair(QKeySequence(keySeq), (KeyEvent::EventType)eventType));
if (it != mappings_.end())
mappings_.erase(it);
}
EC_InputMapper::EC_InputMapper(IModule *module):
IComponent(module->GetFramework()),
contextName(this, "Input context name", "EC_InputMapper"),
contextPriority(this, "Input context priority", 90),
takeKeyboardEventsOverQt(this, "Take keyboard events over Qt", false),
takeMouseEventsOverQt(this, "Take mouse events over Qt", false),
mappings(this, "Mappings"),
executionType(this, "Action execution type", 1),
modifiersEnabled(this, "Key modifiers enable", true),
enabled(this, "Enable actions", true),
keyrepeatTrigger(this, "Trigger on keyrepeats", true)
{
static AttributeMetadata executionAttrData;
static bool metadataInitialized = false;
if(!metadataInitialized)
{
executionAttrData.enums[EntityAction::Local] = "Local";
executionAttrData.enums[EntityAction::Server] = "Server";
executionAttrData.enums[EntityAction::Server | EntityAction::Local] = "Local+Server";
executionAttrData.enums[EntityAction::Peers] = "Peers";
executionAttrData.enums[EntityAction::Peers | EntityAction::Local] = "Local+Peers";
executionAttrData.enums[EntityAction::Peers | EntityAction::Server] = "Local+Server";
executionAttrData.enums[EntityAction::Peers | EntityAction::Server | EntityAction::Local] = "Local+Server+Peers";
metadataInitialized = true;
}
executionType.SetMetadata(&executionAttrData);
connect(this, SIGNAL(OnAttributeChanged(IAttribute *, AttributeChange::Type)),
SLOT(AttributeUpdated(IAttribute *, AttributeChange::Type)));
input_ = GetFramework()->GetInput()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get());
input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get());
input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get());
connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *)));
}
void EC_InputMapper::AttributeUpdated(IAttribute *attribute, AttributeChange::Type change)
{
if(attribute == &contextName || attribute == &contextPriority)
{
input_.reset();
input_ = GetFramework()->GetInput()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get());
connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *)));
}
else if(attribute == &takeKeyboardEventsOverQt)
{
input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get());
}
else if(attribute == &takeMouseEventsOverQt)
{
input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get());
}
else if(attribute == &mappings)
{
}
}
void EC_InputMapper::HandleKeyEvent(KeyEvent *e)
{
if (!enabled.Get())
return;
if ( !keyrepeatTrigger.Get() )
{
// Now we do not repeat keypressed events.
if ( e != 0 && e->eventType == KeyEvent::KeyPressed && e->keyPressCount > 1 )
return;
}
Mappings_t::iterator it;
if (modifiersEnabled.Get())
it = mappings_.find(qMakePair(QKeySequence(e->keyCode | e->modifiers), e->eventType));
else
it = mappings_.find(qMakePair(QKeySequence(e->keyCode), e->eventType));
if (it == mappings_.end())
return;
Scene::Entity *entity = GetParentEntity();
if (!entity)
{
LogWarning("Parent entity not set. Cannot execute action.");
return;
}
ActionInvocation& invocation = it.value();
QString &action = invocation.name;
int execType = invocation.executionType;
// If zero executiontype, use default
if (!execType)
execType = executionType.Get();
// LogDebug("Invoking action " + action.toStdString() + " for entity " + ToString(entity->GetId()));
// If the action has parameters, parse them from the action string.
int idx = action.indexOf('(');
if (idx != -1)
{
QString act = action.left(idx);
QString parsedAction = action.mid(idx + 1);
parsedAction.remove('(');
parsedAction.remove(')');
QStringList parameters = parsedAction.split(',');
entity->Exec((EntityAction::ExecutionType)execType, act, parameters);
}
else
entity->Exec((EntityAction::ExecutionType)execType, action);
}
void EC_InputMapper::HandleMouseEvent(MouseEvent *e)
{
if (!enabled.Get())
return;
if (!GetParentEntity())
return;
//! \todo this hardcoding of look button logic (similar to RexMovementInput) is not nice!
if ((e->IsButtonDown(MouseEvent::RightButton)) && (!GetFramework()->GetInput()->IsMouseCursorVisible()))
{
if (e->relativeX != 0)
GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookX" , QString::number(e->relativeX));
if (e->relativeY != 0)
GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookY" , QString::number(e->relativeY));
}
if (e->relativeZ != 0 && e->relativeZ != -1) // For some reason this is -1 without scroll
GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseScroll" , QString::number(e->relativeZ));
}
<|endoftext|>
|
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file InputMapper.h
* @brief Registers an InputContext from the Naali Input subsystem and uses it to translate
* given set of keys to Entity Actions on the entity the component is part of.
*/
#include "StableHeaders.h"
#include "EC_InputMapper.h"
#include "InputServiceInterface.h"
#include "Entity.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_InputMapper")
/*
std::vector<ProtocolUtilities::MultiObjectUpdateInfo> updates;
EC_OpenSimPrim *prim = entity->GetComponent<EC_OpenSimPrim>().get();
OgreRenderer::EC_OgrePlaceable *ogre_pos = entity->GetComponent<OgreRenderer::EC_OgrePlaceable >().get();
if (!prim && !ogre_pos)
return;
ProtocolUtilities::MultiObjectUpdateInfo update;
update.local_id_ = prim->LocalId;
update.position_ = ogre_pos->GetPosition();
update.orientation_ = ogre_pos->GetOrientation();
update.scale_ = ogre_pos->GetScale();
updates.push_back(new_info);
worldStream->GetServerConnection()->SendMultipleObjectUpdatePacket(update_info_list);
*/
EC_InputMapper::~EC_InputMapper()
{
input_.reset();
}
void EC_InputMapper::RegisterMapping(const QString &action, const QKeySequence &keySeq)
{
// QString inputActionName = input_->Name() + '.' + action;
// const QKeySequence &keyBinding = framework_->Input().KeyBinding(inputActionName, keySeq);
mappings_[keySeq] = action;
// KeyEventSignal *signal = &input_->RegisterKeyEvent(keySeq);
// connect(signal, SIGNAL(SequencePressed(KeyEvent &)), SLOT(test()));
}
EC_InputMapper::EC_InputMapper(Foundation::ModuleInterface *module):
Foundation::ComponentInterface(module->GetFramework())
{
///\todo Generate random/unique name for input context?
input_ = GetFramework()->Input().RegisterInputContext("EC_InputMapper", 900);
input_->SetTakeKeyboardEventsOverQt(true);
connect(input_.get(), SIGNAL(KeyPressed(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
// Register some hardcoded mappings for testing purposes;
RegisterMapping("MoveForward", Qt::Key_I);
RegisterMapping("MoveBackward", Qt::Key_K);
RegisterMapping("MoveLeft", Qt::Key_J);
RegisterMapping("MoveRight", Qt::Key_L);
}
void EC_InputMapper::HandleKeyEvent(KeyEvent *key)
{
LogDebug("HandleKeyEvent");
// We only act on key presses that are not repeats.
// if (key->eventType != KeyEvent::KeyPressed || key->keyPressCount > 1)
// return;
Mappings_t::iterator it = mappings_.find(QKeySequence(key->keyCode, key->modifiers));
if (it == mappings_.end())
return;
const QString &action = it.value();
if (action.isEmpty())
{
LogWarning("");
return;
}
Scene::Entity *entity = GetParentEntity();
if (!entity)
{
LogWarning("Parent entity not set. Cannot execute action.");
return;
}
LogDebug("Performing action " + action.toStdString() + "for entity " + ToString(entity->GetId()));
entity->Exec(action);
}
<commit_msg>Fix EC_InputMapper input context priority from 900 to 90.<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file InputMapper.h
* @brief Registers an InputContext from the Naali Input subsystem and uses it to translate
* given set of keys to Entity Actions on the entity the component is part of.
*/
#include "StableHeaders.h"
#include "EC_InputMapper.h"
#include "InputServiceInterface.h"
#include "Entity.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_InputMapper")
/*
std::vector<ProtocolUtilities::MultiObjectUpdateInfo> updates;
EC_OpenSimPrim *prim = entity->GetComponent<EC_OpenSimPrim>().get();
OgreRenderer::EC_OgrePlaceable *ogre_pos = entity->GetComponent<OgreRenderer::EC_OgrePlaceable >().get();
if (!prim && !ogre_pos)
return;
ProtocolUtilities::MultiObjectUpdateInfo update;
update.local_id_ = prim->LocalId;
update.position_ = ogre_pos->GetPosition();
update.orientation_ = ogre_pos->GetOrientation();
update.scale_ = ogre_pos->GetScale();
updates.push_back(new_info);
worldStream->GetServerConnection()->SendMultipleObjectUpdatePacket(update_info_list);
*/
EC_InputMapper::~EC_InputMapper()
{
input_.reset();
}
void EC_InputMapper::RegisterMapping(const QString &action, const QKeySequence &keySeq)
{
// QString inputActionName = input_->Name() + '.' + action;
// const QKeySequence &keyBinding = framework_->Input().KeyBinding(inputActionName, keySeq);
mappings_[keySeq] = action;
// KeyEventSignal *signal = &input_->RegisterKeyEvent(keySeq);
// connect(signal, SIGNAL(SequencePressed(KeyEvent &)), SLOT(test()));
}
EC_InputMapper::EC_InputMapper(Foundation::ModuleInterface *module):
Foundation::ComponentInterface(module->GetFramework())
{
///\todo Generate random/unique name for input context?
input_ = GetFramework()->Input().RegisterInputContext("EC_InputMapper", 90);
input_->SetTakeKeyboardEventsOverQt(true);
connect(input_.get(), SIGNAL(KeyPressed(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
// Register some hardcoded mappings for testing purposes;
RegisterMapping("MoveForward", Qt::Key_I);
RegisterMapping("MoveBackward", Qt::Key_K);
RegisterMapping("MoveLeft", Qt::Key_J);
RegisterMapping("MoveRight", Qt::Key_L);
}
void EC_InputMapper::HandleKeyEvent(KeyEvent *key)
{
LogDebug("HandleKeyEvent");
// We only act on key presses that are not repeats.
// if (key->eventType != KeyEvent::KeyPressed || key->keyPressCount > 1)
// return;
Mappings_t::iterator it = mappings_.find(QKeySequence(key->keyCode, key->modifiers));
if (it == mappings_.end())
return;
const QString &action = it.value();
if (action.isEmpty())
{
LogWarning("");
return;
}
Scene::Entity *entity = GetParentEntity();
if (!entity)
{
LogWarning("Parent entity not set. Cannot execute action.");
return;
}
LogDebug("Performing action " + action.toStdString() + "for entity " + ToString(entity->GetId()));
entity->Exec(action);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkInformationExecutivePortVectorKey.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkInformationExecutivePortVectorKey.h"
#include "vtkExecutive.h"
#include "vtkGarbageCollector.h"
#include "vtkInformation.h"
#include <vtkstd/algorithm>
#include <vtkstd/vector>
// should the pipeline be double or singly linked (referenced) list, single
// make garbage collecting easier but results in a weak reference.
#define VTK_USE_SINGLE_REF 1
vtkCxxRevisionMacro(vtkInformationExecutivePortVectorKey, "1.6");
//----------------------------------------------------------------------------
vtkInformationExecutivePortVectorKey::vtkInformationExecutivePortVectorKey(const char* name, const char* location):
vtkInformationKey(name, location)
{
vtkFilteringInformationKeyManager::Register(this);
}
//----------------------------------------------------------------------------
vtkInformationExecutivePortVectorKey::~vtkInformationExecutivePortVectorKey()
{
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
//----------------------------------------------------------------------------
class vtkInformationExecutivePortVectorValue: public vtkObjectBase
{
public:
vtkTypeMacro(vtkInformationExecutivePortVectorValue, vtkObjectBase);
vtkstd::vector<vtkExecutive*> Executives;
vtkstd::vector<int> Ports;
virtual ~vtkInformationExecutivePortVectorValue();
void UnRegisterAllExecutives();
};
//----------------------------------------------------------------------------
vtkInformationExecutivePortVectorValue
::~vtkInformationExecutivePortVectorValue()
{
// Remove all our references to executives before erasing the vector.
this->UnRegisterAllExecutives();
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorValue::UnRegisterAllExecutives()
{
#ifndef VTK_USE_SINGLE_REF
for(vtkstd::vector<vtkExecutive*>::iterator i = this->Executives.begin();
i != this->Executives.end(); ++i)
{
if(vtkExecutive* e = *i)
{
e->UnRegister(0);
}
}
#endif
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Append(vtkInformation* info,
vtkExecutive* executive,
int port)
{
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
// The entry already exists. Append to its vector.
#ifndef VTK_USE_SINGLE_REF
executive->Register(0);
#endif
v->Executives.push_back(executive);
v->Ports.push_back(port);
}
else
{
// The entry does not yet exist. Just create it.
this->Set(info, &executive, &port, 1);
}
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Remove(vtkInformation* info,
vtkExecutive* executive,
int port)
{
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
// The entry exists. Find this executive/port pair and remove it.
for(unsigned int i=0; i < v->Executives.size(); ++i)
{
if(v->Executives[i] == executive && v->Ports[i] == port)
{
v->Executives.erase(v->Executives.begin()+i);
v->Ports.erase(v->Ports.begin()+i);
#ifndef VTK_USE_SINGLE_REF
executive->UnRegister(0);
#endif
break;
}
}
// If the last entry was removed, remove the entire value.
if(v->Executives.empty())
{
this->SetAsObjectBase(info, 0);
}
}
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Set(vtkInformation* info,
vtkExecutive** executives,
int* ports, int length)
{
if(executives && ports && length > 0)
{
#ifndef VTK_USE_SINGLE_REF
// Register our references to all the given executives.
for(int i=0; i < length; ++i)
{
if(executives[i])
{
executives[i]->Register(0);
}
}
#endif
// Store the vector of pointers.
vtkInformationExecutivePortVectorValue* oldv =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info));
if(oldv && static_cast<int>(oldv->Executives.size()) == length)
{
// Replace the existing value.
oldv->UnRegisterAllExecutives();
vtkstd::copy(executives, executives+length, oldv->Executives.begin());
vtkstd::copy(ports, ports+length, oldv->Ports.begin());
// Since this sets a value without call SetAsObjectBase(),
// the info has to be modified here (instead of
// vtkInformation::SetAsObjectBase()
info->Modified();
}
else
{
// Allocate a new value.
vtkInformationExecutivePortVectorValue* v =
new vtkInformationExecutivePortVectorValue;
this->ConstructClass("vtkInformationExecutivePortVectorValue");
v->Executives.insert(v->Executives.begin(), executives, executives+length);
v->Ports.insert(v->Ports.begin(), ports, ports+length);
this->SetAsObjectBase(info, v);
v->Delete();
}
}
else
{
this->SetAsObjectBase(info, 0);
}
}
//----------------------------------------------------------------------------
vtkExecutive**
vtkInformationExecutivePortVectorKey::GetExecutives(vtkInformation* info)
{
vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info));
return v?(&v->Executives[0]):0;
}
//----------------------------------------------------------------------------
int* vtkInformationExecutivePortVectorKey::GetPorts(vtkInformation* info)
{
vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info));
return v?(&v->Ports[0]):0;
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Get(vtkInformation* info,
vtkExecutive** executives,
int* ports)
{
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
vtkstd::copy(v->Executives.begin(), v->Executives.end(), executives);
vtkstd::copy(v->Ports.begin(), v->Ports.end(), ports);
}
}
//----------------------------------------------------------------------------
int vtkInformationExecutivePortVectorKey::Length(vtkInformation* info)
{
vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info));
return v?static_cast<int>(v->Executives.size()):0;
}
//----------------------------------------------------------------------------
int vtkInformationExecutivePortVectorKey::Has(vtkInformation* info)
{
return this->GetAsObjectBase(info)?1:0;
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::ShallowCopy(vtkInformation* from,
vtkInformation* to)
{
this->Set(to, this->GetExecutives(from), this->GetPorts(from),
this->Length(from));
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Remove(vtkInformation* info)
{
this->Superclass::Remove(info);
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Print(ostream& os,
vtkInformation* info)
{
// Print the value.
if(this->Has(info))
{
vtkExecutive** executives = this->GetExecutives(info);
int* ports = this->GetPorts(info);
int length = this->Length(info);
const char* sep = "";
for(int i=0; i < length; ++i)
{
if(executives[i])
{
os << sep << executives[i]->GetClassName()
<< "(" << executives[i] << ") port " << ports[i];
}
else
{
os << sep << "(NULL) port " << ports[i];
}
sep = ", ";
}
}
}
//----------------------------------------------------------------------------
void
vtkInformationExecutivePortVectorKey::Report(vtkInformation* info,
vtkGarbageCollector* collector)
{
#ifndef VTK_USE_SINGLE_REF
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
for(vtkstd::vector<vtkExecutive*>::iterator i = v->Executives.begin();
i != v->Executives.end(); ++i)
{
vtkGarbageCollectorReport(collector, *i, this->GetName());
}
}
#endif
}
//----------------------------------------------------------------------------
vtkExecutive**
vtkInformationExecutivePortVectorKey
::GetExecutivesWatchAddress(vtkInformation* info)
{
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
return &v->Executives[0];
}
return 0;
}
//----------------------------------------------------------------------------
int*
vtkInformationExecutivePortVectorKey
::GetPortsWatchAddress(vtkInformation* info)
{
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
return &v->Ports[0];
}
return 0;
}
<commit_msg>COMP: fix warning<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkInformationExecutivePortVectorKey.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkInformationExecutivePortVectorKey.h"
#include "vtkExecutive.h"
#include "vtkGarbageCollector.h"
#include "vtkInformation.h"
#include <vtkstd/algorithm>
#include <vtkstd/vector>
// should the pipeline be double or singly linked (referenced) list, single
// make garbage collecting easier but results in a weak reference.
#define VTK_USE_SINGLE_REF 1
vtkCxxRevisionMacro(vtkInformationExecutivePortVectorKey, "1.7");
//----------------------------------------------------------------------------
vtkInformationExecutivePortVectorKey::vtkInformationExecutivePortVectorKey(const char* name, const char* location):
vtkInformationKey(name, location)
{
vtkFilteringInformationKeyManager::Register(this);
}
//----------------------------------------------------------------------------
vtkInformationExecutivePortVectorKey::~vtkInformationExecutivePortVectorKey()
{
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
//----------------------------------------------------------------------------
class vtkInformationExecutivePortVectorValue: public vtkObjectBase
{
public:
vtkTypeMacro(vtkInformationExecutivePortVectorValue, vtkObjectBase);
vtkstd::vector<vtkExecutive*> Executives;
vtkstd::vector<int> Ports;
virtual ~vtkInformationExecutivePortVectorValue();
void UnRegisterAllExecutives();
};
//----------------------------------------------------------------------------
vtkInformationExecutivePortVectorValue
::~vtkInformationExecutivePortVectorValue()
{
// Remove all our references to executives before erasing the vector.
this->UnRegisterAllExecutives();
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorValue::UnRegisterAllExecutives()
{
#ifndef VTK_USE_SINGLE_REF
for(vtkstd::vector<vtkExecutive*>::iterator i = this->Executives.begin();
i != this->Executives.end(); ++i)
{
if(vtkExecutive* e = *i)
{
e->UnRegister(0);
}
}
#endif
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Append(vtkInformation* info,
vtkExecutive* executive,
int port)
{
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
// The entry already exists. Append to its vector.
#ifndef VTK_USE_SINGLE_REF
executive->Register(0);
#endif
v->Executives.push_back(executive);
v->Ports.push_back(port);
}
else
{
// The entry does not yet exist. Just create it.
this->Set(info, &executive, &port, 1);
}
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Remove(vtkInformation* info,
vtkExecutive* executive,
int port)
{
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
// The entry exists. Find this executive/port pair and remove it.
for(unsigned int i=0; i < v->Executives.size(); ++i)
{
if(v->Executives[i] == executive && v->Ports[i] == port)
{
v->Executives.erase(v->Executives.begin()+i);
v->Ports.erase(v->Ports.begin()+i);
#ifndef VTK_USE_SINGLE_REF
executive->UnRegister(0);
#endif
break;
}
}
// If the last entry was removed, remove the entire value.
if(v->Executives.empty())
{
this->SetAsObjectBase(info, 0);
}
}
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Set(vtkInformation* info,
vtkExecutive** executives,
int* ports, int length)
{
if(executives && ports && length > 0)
{
#ifndef VTK_USE_SINGLE_REF
// Register our references to all the given executives.
for(int i=0; i < length; ++i)
{
if(executives[i])
{
executives[i]->Register(0);
}
}
#endif
// Store the vector of pointers.
vtkInformationExecutivePortVectorValue* oldv =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info));
if(oldv && static_cast<int>(oldv->Executives.size()) == length)
{
// Replace the existing value.
oldv->UnRegisterAllExecutives();
vtkstd::copy(executives, executives+length, oldv->Executives.begin());
vtkstd::copy(ports, ports+length, oldv->Ports.begin());
// Since this sets a value without call SetAsObjectBase(),
// the info has to be modified here (instead of
// vtkInformation::SetAsObjectBase()
info->Modified();
}
else
{
// Allocate a new value.
vtkInformationExecutivePortVectorValue* v =
new vtkInformationExecutivePortVectorValue;
this->ConstructClass("vtkInformationExecutivePortVectorValue");
v->Executives.insert(v->Executives.begin(), executives, executives+length);
v->Ports.insert(v->Ports.begin(), ports, ports+length);
this->SetAsObjectBase(info, v);
v->Delete();
}
}
else
{
this->SetAsObjectBase(info, 0);
}
}
//----------------------------------------------------------------------------
vtkExecutive**
vtkInformationExecutivePortVectorKey::GetExecutives(vtkInformation* info)
{
vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info));
return v?(&v->Executives[0]):0;
}
//----------------------------------------------------------------------------
int* vtkInformationExecutivePortVectorKey::GetPorts(vtkInformation* info)
{
vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info));
return v?(&v->Ports[0]):0;
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Get(vtkInformation* info,
vtkExecutive** executives,
int* ports)
{
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
vtkstd::copy(v->Executives.begin(), v->Executives.end(), executives);
vtkstd::copy(v->Ports.begin(), v->Ports.end(), ports);
}
}
//----------------------------------------------------------------------------
int vtkInformationExecutivePortVectorKey::Length(vtkInformation* info)
{
vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info));
return v?static_cast<int>(v->Executives.size()):0;
}
//----------------------------------------------------------------------------
int vtkInformationExecutivePortVectorKey::Has(vtkInformation* info)
{
return this->GetAsObjectBase(info)?1:0;
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::ShallowCopy(vtkInformation* from,
vtkInformation* to)
{
this->Set(to, this->GetExecutives(from), this->GetPorts(from),
this->Length(from));
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Remove(vtkInformation* info)
{
this->Superclass::Remove(info);
}
//----------------------------------------------------------------------------
void vtkInformationExecutivePortVectorKey::Print(ostream& os,
vtkInformation* info)
{
// Print the value.
if(this->Has(info))
{
vtkExecutive** executives = this->GetExecutives(info);
int* ports = this->GetPorts(info);
int length = this->Length(info);
const char* sep = "";
for(int i=0; i < length; ++i)
{
if(executives[i])
{
os << sep << executives[i]->GetClassName()
<< "(" << executives[i] << ") port " << ports[i];
}
else
{
os << sep << "(NULL) port " << ports[i];
}
sep = ", ";
}
}
}
//----------------------------------------------------------------------------
void
#ifdef VTK_USE_SINGLE_REF
vtkInformationExecutivePortVectorKey::Report(vtkInformation*,
vtkGarbageCollector*)
{
#else
vtkInformationExecutivePortVectorKey::Report(vtkInformation* info,
vtkGarbageCollector* collector)
{
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
for(vtkstd::vector<vtkExecutive*>::iterator i = v->Executives.begin();
i != v->Executives.end(); ++i)
{
vtkGarbageCollectorReport(collector, *i, this->GetName());
}
}
#endif
}
//----------------------------------------------------------------------------
vtkExecutive**
vtkInformationExecutivePortVectorKey
::GetExecutivesWatchAddress(vtkInformation* info)
{
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
return &v->Executives[0];
}
return 0;
}
//----------------------------------------------------------------------------
int*
vtkInformationExecutivePortVectorKey
::GetPortsWatchAddress(vtkInformation* info)
{
if(vtkInformationExecutivePortVectorValue* v =
static_cast<vtkInformationExecutivePortVectorValue *>
(this->GetAsObjectBase(info)))
{
return &v->Ports[0];
}
return 0;
}
<|endoftext|>
|
<commit_before>// IBM_PROLOG_BEGIN_TAG
// This is an automatically generated prolog.
//
// $Source: src/include/usr/ecmddatabuffer/prdfCompressBuffer.H $
//
// IBM CONFIDENTIAL
//
// COPYRIGHT International Business Machines Corp. 2011
//
// p1
//
// Object Code Only (OCO) source materials
// Licensed Internal Code Source Materials
// IBM HostBoot Licensed Internal Code
//
// The source code for this program is not published or other-
// wise divested of its trade secrets, irrespective of what has
// been deposited with the U.S. Copyright Office.
//
// Origin: 30
//
// IBM_PROLOG_END
// IMPORTED FROM FIPS340 V1.2 on 11/10/2011
// Change Log *****************************************************************
//
// Flag Reason Vers Date Coder Description
// ---- ------- ---- -------- -------- --------------------------------------
// F478331 f225 10/07/04 iawillia Initial file creation.
//
// End Change Log *************************************************************
#ifndef __PRDFCOMPRESSBUFFER_H
#define __PRDFCOMPRESSBUFFER_H
#include <stdint.h>
#include <string.h>
#ifndef MIN
#define MIN(a, b) ( ((a) < (b)) ? (a) : (b) )
#endif
/*
* Prdf Compression Algorithm:
* The purpose of these compression routines are to compress the register
* dumps contained in our error logs. In large systems, we could possibly have
* more register data than we could possibly fit in an error log. These
* routines will allow us to fit more data into the error logs. In addition,
* the algorithms have been designed such that even if the end of the stream
* is lost (cut short), we can uncompress all of the data up to that point. We
* had proposed using the Zlib compression algorithms, but they required the
* CRC to match and we did not want that requirement.
*
* This compression algorithm is based off the LZ77 compression algorithm.
* The algorithm consists of a look-behind buffer of 1024 bytes, and a
* look-ahead buffer of 63 bytes. The algorithm attempts to find a match from
* the start of the look-ahead buffer located inside the look-behind buffer.
* If the longest match is bigger than 2 bytes (2 bytes is the break-even
* point), it converts the match into a token (pos in look-behind, length) of
* two bytes (12 bits to pos, 6 to length). If no match is found, the first
* character is popped from the look-ahead buffer. As matches are found (or
* not found) and popped from the look-ahead buffer, they are added to the
* end of the look-behind buffer (if the buffer increases over 1024, the start
* is shifted forward).
*
* As the stream (look-ahead buffer) is converted into tokens, they are
* bundled into groups of 8. A special token is added to the beginning of the
* bundle, recording the size of the following 8 tokens (2 or 1 bytes). Once
* the token bundle is complete (or end-of-stream), it is added to the output
* buffer.
*
* To use these routines, #define PRDF_COMPRESSBUFFER_UNCOMPRESS_FUNCTIONS
* or PRDF_COMPRESSBUFFER_COMPRESS_FUNCTIONS, depending on usage. These reduce
* the code footprint, since only the needed functions are compiled in.
*
*/
namespace PrdfCompressBuffer
{
/* size_t compressedBufferMax(size_t)
* Determines the maximum size of the compressed buffer (worst
* case) based on an input buffer size.
*/
#ifdef PRDF_COMPRESSBUFFER_COMPRESS_FUNCTIONS
size_t compressedBufferMax(size_t i_bufSize)
{
return 1 + ((i_bufSize * 9) / 8);
};
#endif
static size_t COMPRESSION_BREAKEVEN = 3;
/* class CompressedToken
* Internal class for converting (pos,size) tokens to two char.
*/
class CompressedToken
{
private:
uint8_t token[2];
public:
#ifdef PRDF_COMPRESSBUFFER_UNCOMPRESS_FUNCTIONS
// Default constructor.
CompressedToken() {};
#endif
#ifdef PRDF_COMPRESSBUFFER_COMPRESS_FUNCTIONS
/* CompressedToken(size_t, size_t)
* Convert position and size to uint8 tokens.
*/
CompressedToken(size_t i_pos, size_t i_size)
{
uint16_t l_token = (i_pos << 6)
| (i_size - COMPRESSION_BREAKEVEN);
token[1] = l_token & 0xFF;
token[0] = (l_token >> 8) & 0xFF;
};
#endif
#ifdef PRDF_COMPRESSBUFFER_UNCOMPRESS_FUNCTIONS
/* void uncompress(uint8_t *, uint8_t *&, size_t&)
* Convert uint8 tokens to pos,size values. Changes
* o_pos to be a pointer to the string inside the buffer and sets
* o_size to be the size of the string.
*/
void uncompress(uint8_t * i_buf, uint8_t * &o_pos, size_t &o_size)
{
uint16_t l_token = (token[0] << 8) | token[1];
o_pos = &i_buf[(l_token & 0xFFC0) >> 6];
o_size = (l_token & 0x3F) + COMPRESSION_BREAKEVEN;
return;
};
/* void read(uint8_t *)
* Read two bytes from the buffer to keep as tokens.
* NOTE: Does not modify i_buf.
*/
void read(uint8_t * i_buf)
{
token[0] = i_buf[0];
token[1] = i_buf[1];
};
#endif
#ifdef PRDF_COMPRESSBUFFER_COMPRESS_FUNCTIONS
/* void write(uint8_t *)
* Copy tokens into the beginning of the buffer.
*/
void write(uint8_t * o_buf) { memcpy(o_buf, token, 2); };
#endif
size_t size() { return 2; };
};
#ifdef PRDF_COMPRESSBUFFER_COMPRESS_FUNCTIONS
/* void compressBuffer(uint8_t *, size_t, uint8_t *, size_t &)
* Compresses i_buf and stores result into o_buf.
*
* i_buf : pointer to input buffer.
* i_size : size of input buffer.
* o_buf : pointer to output buffer (supplied by caller).
* o_size : max size of output buffer. After function, size of
* compressed buffer.
*
* NOTE: The size of the output buffer should be 1 + ((i_size * 9) / 8)
* to guarentee no data is lost (worst case for compression).
*/
void compressBuffer(uint8_t * i_buf, size_t i_size,
uint8_t * o_buf, size_t &o_size)
{
// Asserts.
if ((i_buf == NULL) || (o_buf == NULL))
{
o_size = 0;
return;
}
uint8_t * l_lookahead = i_buf; // Pointer to the look-behind buf.
size_t l_laSize = 0; // Size of look-behind.
size_t l_tokPos = 0; // Number of tokens in the bundle.
uint8_t * l_tokC = o_buf++; // Store compress bits and advance ptr.
size_t l_outputSize = 1; // start with l_tokC.
while((i_size > 0) && (l_outputSize < o_size))
{
size_t l_curLen = 1;
uint8_t * l_match = NULL;
// Find the longest match. (2 is our break-even pt,
// but 3 will provide better compression).
for (size_t i = 3;
i < MIN(i_size, l_laSize) && (i < (64 + COMPRESSION_BREAKEVEN))
; i++)
{
uint8_t * l_tmpMatch = NULL;
// MIKE TODO
l_tmpMatch = NULL;
//l_tmpMatch = (uint8_t *) memmem(l_lookahead, l_laSize,
//i_buf, i);
if (l_tmpMatch != NULL) // found match.
{
l_match = l_tmpMatch;
l_curLen = i;
}
else
i = i_size + l_laSize; // abort for loop.
}
// Create token.
if (l_match != NULL)
{
// found match, make sure there is room for the token.
if (o_size - l_outputSize >= 2)
{
CompressedToken l_token(l_match - l_lookahead, l_curLen);
l_token.write(o_buf);
o_buf += 2;
l_outputSize += 2;
(*l_tokC) = (*l_tokC << 1) | 0x1;
l_tokPos++;
i_buf += l_curLen;
l_laSize += l_curLen;
i_size -= l_curLen;
}
else
{
l_outputSize = o_size;
}
}
else
{
// no match, copy if room in the buffer.
if (o_size - l_outputSize >= 1)
{
o_buf[0] = i_buf[0];
o_buf++;
l_outputSize++;
(*l_tokC) = (*l_tokC << 1) | 0x0;
l_tokPos++;
i_buf++;
l_laSize++;
i_size--;
}
// else <= 0, so don't mess with l_outputSize.
}
// flush out lookahead. (keep at 1024 bytes)
while(l_laSize >= 1024)
{
l_laSize--;
l_lookahead++;
}
// check if bundle complete, create new bundle.
if (l_tokPos == 8)
{
l_tokPos = 0;
l_tokC = o_buf++;
l_outputSize++;
}
} // end while.
// Shift our bundle bits correctly. (the uncompressor doesn't know if
// the bundle was complete, so always assumes so.
if (l_tokPos != 0)
(*l_tokC) = (*l_tokC) << (8 - l_tokPos);
// We never _really_ go past our buffer, but sometimes our size says
// we did, so fix that up...
if (l_outputSize <= o_size)
o_size = l_outputSize;
return;
};
#endif
#ifdef PRDF_COMPRESSBUFFER_UNCOMPRESS_FUNCTIONS
/* void uncompressBuffer(uint8_t *, size_t, uint8_t *, size_t &)
* Uncompresses i_buf and stores result into o_buf.
*
* i_buf : pointer to input buffer.
* i_size : size of input buffer.
* o_buf : pointer to output buffer (supplied by caller).
* o_size : max size of output buffer. After function, size of
* uncompressed buffer.
*
* NOTE: The size is never stored in an compressed or uncompressed buffer.
* The caller needs to keep track of those kind of things and add
* whatever kind of header they need. If o_size isn't big enough
* you're not going to get the whole stream. These functions will
* not overrun the buffer.
*/
void uncompressBuffer(uint8_t * i_buf, size_t i_size,
uint8_t * o_buf, size_t & o_size)
{
// Asserts.
if ((i_buf == NULL) || (o_buf == NULL))
{
o_size = 0;
return;
}
uint8_t * l_lookahead = o_buf; // Look-behind buffer.
size_t l_laSize = 0; // look-behind size.
uint8_t l_tokC = 0; // Bundle bits.
uint8_t l_tokPos = 8; // Number of tokens from the bundle
// thus far. (start at 8 to get a new
// bundle right away).
size_t l_outputSize = 0; // Size of output buffer.
while ((i_size > 0) & (o_size > 0)) // while we're at the end of a buf.
{
// Check if we need to get a new bundle.
if (l_tokPos == 8)
{
l_tokPos = 0;
l_tokC = i_buf[0];
i_buf++;
i_size--;
continue;
}
// Check if token was compressed or not.
if ((l_tokC >> (7 - l_tokPos)) & 0x1)
{
// compressed token...
size_t l_matchSize;
uint8_t * l_match;
CompressedToken l_tok;
// read token from stream.
l_tok.read(i_buf);
i_buf += l_tok.size();
i_size -= l_tok.size();
// get pointer to lookahead buffer, copy into output buffer.
l_tok.uncompress(l_lookahead, l_match, l_matchSize);
memcpy(o_buf, l_match, MIN(l_matchSize, o_size));
// fix up all our sizes and pointers.
l_laSize += l_matchSize;
l_outputSize += MIN (l_matchSize, o_size);
o_size -= MIN (l_matchSize, o_size);
o_buf += l_matchSize;
}
else
{
// uncompressed token... just copy the byte.
o_buf[0] = i_buf[0];
o_size--;
o_buf++;
i_buf++;
i_size--;
l_laSize++;
l_outputSize++;
}
l_tokPos++; // just did a token, so inc the bundle count.
// Advance the look-behind buffer as needed.
while (l_laSize >= 1024)
{
l_lookahead++;
l_laSize--;
}
}
// fix up o_size (since we've been decrementing it...)
o_size = l_outputSize;
};
#endif
}; // end namespace.
#endif
<commit_msg>Enable call to memmem in prdfCompressBuffer (bugfix)<commit_after>// IBM_PROLOG_BEGIN_TAG
// This is an automatically generated prolog.
//
// $Source: src/include/usr/ecmddatabuffer/prdfCompressBuffer.H $
//
// IBM CONFIDENTIAL
//
// COPYRIGHT International Business Machines Corp. 2011
//
// p1
//
// Object Code Only (OCO) source materials
// Licensed Internal Code Source Materials
// IBM HostBoot Licensed Internal Code
//
// The source code for this program is not published or other-
// wise divested of its trade secrets, irrespective of what has
// been deposited with the U.S. Copyright Office.
//
// Origin: 30
//
// IBM_PROLOG_END
// IMPORTED FROM FIPS340 V1.2 on 11/10/2011
// Change Log *****************************************************************
//
// Flag Reason Vers Date Coder Description
// ---- ------- ---- -------- -------- --------------------------------------
// F478331 f225 10/07/04 iawillia Initial file creation.
//
// End Change Log *************************************************************
#ifndef __PRDFCOMPRESSBUFFER_H
#define __PRDFCOMPRESSBUFFER_H
#include <stdint.h>
#include <string.h>
#ifndef MIN
#define MIN(a, b) ( ((a) < (b)) ? (a) : (b) )
#endif
/*
* Prdf Compression Algorithm:
* The purpose of these compression routines are to compress the register
* dumps contained in our error logs. In large systems, we could possibly have
* more register data than we could possibly fit in an error log. These
* routines will allow us to fit more data into the error logs. In addition,
* the algorithms have been designed such that even if the end of the stream
* is lost (cut short), we can uncompress all of the data up to that point. We
* had proposed using the Zlib compression algorithms, but they required the
* CRC to match and we did not want that requirement.
*
* This compression algorithm is based off the LZ77 compression algorithm.
* The algorithm consists of a look-behind buffer of 1024 bytes, and a
* look-ahead buffer of 63 bytes. The algorithm attempts to find a match from
* the start of the look-ahead buffer located inside the look-behind buffer.
* If the longest match is bigger than 2 bytes (2 bytes is the break-even
* point), it converts the match into a token (pos in look-behind, length) of
* two bytes (12 bits to pos, 6 to length). If no match is found, the first
* character is popped from the look-ahead buffer. As matches are found (or
* not found) and popped from the look-ahead buffer, they are added to the
* end of the look-behind buffer (if the buffer increases over 1024, the start
* is shifted forward).
*
* As the stream (look-ahead buffer) is converted into tokens, they are
* bundled into groups of 8. A special token is added to the beginning of the
* bundle, recording the size of the following 8 tokens (2 or 1 bytes). Once
* the token bundle is complete (or end-of-stream), it is added to the output
* buffer.
*
* To use these routines, #define PRDF_COMPRESSBUFFER_UNCOMPRESS_FUNCTIONS
* or PRDF_COMPRESSBUFFER_COMPRESS_FUNCTIONS, depending on usage. These reduce
* the code footprint, since only the needed functions are compiled in.
*
*/
namespace PrdfCompressBuffer
{
/* size_t compressedBufferMax(size_t)
* Determines the maximum size of the compressed buffer (worst
* case) based on an input buffer size.
*/
#ifdef PRDF_COMPRESSBUFFER_COMPRESS_FUNCTIONS
size_t compressedBufferMax(size_t i_bufSize)
{
return 1 + ((i_bufSize * 9) / 8);
};
#endif
static size_t COMPRESSION_BREAKEVEN = 3;
/* class CompressedToken
* Internal class for converting (pos,size) tokens to two char.
*/
class CompressedToken
{
private:
uint8_t token[2];
public:
#ifdef PRDF_COMPRESSBUFFER_UNCOMPRESS_FUNCTIONS
// Default constructor.
CompressedToken() {};
#endif
#ifdef PRDF_COMPRESSBUFFER_COMPRESS_FUNCTIONS
/* CompressedToken(size_t, size_t)
* Convert position and size to uint8 tokens.
*/
CompressedToken(size_t i_pos, size_t i_size)
{
uint16_t l_token = (i_pos << 6)
| (i_size - COMPRESSION_BREAKEVEN);
token[1] = l_token & 0xFF;
token[0] = (l_token >> 8) & 0xFF;
};
#endif
#ifdef PRDF_COMPRESSBUFFER_UNCOMPRESS_FUNCTIONS
/* void uncompress(uint8_t *, uint8_t *&, size_t&)
* Convert uint8 tokens to pos,size values. Changes
* o_pos to be a pointer to the string inside the buffer and sets
* o_size to be the size of the string.
*/
void uncompress(uint8_t * i_buf, uint8_t * &o_pos, size_t &o_size)
{
uint16_t l_token = (token[0] << 8) | token[1];
o_pos = &i_buf[(l_token & 0xFFC0) >> 6];
o_size = (l_token & 0x3F) + COMPRESSION_BREAKEVEN;
return;
};
/* void read(uint8_t *)
* Read two bytes from the buffer to keep as tokens.
* NOTE: Does not modify i_buf.
*/
void read(uint8_t * i_buf)
{
token[0] = i_buf[0];
token[1] = i_buf[1];
};
#endif
#ifdef PRDF_COMPRESSBUFFER_COMPRESS_FUNCTIONS
/* void write(uint8_t *)
* Copy tokens into the beginning of the buffer.
*/
void write(uint8_t * o_buf) { memcpy(o_buf, token, 2); };
#endif
size_t size() { return 2; };
};
#ifdef PRDF_COMPRESSBUFFER_COMPRESS_FUNCTIONS
/* void compressBuffer(uint8_t *, size_t, uint8_t *, size_t &)
* Compresses i_buf and stores result into o_buf.
*
* i_buf : pointer to input buffer.
* i_size : size of input buffer.
* o_buf : pointer to output buffer (supplied by caller).
* o_size : max size of output buffer. After function, size of
* compressed buffer.
*
* NOTE: The size of the output buffer should be 1 + ((i_size * 9) / 8)
* to guarentee no data is lost (worst case for compression).
*/
void compressBuffer(uint8_t * i_buf, size_t i_size,
uint8_t * o_buf, size_t &o_size)
{
// Asserts.
if ((i_buf == NULL) || (o_buf == NULL))
{
o_size = 0;
return;
}
uint8_t * l_lookahead = i_buf; // Pointer to the look-behind buf.
size_t l_laSize = 0; // Size of look-behind.
size_t l_tokPos = 0; // Number of tokens in the bundle.
uint8_t * l_tokC = o_buf++; // Store compress bits and advance ptr.
size_t l_outputSize = 1; // start with l_tokC.
while((i_size > 0) && (l_outputSize < o_size))
{
size_t l_curLen = 1;
uint8_t * l_match = NULL;
// Find the longest match. (2 is our break-even pt,
// but 3 will provide better compression).
for (size_t i = 3;
i < MIN(i_size, l_laSize) && (i < (64 + COMPRESSION_BREAKEVEN))
; i++)
{
uint8_t * l_tmpMatch = NULL;
l_tmpMatch = (uint8_t *) memmem(l_lookahead, l_laSize,
i_buf, i);
if (l_tmpMatch != NULL) // found match.
{
l_match = l_tmpMatch;
l_curLen = i;
}
else
i = i_size + l_laSize; // abort for loop.
}
// Create token.
if (l_match != NULL)
{
// found match, make sure there is room for the token.
if (o_size - l_outputSize >= 2)
{
CompressedToken l_token(l_match - l_lookahead, l_curLen);
l_token.write(o_buf);
o_buf += 2;
l_outputSize += 2;
(*l_tokC) = (*l_tokC << 1) | 0x1;
l_tokPos++;
i_buf += l_curLen;
l_laSize += l_curLen;
i_size -= l_curLen;
}
else
{
l_outputSize = o_size;
}
}
else
{
// no match, copy if room in the buffer.
if (o_size - l_outputSize >= 1)
{
o_buf[0] = i_buf[0];
o_buf++;
l_outputSize++;
(*l_tokC) = (*l_tokC << 1) | 0x0;
l_tokPos++;
i_buf++;
l_laSize++;
i_size--;
}
// else <= 0, so don't mess with l_outputSize.
}
// flush out lookahead. (keep at 1024 bytes)
while(l_laSize >= 1024)
{
l_laSize--;
l_lookahead++;
}
// check if bundle complete, create new bundle.
if (l_tokPos == 8)
{
l_tokPos = 0;
l_tokC = o_buf++;
l_outputSize++;
}
} // end while.
// Shift our bundle bits correctly. (the uncompressor doesn't know if
// the bundle was complete, so always assumes so.
if (l_tokPos != 0)
(*l_tokC) = (*l_tokC) << (8 - l_tokPos);
// We never _really_ go past our buffer, but sometimes our size says
// we did, so fix that up...
if (l_outputSize <= o_size)
o_size = l_outputSize;
return;
};
#endif
#ifdef PRDF_COMPRESSBUFFER_UNCOMPRESS_FUNCTIONS
/* void uncompressBuffer(uint8_t *, size_t, uint8_t *, size_t &)
* Uncompresses i_buf and stores result into o_buf.
*
* i_buf : pointer to input buffer.
* i_size : size of input buffer.
* o_buf : pointer to output buffer (supplied by caller).
* o_size : max size of output buffer. After function, size of
* uncompressed buffer.
*
* NOTE: The size is never stored in an compressed or uncompressed buffer.
* The caller needs to keep track of those kind of things and add
* whatever kind of header they need. If o_size isn't big enough
* you're not going to get the whole stream. These functions will
* not overrun the buffer.
*/
void uncompressBuffer(uint8_t * i_buf, size_t i_size,
uint8_t * o_buf, size_t & o_size)
{
// Asserts.
if ((i_buf == NULL) || (o_buf == NULL))
{
o_size = 0;
return;
}
uint8_t * l_lookahead = o_buf; // Look-behind buffer.
size_t l_laSize = 0; // look-behind size.
uint8_t l_tokC = 0; // Bundle bits.
uint8_t l_tokPos = 8; // Number of tokens from the bundle
// thus far. (start at 8 to get a new
// bundle right away).
size_t l_outputSize = 0; // Size of output buffer.
while ((i_size > 0) & (o_size > 0)) // while we're at the end of a buf.
{
// Check if we need to get a new bundle.
if (l_tokPos == 8)
{
l_tokPos = 0;
l_tokC = i_buf[0];
i_buf++;
i_size--;
continue;
}
// Check if token was compressed or not.
if ((l_tokC >> (7 - l_tokPos)) & 0x1)
{
// compressed token...
size_t l_matchSize;
uint8_t * l_match;
CompressedToken l_tok;
// read token from stream.
l_tok.read(i_buf);
i_buf += l_tok.size();
i_size -= l_tok.size();
// get pointer to lookahead buffer, copy into output buffer.
l_tok.uncompress(l_lookahead, l_match, l_matchSize);
memcpy(o_buf, l_match, MIN(l_matchSize, o_size));
// fix up all our sizes and pointers.
l_laSize += l_matchSize;
l_outputSize += MIN (l_matchSize, o_size);
o_size -= MIN (l_matchSize, o_size);
o_buf += l_matchSize;
}
else
{
// uncompressed token... just copy the byte.
o_buf[0] = i_buf[0];
o_size--;
o_buf++;
i_buf++;
i_size--;
l_laSize++;
l_outputSize++;
}
l_tokPos++; // just did a token, so inc the bundle count.
// Advance the look-behind buffer as needed.
while (l_laSize >= 1024)
{
l_lookahead++;
l_laSize--;
}
}
// fix up o_size (since we've been decrementing it...)
o_size = l_outputSize;
};
#endif
}; // end namespace.
#endif
<|endoftext|>
|
<commit_before>#include <tools/common/log.h>
#include <tools/common/fmt.h>
int main (){
tools::log = tools::Logger::setLogger("test-log",0,true);
tools::log->info("This is a test log");
fmt::print("Hello world\n");
std::vector<bool> test1 = {true,false,true};
std::vector<double> test2 = {1,2,3};
tools::log->info("This tests logging a vector<bool> {}", test1);
tools::log->info("This tests logging a vector<bool> {}", fmt::join(test1,","));
tools::log->info("This tests logging a vector<double> {}", test2);
tools::log->info("This tests logging a vector<double> {:+.3f}", fmt::join(test2,","));
}<commit_msg>remove vector<bool> test: seems to be broken in new fmt<commit_after>#include <tools/common/log.h>
#include <tools/common/fmt.h>
int main (){
tools::log = tools::Logger::setLogger("test-log",0,true);
tools::log->info("This is a test log");
fmt::print("Hello world\n");
std::vector<bool> test1 = {true,false,true};
std::vector<double> test2 = {1,2,3};
// tools::log->info("This tests logging a vector<bool> {}", test1); // Broken
tools::log->info("This tests logging a vector<bool> {}", fmt::join(test1,","));
tools::log->info("This tests logging a vector<double> {}", test2);
tools::log->info("This tests logging a vector<double> {:+.3f}", fmt::join(test2,","));
}<|endoftext|>
|
<commit_before>// Copyright (C) 2010, 2011 and 2012 Marcin Arkadiusz Skrobiranda.
// 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 project 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 PROJECT 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 PROJECT 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 <Game/GameServer/Common/Constants.hpp>
#include <Game/GameServer/Generic/Executors/ExecutorEcho.hpp>
#include <boost/make_shared.hpp>
#include <log4cpp/Category.hh>
using namespace GameServer::Persistence;
using namespace boost;
using namespace log4cpp;
using namespace std;
namespace Game
{
ExecutorEcho::ExecutorEcho(
IContextShrPtr a_context
)
: Executor(a_context)
{
}
void ExecutorEcho::logExecutorStart() const
{
Category::getInstance("Category").infoStream() << "Starting the ExecutorEcho.";
}
bool ExecutorEcho::getParameters(
TUSLanguage::ICommand::Handle a_request
)
{
return true;
}
bool ExecutorEcho::processParameters()
{
return true;
}
bool ExecutorEcho::authenticate(
IPersistenceShrPtr a_persistence
) const
{
return true;
}
bool ExecutorEcho::getActingUser(
IPersistenceShrPtr a_persistence
)
{
return true;
}
bool ExecutorEcho::authorize(
IPersistenceShrPtr a_persistence
) const
{
return true;
}
bool ExecutorEcho::epochIsActive(
IPersistenceShrPtr a_persistence
) const
{
return true;
}
bool ExecutorEcho::verifyWorldConfiguration(
IPersistenceShrPtr a_persistence
) const
{
return true;
}
TUSLanguage::ICommand::Handle ExecutorEcho::perform(
IPersistenceShrPtr a_persistence
) const
{
return getBasicReply(REPLY_STATUS_OK);
}
TUSLanguage::ICommand::Handle ExecutorEcho::getBasicReply(
unsigned int const a_status
) const
{
// TUSLanguage::ICommand::Handle reply = make_shared<Reply>();
//
// reply->m_xml_document->appendNode("reply")->appendAttribute("id")->setValue(REPLY_ID_ECHO);
// reply->m_xml_document->getNode("reply")->appendNode("status")->appendAttribute("value")->setValue(a_status);
//
// return reply;
}
} // namespace Game
<commit_msg>ExecutorEcho ported.<commit_after>// Copyright (C) 2010, 2011 and 2012 Marcin Arkadiusz Skrobiranda.
// 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 project 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 PROJECT 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 PROJECT 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 <Game/GameServer/Common/Constants.hpp>
#include <Game/GameServer/Generic/Executors/ExecutorEcho.hpp>
#include <Language/Interface/ReplyBuilder.hpp>
#include <boost/make_shared.hpp>
#include <log4cpp/Category.hh>
using namespace GameServer::Persistence;
using namespace boost;
using namespace log4cpp;
using namespace std;
namespace Game
{
ExecutorEcho::ExecutorEcho(
IContextShrPtr a_context
)
: Executor(a_context)
{
}
void ExecutorEcho::logExecutorStart() const
{
Category::getInstance("Category").infoStream() << "Starting the ExecutorEcho.";
}
bool ExecutorEcho::getParameters(
TUSLanguage::ICommand::Handle a_request
)
{
return true;
}
bool ExecutorEcho::processParameters()
{
return true;
}
bool ExecutorEcho::authenticate(
IPersistenceShrPtr a_persistence
) const
{
return true;
}
bool ExecutorEcho::getActingUser(
IPersistenceShrPtr a_persistence
)
{
return true;
}
bool ExecutorEcho::authorize(
IPersistenceShrPtr a_persistence
) const
{
return true;
}
bool ExecutorEcho::epochIsActive(
IPersistenceShrPtr a_persistence
) const
{
return true;
}
bool ExecutorEcho::verifyWorldConfiguration(
IPersistenceShrPtr a_persistence
) const
{
return true;
}
TUSLanguage::ICommand::Handle ExecutorEcho::perform(
IPersistenceShrPtr a_persistence
) const
{
return getBasicReply(REPLY_STATUS_OK);
}
TUSLanguage::ICommand::Handle ExecutorEcho::getBasicReply(
unsigned int const a_status
) const
{
TUSLanguage::ReplyBuilder reply_builder;
return reply_builder.buildEchoReply(a_status);
}
} // namespace Game
<|endoftext|>
|
<commit_before>/*
* ESPectro32_Button.cpp
*
* Created on: Aug 8, 2017
* Author: andri
*/
#include "ESPectro32_Button.h"
#include <GPIO.h>
/* the global instance pointer */
//static xQueueHandle button_evt_queue = NULL;
ESPectro32_Button::ESPectro32_Button(uint8_t gpio, boolean activeHigh):
gpioNumber_(gpio), activeHigh_(activeHigh), Task("ESPectro32_Button_Task", 2048, configMAX_PRIORITIES - 2) {
//std::string taskName = "ESPectro32_Button_Task" + std::to_string((int)gpioNumber_);
char buf[30];
sprintf(buf, "ESPectro32_Button_Task_%d", gpioNumber_);
std::string taskName = std::string(buf);
setTaskName(taskName);
}
ESPectro32_Button::~ESPectro32_Button() {
}
/*
static void IRAM_ATTR ESPectro32_Button_Interrupt(void *arg) {
uint8_t gpio_num = (uint8_t) arg;
xQueueSendFromISR(button_evt_queue, &gpio_num, NULL);
}
*/
void ESPectro32_Button::begin() {
this->start(NULL);
}
ESPectro32_Button::Button_State ESPectro32_Button::getState() {
return buttonState_;
}
void ESPectro32_Button::runAsync(void *data) {
uint8_t currGpioNumber = (uint8_t)data;
//uint8_t io_num;
for(;;) {
/*
if(xQueueReceive(button_evt_queue, &io_num, (100/portTICK_PERIOD_MS))) {
//lastKnownLevel_ = gpio_get_level((gpio_num_t)io_num);
bool val = gpio_get_level((gpio_num_t)io_num);
printf("GPIO[%d] intr, val: %d, gpio: %d\n", io_num, val, currGpioNumber);
if (io_num == currGpioNumber) {
interruptTriggered_ = true;
//if (!runAlreadyCalled_) {
// examine();
//}
}
}
*/
//run();
examine();
vTaskDelay(50);
}
}
void ESPectro32_Button::start(void *taskData) {
/*
if (button_evt_queue == NULL) {
button_evt_queue = xQueueCreate(10, sizeof(uint8_t));
}
*/
ESP32CPP::GPIO::setInput((gpio_num_t)gpioNumber_);
//ESP32CPP::GPIO::setInterruptType((gpio_num_t)gpioNumber_, (gpio_int_type_t)GPIO_INTR_ANYEDGE);
//ESP32CPP::GPIO::addISRHandler((gpio_num_t)gpioNumber_, ESPectro32_Button_Interrupt, (void*)gpioNumber_);
Task::start((void*)gpioNumber_);
}
void ESPectro32_Button::examine() {
bool pressed = isActive();
unsigned long now = millis(); // current (relative) time in msecs.
// Implementation of the state machine
if (buttonState_ == ESPectro32ButtonUnknown) {
if (pressed) {
//printf("Pressed\n");
buttonState_ = ESPectro32ButtonPressed;
checkingStartTime_ = now; // remember starting time
}
}
else if (buttonState_ == ESPectro32ButtonPressed) {
if ((!pressed) && ((unsigned long) (now - checkingStartTime_) < ESPECTRO32_BUTTON_DEBOUNCE_DURATION_MS)) {
// button was released too quickly, checking done
buttonState_ = ESPectro32ButtonUnknown;
printf("Debounced after pressed\n");
} else if (!pressed) {
buttonState_ = ESPectro32ButtonReleased;
checkingEndTime_ = now; // remember stopping time
//printf("Released\n");
} else if ((pressed) && ((unsigned long) (now - checkingStartTime_) > ESPECTRO32_BUTTON_PRESS_DURATION_MS)) {
//printf("Considered Down\n");
if (btnDownCallback_) {
btnDownCallback_();
}
if (longPressedCallback_)
longPressedCallback_();
// if (_duringLongPressFunc)
// _duringLongPressFunc();
trackLongPressed_ = true; // Keep track of long press state
buttonState_ = ESPectro32ButtonWaitingForLongPressed;
} else {
// wait. Stay in this state.
}
}
else if (buttonState_ == ESPectro32ButtonReleased) {
if (!doublePressedCallback_ || (unsigned long)(now - checkingStartTime_) > ESPECTRO32_BUTTON_CLICK_DURATION_MS) {
// this was only a single short click
//printf("Considered Up\n");
if (btnUpCallback_)
btnUpCallback_();
buttonState_ = ESPectro32ButtonUnknown; // checking done.
} else if ((pressed) && ((unsigned long)(now - checkingEndTime_) > ESPECTRO32_BUTTON_DEBOUNCE_DURATION_MS)) {
buttonState_ = ESPectro32ButtonSecondPressed; // step to state 3
checkingStartTime_ = now; // remember starting time
}
}
else if (buttonState_ == ESPectro32ButtonSecondPressed) {
if (!pressed && ((unsigned long) (now - checkingStartTime_) > ESPECTRO32_BUTTON_DEBOUNCE_DURATION_MS)) {
// this was a 2 click sequence.
if (doublePressedCallback_)
doublePressedCallback_();
//printf("Considered Double\n");
buttonState_ = ESPectro32ButtonUnknown; // checking done.
}
}
else if (buttonState_ == ESPectro32ButtonWaitingForLongPressed) {
if (!pressed) {
//printf("Considered Long\n");
trackLongPressed_ = false; // Keep track of long press state
if(longPressedCallback_)
longPressedCallback_();
buttonState_ = ESPectro32ButtonUnknown; // checking done.
} else {
// button is being long pressed
trackLongPressed_ = true; // Keep track of long press state
//if (_duringLongPressFunc) _duringLongPressFunc();
}
}
}
/*
void ESPectro32_Button::run() {
runAlreadyCalled_ = true;
unsigned long currentMillis = millis();
if (!interruptTriggered_) {
if ((currentMillis - lastButtonPressedMillis_ > ESPECTRO32_BUTTON_LONG_PRESS_DURATION_MS)) {
if (buttonState_ == ESPectro32ButtonPressed) {
buttonState_ = ESPectro32ButtonLongPressed;
Serial.println(F("Considered Long Pressed"));
if (longPressedCallback_) {
longPressedCallback_();
}
}
//pressCount_ = 0;
}
pressCount_ = 0;
}
else {
interruptTriggered_ = false;
if ((currentMillis - lastButtonChangedMillis_) > ESPECTRO32_BUTTON_DEBOUNCE_DURATION_MS) {
lastButtonChangedMillis_ = currentMillis;
}
else {
Serial.println(F("Debounced"));
return;
}
bool pressed = isActive();
if (pressed) {
lastButtonPressedMillis_ = currentMillis;
//lastButtonChangedMillis_ = currentMillis;
buttonState_ = ESPectro32ButtonPressed;
Serial.println(F("DOWN"));
if (btnDownCallback_) {
btnDownCallback_();
}
}
else {
//lastButtonReleasedMillis_ = currentMillis;
Serial.println(F("Released"));
if (btnUpCallback_) {
btnUpCallback_();
}
if (buttonState_ != ESPectro32ButtonLongPressed && currentMillis - lastButtonPressedMillis_ > ESPECTRO32_BUTTON_PRESS_DURATION_MS) {
buttonState_ = ESPectro32ButtonReleased;
Serial.println(F("PRESSED"));
if (pressedCallback_) {
pressedCallback_();
}
//TODO: Double pressed not working well
//if (currentMillis - lastButtonPressedMillis_ > ESPECTRO32_BUTTON_PRESS_DURATION_MS) {
pressCount_++;
Serial.printf("Pressed count %d\n", pressCount_);
//}
if (pressCount_ == 2) {
pressCount_ = 0;
Serial.println(F("DOUBLE PRESSED"));
if (doublePressedCallback_) {
doublePressedCallback_();
}
}
}
}
}
}
*/
void ESPectro32_Button::onButtonDown(ButtonActionCallback cb) {
btnDownCallback_ = cb;
}
void ESPectro32_Button::onButtonUp(ButtonActionCallback cb) {
btnUpCallback_ = cb;
}
void ESPectro32_Button::onPressed(ButtonActionCallback cb) {
pressedCallback_ = cb;
}
void ESPectro32_Button::onLongPressed(ButtonActionCallback cb) {
longPressedCallback_ = cb;
}
void ESPectro32_Button::onDoublePressed(ButtonActionCallback cb) {
doublePressedCallback_ = cb;
}
bool ESPectro32_Button::isActive() {
// int buttonState = digitalRead(gpioNumber_);
// boolean pressed = activeHigh_ ? buttonState == HIGH : buttonState == LOW;
bool buttonState = ESP32CPP::GPIO::read((gpio_num_t)gpioNumber_);
bool pressed = activeHigh_ ? buttonState : !buttonState;
return pressed;
}
<commit_msg>Convert to pointer of uint8_t<commit_after>/*
* ESPectro32_Button.cpp
*
* Created on: Aug 8, 2017
* Author: andri
*/
#include "ESPectro32_Button.h"
#include <GPIO.h>
/* the global instance pointer */
//static xQueueHandle button_evt_queue = NULL;
ESPectro32_Button::ESPectro32_Button(uint8_t gpio, boolean activeHigh):
gpioNumber_(gpio), activeHigh_(activeHigh), Task("ESPectro32_Button_Task", 2048, configMAX_PRIORITIES - 2) {
//std::string taskName = "ESPectro32_Button_Task" + std::to_string((int)gpioNumber_);
char buf[30];
sprintf(buf, "ESPectro32_Button_Task_%d", gpioNumber_);
std::string taskName = std::string(buf);
setTaskName(taskName);
}
ESPectro32_Button::~ESPectro32_Button() {
}
/*
static void IRAM_ATTR ESPectro32_Button_Interrupt(void *arg) {
uint8_t gpio_num = (uint8_t) arg;
xQueueSendFromISR(button_evt_queue, &gpio_num, NULL);
}
*/
void ESPectro32_Button::begin() {
this->start(NULL);
}
ESPectro32_Button::Button_State ESPectro32_Button::getState() {
return buttonState_;
}
void ESPectro32_Button::runAsync(void *data) {
uint8_t currGpioNumber = *((uint8_t*)data);
//uint8_t io_num;
for(;;) {
/*
if(xQueueReceive(button_evt_queue, &io_num, (100/portTICK_PERIOD_MS))) {
//lastKnownLevel_ = gpio_get_level((gpio_num_t)io_num);
bool val = gpio_get_level((gpio_num_t)io_num);
printf("GPIO[%d] intr, val: %d, gpio: %d\n", io_num, val, currGpioNumber);
if (io_num == currGpioNumber) {
interruptTriggered_ = true;
//if (!runAlreadyCalled_) {
// examine();
//}
}
}
*/
//run();
examine();
vTaskDelay(50);
}
}
void ESPectro32_Button::start(void *taskData) {
/*
if (button_evt_queue == NULL) {
button_evt_queue = xQueueCreate(10, sizeof(uint8_t));
}
*/
ESP32CPP::GPIO::setInput((gpio_num_t)gpioNumber_);
//ESP32CPP::GPIO::setInterruptType((gpio_num_t)gpioNumber_, (gpio_int_type_t)GPIO_INTR_ANYEDGE);
//ESP32CPP::GPIO::addISRHandler((gpio_num_t)gpioNumber_, ESPectro32_Button_Interrupt, (void*)gpioNumber_);
Task::start((void*)gpioNumber_);
}
void ESPectro32_Button::examine() {
bool pressed = isActive();
unsigned long now = millis(); // current (relative) time in msecs.
// Implementation of the state machine
if (buttonState_ == ESPectro32ButtonUnknown) {
if (pressed) {
//printf("Pressed\n");
buttonState_ = ESPectro32ButtonPressed;
checkingStartTime_ = now; // remember starting time
}
}
else if (buttonState_ == ESPectro32ButtonPressed) {
if ((!pressed) && ((unsigned long) (now - checkingStartTime_) < ESPECTRO32_BUTTON_DEBOUNCE_DURATION_MS)) {
// button was released too quickly, checking done
buttonState_ = ESPectro32ButtonUnknown;
printf("Debounced after pressed\n");
} else if (!pressed) {
buttonState_ = ESPectro32ButtonReleased;
checkingEndTime_ = now; // remember stopping time
//printf("Released\n");
} else if ((pressed) && ((unsigned long) (now - checkingStartTime_) > ESPECTRO32_BUTTON_PRESS_DURATION_MS)) {
//printf("Considered Down\n");
if (btnDownCallback_) {
btnDownCallback_();
}
if (longPressedCallback_)
longPressedCallback_();
// if (_duringLongPressFunc)
// _duringLongPressFunc();
trackLongPressed_ = true; // Keep track of long press state
buttonState_ = ESPectro32ButtonWaitingForLongPressed;
} else {
// wait. Stay in this state.
}
}
else if (buttonState_ == ESPectro32ButtonReleased) {
if (!doublePressedCallback_ || (unsigned long)(now - checkingStartTime_) > ESPECTRO32_BUTTON_CLICK_DURATION_MS) {
// this was only a single short click
//printf("Considered Up\n");
if (btnUpCallback_)
btnUpCallback_();
buttonState_ = ESPectro32ButtonUnknown; // checking done.
} else if ((pressed) && ((unsigned long)(now - checkingEndTime_) > ESPECTRO32_BUTTON_DEBOUNCE_DURATION_MS)) {
buttonState_ = ESPectro32ButtonSecondPressed; // step to state 3
checkingStartTime_ = now; // remember starting time
}
}
else if (buttonState_ == ESPectro32ButtonSecondPressed) {
if (!pressed && ((unsigned long) (now - checkingStartTime_) > ESPECTRO32_BUTTON_DEBOUNCE_DURATION_MS)) {
// this was a 2 click sequence.
if (doublePressedCallback_)
doublePressedCallback_();
//printf("Considered Double\n");
buttonState_ = ESPectro32ButtonUnknown; // checking done.
}
}
else if (buttonState_ == ESPectro32ButtonWaitingForLongPressed) {
if (!pressed) {
//printf("Considered Long\n");
trackLongPressed_ = false; // Keep track of long press state
if(longPressedCallback_)
longPressedCallback_();
buttonState_ = ESPectro32ButtonUnknown; // checking done.
} else {
// button is being long pressed
trackLongPressed_ = true; // Keep track of long press state
//if (_duringLongPressFunc) _duringLongPressFunc();
}
}
}
/*
void ESPectro32_Button::run() {
runAlreadyCalled_ = true;
unsigned long currentMillis = millis();
if (!interruptTriggered_) {
if ((currentMillis - lastButtonPressedMillis_ > ESPECTRO32_BUTTON_LONG_PRESS_DURATION_MS)) {
if (buttonState_ == ESPectro32ButtonPressed) {
buttonState_ = ESPectro32ButtonLongPressed;
Serial.println(F("Considered Long Pressed"));
if (longPressedCallback_) {
longPressedCallback_();
}
}
//pressCount_ = 0;
}
pressCount_ = 0;
}
else {
interruptTriggered_ = false;
if ((currentMillis - lastButtonChangedMillis_) > ESPECTRO32_BUTTON_DEBOUNCE_DURATION_MS) {
lastButtonChangedMillis_ = currentMillis;
}
else {
Serial.println(F("Debounced"));
return;
}
bool pressed = isActive();
if (pressed) {
lastButtonPressedMillis_ = currentMillis;
//lastButtonChangedMillis_ = currentMillis;
buttonState_ = ESPectro32ButtonPressed;
Serial.println(F("DOWN"));
if (btnDownCallback_) {
btnDownCallback_();
}
}
else {
//lastButtonReleasedMillis_ = currentMillis;
Serial.println(F("Released"));
if (btnUpCallback_) {
btnUpCallback_();
}
if (buttonState_ != ESPectro32ButtonLongPressed && currentMillis - lastButtonPressedMillis_ > ESPECTRO32_BUTTON_PRESS_DURATION_MS) {
buttonState_ = ESPectro32ButtonReleased;
Serial.println(F("PRESSED"));
if (pressedCallback_) {
pressedCallback_();
}
//TODO: Double pressed not working well
//if (currentMillis - lastButtonPressedMillis_ > ESPECTRO32_BUTTON_PRESS_DURATION_MS) {
pressCount_++;
Serial.printf("Pressed count %d\n", pressCount_);
//}
if (pressCount_ == 2) {
pressCount_ = 0;
Serial.println(F("DOUBLE PRESSED"));
if (doublePressedCallback_) {
doublePressedCallback_();
}
}
}
}
}
}
*/
void ESPectro32_Button::onButtonDown(ButtonActionCallback cb) {
btnDownCallback_ = cb;
}
void ESPectro32_Button::onButtonUp(ButtonActionCallback cb) {
btnUpCallback_ = cb;
}
void ESPectro32_Button::onPressed(ButtonActionCallback cb) {
pressedCallback_ = cb;
}
void ESPectro32_Button::onLongPressed(ButtonActionCallback cb) {
longPressedCallback_ = cb;
}
void ESPectro32_Button::onDoublePressed(ButtonActionCallback cb) {
doublePressedCallback_ = cb;
}
bool ESPectro32_Button::isActive() {
// int buttonState = digitalRead(gpioNumber_);
// boolean pressed = activeHigh_ ? buttonState == HIGH : buttonState == LOW;
bool buttonState = ESP32CPP::GPIO::read((gpio_num_t)gpioNumber_);
bool pressed = activeHigh_ ? buttonState : !buttonState;
return pressed;
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: Markus Fasel *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliHLTCaloTriggerDataStruct.h"
#include "AliHLTCaloTriggerHeaderStruct.h"
#include "AliHLTCaloTriggerRawDigitDataStruct.h"
#include "AliEMCALTriggerSTURawStream.h"
#include "AliHLTEMCALDefinitions.h"
#include "AliHLTEMCALGeometry.h"
#include "AliHLTEMCALTriggerDataMakerComponent.h"
ClassImp(AliHLTEMCALTriggerDataMakerComponent)
AliHLTEMCALTriggerDataMakerComponent::AliHLTEMCALTriggerDataMakerComponent():
AliHLTCaloProcessor(),
AliHLTCaloConstantsHandler("EMCAL"),
fGeometry(NULL),
fSTUHeader(),
fNRawDigitsTRU(0),
fNRawDigitsSTU(0),
fMaxChannel(0)
{
for(Short_t iter = 0; iter < kMaxChannels; iter++){
fRawIndexesTRU[iter] = -1;
fRawIndexesSTU[iter] = -1;
}
}
AliHLTEMCALTriggerDataMakerComponent::~AliHLTEMCALTriggerDataMakerComponent() {
if(fGeometry) delete fGeometry;
}
int AliHLTEMCALTriggerDataMakerComponent::DoInit(int argc, const char **argv){
fGeometry = new AliHLTEMCALGeometry(GetRunNo());
return 0;
}
int AliHLTEMCALTriggerDataMakerComponent::DoDeinit(){
if(fGeometry) delete fGeometry;
fGeometry = NULL;
return 0;
}
const char* AliHLTEMCALTriggerDataMakerComponent::GetComponentID(){
return "EmcalTriggerDataMaker";
}
void AliHLTEMCALTriggerDataMakerComponent::GetInputDataTypes( std::vector <AliHLTComponentDataType>& list){
list.clear();
list.push_back( AliHLTEMCALDefinitions::fgkTriggerRawDigitDataType | kAliHLTDataOriginEMCAL );
list.push_back( AliHLTEMCALDefinitions::fgkTriggerSTUDataType | kAliHLTDataOriginEMCAL );
}
AliHLTComponentDataType AliHLTEMCALTriggerDataMakerComponent::GetOutputDataType(){
return kAliHLTDataTypeCaloTrigger | kAliHLTDataOriginEMCAL;
}
void AliHLTEMCALTriggerDataMakerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier){
constBase = sizeof(AliHLTCaloTriggerHeaderStruct);
inputMultiplier = 1.5;
}
AliHLTComponent* AliHLTEMCALTriggerDataMakerComponent::Spawn(){
return new AliHLTEMCALTriggerDataMakerComponent;
}
bool AliHLTEMCALTriggerDataMakerComponent::CheckInputDataType(const AliHLTComponentDataType &datatype) {
//comment
vector <AliHLTComponentDataType> validTypes;
GetInputDataTypes(validTypes);
for(UInt_t i=0; i < validTypes.size(); i++) {
if ( datatype == validTypes.at(i) ) {
return true;
}
}
HLTDebug("Invalid Datatype");
return false;
}
int AliHLTEMCALTriggerDataMakerComponent::DoEvent( const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& trigData, AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size, std::vector<AliHLTComponentBlockData>& outputBlocks ){
if(!IsDataEvent()) {
size = 0;
return 0;
}
UInt_t totSize = 0;
const AliHLTComponentBlockData* iter = NULL;
// Get pointers to output buffer
AliHLTCaloTriggerHeaderStruct *headerPtr = reinterpret_cast<AliHLTCaloTriggerHeaderStruct *>(outputPtr);
AliHLTCaloTriggerDataStruct *dataIter = reinterpret_cast<AliHLTCaloTriggerDataStruct *>(outputPtr + sizeof(AliHLTCaloTriggerHeaderStruct));
totSize += sizeof(AliHLTCaloTriggerHeaderStruct);
Reset();
AliHLTCaloTriggerRawDigitDataStruct *dataptr = NULL;
for(ULong_t ndx = 0; ndx < evtData.fBlockCnt; ndx++){
iter = blocks + ndx;
if(!this->CheckInputDataType(iter->fDataType)){
continue;
}
if(iter->fDataType == AliHLTEMCALDefinitions::fgkTriggerRawDigitDataType){
// Handle TRU data
Int_t ndigits = iter->fSize / sizeof(AliHLTCaloTriggerRawDigitDataStruct);
HLTDebug("Data containing %d TRU digits", ndigits);
dataptr = reinterpret_cast<AliHLTCaloTriggerRawDigitDataStruct *>(iter->fPtr);
ReadTRUData(ndigits, dataptr);
} else if(iter->fDataType == AliHLTEMCALDefinitions::fgkTriggerSTUDataType){
// Handle STU data
AliHLTEMCALSTUHeaderStruct *stuheader = reinterpret_cast<AliHLTEMCALSTUHeaderStruct *>(iter->fPtr);
AliHLTInt32_t sizeExpected = sizeof(AliHLTEMCALSTUHeaderStruct) + sizeof(AliHLTCaloTriggerRawDigitDataStruct) * stuheader->fNRawDigits;
if(iter->fSize != sizeExpected){
HLTWarning("STU-reader: Size of the input buffer not matching for amount of digits, expected %d, obtained %d", sizeExpected, iter->fSize);
continue;
}
dataptr = reinterpret_cast<AliHLTCaloTriggerRawDigitDataStruct *>(reinterpret_cast<AliHLTUInt8_t*>(iter->fPtr) + sizeof(AliHLTEMCALSTUHeaderStruct));
HLTDebug("Data containing %d STU digits", stuheader->fNRawDigits);
ReadSTUData(stuheader, dataptr);
}
}
// Write header
memcpy(headerPtr->fL1Threshold, fSTUHeader.fL1Threshold, sizeof(Int_t) *4);
memcpy(headerPtr->fL1V0, fSTUHeader.fL1V0, sizeof(Int_t) * 2);
headerPtr->fL1FrameMask = fSTUHeader.fL1FrameMask;
AliHLTUInt32_t availableSize = size - sizeof(AliHLTCaloTriggerHeaderStruct);
// Write data
Int_t dataSize = MakeTriggerData(dataIter, availableSize);
totSize += dataSize;
headerPtr->fNfastor = dataSize / sizeof(AliHLTCaloTriggerDataStruct);
AliHLTComponentBlockData bdChannelData;
FillBlockData( bdChannelData );
bdChannelData.fOffset = 0; //FIXME
bdChannelData.fSize = totSize;
bdChannelData.fDataType = GetOutputDataType();
outputBlocks.push_back(bdChannelData);
outputPtr += totSize; //Updating position of the output buffer
size = totSize;
return 0;
}
void AliHLTEMCALTriggerDataMakerComponent::ReadSTUData(AliHLTEMCALSTUHeaderStruct *headerptr, AliHLTCaloTriggerRawDigitDataStruct *dataptr){
fSTUHeader = *headerptr;
for(UShort_t idig = 0; idig < headerptr->fNRawDigits; idig++){
if(dataptr->fID > kMaxChannels || dataptr->fID < 0){
HLTWarning("Invalid TRU index: %d", dataptr->fID);
dataptr++;
continue;
}
fRawIndexesSTU[dataptr->fID] = fNRawDigitsSTU;
if(dataptr->fID > fMaxChannel) fMaxChannel = dataptr->fID;
fSTURawDigitBuffer[fNRawDigitsSTU] = *dataptr;
dataptr++;
fNRawDigitsSTU++;
}
HLTDebug("Successfully read in %d STU digits", fNRawDigitsSTU);
}
void AliHLTEMCALTriggerDataMakerComponent::ReadTRUData(UShort_t ndigits, AliHLTCaloTriggerRawDigitDataStruct *triggerdata){
for(UShort_t idig = 0; idig < ndigits; idig++){
fRawIndexesTRU[triggerdata->fID] = fNRawDigitsTRU;
if(triggerdata->fID > fMaxChannel) fMaxChannel = triggerdata->fID;
fTRURawDigitBuffer[fNRawDigitsTRU] = *triggerdata;
triggerdata++;
fNRawDigitsTRU++;
}
HLTDebug("Successfully read in %d TRU digits", fNRawDigitsTRU);
}
Int_t AliHLTEMCALTriggerDataMakerComponent::MakeTriggerData(AliHLTCaloTriggerDataStruct *outputdata, AliHLTUInt32_t &availableSize) {
if(availableSize < sizeof(AliHLTCaloTriggerDataStruct)){
HLTWarning("Not enough space in buffer to write triggers");
return 0;
}
Int_t outputsize = 0, col = 0, row = 0, ntriggers = 0 ;
AliHLTCaloTriggerRawDigitDataStruct tmpdigit;
for(UShort_t indcounter = 0; indcounter <= fMaxChannel; indcounter++){
if(availableSize < sizeof(AliHLTCaloTriggerDataStruct)){
HLTWarning("Buffer exceeded after %d triggers", ntriggers);
break;
}
fGeometry->GetGeometryPtr()->GetPositionInEMCALFromAbsFastORIndex(indcounter, col, row);
if(fRawIndexesTRU[indcounter] >= 0 && fRawIndexesSTU[indcounter] >=0){
CombineTRUSTUDigit(tmpdigit, fTRURawDigitBuffer[fRawIndexesTRU[indcounter]], fSTURawDigitBuffer[fRawIndexesSTU[indcounter]]);
ConvertRawDigit(outputdata, &tmpdigit, col, row);
outputsize += sizeof(AliHLTCaloTriggerDataStruct);
availableSize += sizeof(AliHLTCaloTriggerDataStruct);
outputdata++;
ntriggers++;
} else if(fRawIndexesTRU[indcounter] >= 0){
ConvertRawDigit(outputdata, &(fTRURawDigitBuffer[fRawIndexesTRU[indcounter]]), col, row);
outputsize += sizeof(AliHLTCaloTriggerDataStruct);
availableSize += sizeof(AliHLTCaloTriggerDataStruct);
outputdata++;
ntriggers++;
} else if(fRawIndexesSTU[indcounter] >= 0){
ConvertRawDigit(outputdata, &(fSTURawDigitBuffer[fRawIndexesSTU[indcounter]]), col, row);
outputsize += sizeof(AliHLTCaloTriggerDataStruct);
availableSize += sizeof(AliHLTCaloTriggerDataStruct);
outputdata++;
ntriggers++;
}
}
return outputsize;
}
void AliHLTEMCALTriggerDataMakerComponent::CombineTRUSTUDigit(
AliHLTCaloTriggerRawDigitDataStruct &target,
const AliHLTCaloTriggerRawDigitDataStruct &trudigit,
const AliHLTCaloTriggerRawDigitDataStruct &studigit){
AliHLTCaloTriggerRawDigitDataStruct merged;
target.fID = trudigit.fID;
target.fNTimeSamples = trudigit.fNTimeSamples;
memcpy(target.fTimeSamples, trudigit.fTimeSamples, sizeof(target.fTimeSamples));
target.fNL0Times = trudigit.fNL0Times;
memcpy(target.fL0Times, trudigit.fL0Times, sizeof(target.fL0Times));
target.fL1TimeSum = studigit.fL1TimeSum;
target.fTriggerBits = trudigit.fTriggerBits | studigit.fTriggerBits;
}
void AliHLTEMCALTriggerDataMakerComponent::Reset(){
for(Short_t iter = 0; iter < kMaxChannels; iter++){
fRawIndexesTRU[iter] = -1;
fRawIndexesSTU[iter] = -1;
}
fNRawDigitsTRU = 0;
fNRawDigitsSTU = 0;
fMaxChannel = 0;
}
void AliHLTEMCALTriggerDataMakerComponent::ConvertRawDigit(AliHLTCaloTriggerDataStruct *target, const AliHLTCaloTriggerRawDigitDataStruct *source, Int_t col, Int_t row) {
target->fCol = col;
target->fRow = row;
Int_t amplitude, time;
GetRawDigitMaximumAmplitude(*source, amplitude, time);
target->fAmplitude = static_cast<Float_t>(amplitude);
target->fTime = static_cast<Float_t>(time);
target->fL1TimeSum = source->fL1TimeSum;
target->fNL0Times = source->fNL0Times;
memcpy(target->fL0Times, source->fL0Times, sizeof(UChar_t) * 10);
target->fTriggerBits = source->fTriggerBits;
}
<commit_msg>Fix incorrect buffer size calculation in EMCAL TriggerDataMaker<commit_after>/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: Markus Fasel *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliHLTCaloTriggerDataStruct.h"
#include "AliHLTCaloTriggerHeaderStruct.h"
#include "AliHLTCaloTriggerRawDigitDataStruct.h"
#include "AliEMCALTriggerSTURawStream.h"
#include "AliHLTEMCALDefinitions.h"
#include "AliHLTEMCALGeometry.h"
#include "AliHLTEMCALTriggerDataMakerComponent.h"
ClassImp(AliHLTEMCALTriggerDataMakerComponent)
AliHLTEMCALTriggerDataMakerComponent::AliHLTEMCALTriggerDataMakerComponent():
AliHLTCaloProcessor(),
AliHLTCaloConstantsHandler("EMCAL"),
fGeometry(NULL),
fSTUHeader(),
fNRawDigitsTRU(0),
fNRawDigitsSTU(0),
fMaxChannel(0)
{
for(Short_t iter = 0; iter < kMaxChannels; iter++){
fRawIndexesTRU[iter] = -1;
fRawIndexesSTU[iter] = -1;
}
}
AliHLTEMCALTriggerDataMakerComponent::~AliHLTEMCALTriggerDataMakerComponent() {
if(fGeometry) delete fGeometry;
}
int AliHLTEMCALTriggerDataMakerComponent::DoInit(int argc, const char **argv){
fGeometry = new AliHLTEMCALGeometry(GetRunNo());
return 0;
}
int AliHLTEMCALTriggerDataMakerComponent::DoDeinit(){
if(fGeometry) delete fGeometry;
fGeometry = NULL;
return 0;
}
const char* AliHLTEMCALTriggerDataMakerComponent::GetComponentID(){
return "EmcalTriggerDataMaker";
}
void AliHLTEMCALTriggerDataMakerComponent::GetInputDataTypes( std::vector <AliHLTComponentDataType>& list){
list.clear();
list.push_back( AliHLTEMCALDefinitions::fgkTriggerRawDigitDataType | kAliHLTDataOriginEMCAL );
list.push_back( AliHLTEMCALDefinitions::fgkTriggerSTUDataType | kAliHLTDataOriginEMCAL );
}
AliHLTComponentDataType AliHLTEMCALTriggerDataMakerComponent::GetOutputDataType(){
return kAliHLTDataTypeCaloTrigger | kAliHLTDataOriginEMCAL;
}
void AliHLTEMCALTriggerDataMakerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier){
constBase = sizeof(AliHLTCaloTriggerHeaderStruct);
inputMultiplier = 1.5;
}
AliHLTComponent* AliHLTEMCALTriggerDataMakerComponent::Spawn(){
return new AliHLTEMCALTriggerDataMakerComponent;
}
bool AliHLTEMCALTriggerDataMakerComponent::CheckInputDataType(const AliHLTComponentDataType &datatype) {
//comment
vector <AliHLTComponentDataType> validTypes;
GetInputDataTypes(validTypes);
for(UInt_t i=0; i < validTypes.size(); i++) {
if ( datatype == validTypes.at(i) ) {
return true;
}
}
HLTDebug("Invalid Datatype");
return false;
}
int AliHLTEMCALTriggerDataMakerComponent::DoEvent( const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& trigData, AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size, std::vector<AliHLTComponentBlockData>& outputBlocks ){
if(!IsDataEvent()) {
size = 0;
return 0;
}
UInt_t totSize = 0;
const AliHLTComponentBlockData* iter = NULL;
// Get pointers to output buffer
AliHLTCaloTriggerHeaderStruct *headerPtr = reinterpret_cast<AliHLTCaloTriggerHeaderStruct *>(outputPtr);
AliHLTCaloTriggerDataStruct *dataIter = reinterpret_cast<AliHLTCaloTriggerDataStruct *>(outputPtr + sizeof(AliHLTCaloTriggerHeaderStruct));
totSize += sizeof(AliHLTCaloTriggerHeaderStruct);
Reset();
AliHLTCaloTriggerRawDigitDataStruct *dataptr = NULL;
for(ULong_t ndx = 0; ndx < evtData.fBlockCnt; ndx++){
iter = blocks + ndx;
if(!this->CheckInputDataType(iter->fDataType)){
continue;
}
if(iter->fDataType == AliHLTEMCALDefinitions::fgkTriggerRawDigitDataType){
// Handle TRU data
Int_t ndigits = iter->fSize / sizeof(AliHLTCaloTriggerRawDigitDataStruct);
HLTDebug("Data containing %d TRU digits", ndigits);
dataptr = reinterpret_cast<AliHLTCaloTriggerRawDigitDataStruct *>(iter->fPtr);
ReadTRUData(ndigits, dataptr);
} else if(iter->fDataType == AliHLTEMCALDefinitions::fgkTriggerSTUDataType){
// Handle STU data
AliHLTEMCALSTUHeaderStruct *stuheader = reinterpret_cast<AliHLTEMCALSTUHeaderStruct *>(iter->fPtr);
AliHLTInt32_t sizeExpected = sizeof(AliHLTEMCALSTUHeaderStruct) + sizeof(AliHLTCaloTriggerRawDigitDataStruct) * stuheader->fNRawDigits;
if(iter->fSize != sizeExpected){
HLTWarning("STU-reader: Size of the input buffer not matching for amount of digits, expected %d, obtained %d", sizeExpected, iter->fSize);
continue;
}
dataptr = reinterpret_cast<AliHLTCaloTriggerRawDigitDataStruct *>(reinterpret_cast<AliHLTUInt8_t*>(iter->fPtr) + sizeof(AliHLTEMCALSTUHeaderStruct));
HLTDebug("Data containing %d STU digits", stuheader->fNRawDigits);
ReadSTUData(stuheader, dataptr);
}
}
// Write header
memcpy(headerPtr->fL1Threshold, fSTUHeader.fL1Threshold, sizeof(Int_t) *4);
memcpy(headerPtr->fL1V0, fSTUHeader.fL1V0, sizeof(Int_t) * 2);
headerPtr->fL1FrameMask = fSTUHeader.fL1FrameMask;
AliHLTUInt32_t availableSize = size - sizeof(AliHLTCaloTriggerHeaderStruct);
// Write data
Int_t dataSize = MakeTriggerData(dataIter, availableSize);
totSize += dataSize;
headerPtr->fNfastor = dataSize / sizeof(AliHLTCaloTriggerDataStruct);
AliHLTComponentBlockData bdChannelData;
FillBlockData( bdChannelData );
bdChannelData.fOffset = 0; //FIXME
bdChannelData.fSize = totSize;
bdChannelData.fDataType = GetOutputDataType();
outputBlocks.push_back(bdChannelData);
outputPtr += totSize; //Updating position of the output buffer
size = totSize;
return 0;
}
void AliHLTEMCALTriggerDataMakerComponent::ReadSTUData(AliHLTEMCALSTUHeaderStruct *headerptr, AliHLTCaloTriggerRawDigitDataStruct *dataptr){
fSTUHeader = *headerptr;
for(UShort_t idig = 0; idig < headerptr->fNRawDigits; idig++){
if(dataptr->fID > kMaxChannels || dataptr->fID < 0){
HLTWarning("Invalid TRU index: %d", dataptr->fID);
dataptr++;
continue;
}
fRawIndexesSTU[dataptr->fID] = fNRawDigitsSTU;
if(dataptr->fID > fMaxChannel) fMaxChannel = dataptr->fID;
fSTURawDigitBuffer[fNRawDigitsSTU] = *dataptr;
dataptr++;
fNRawDigitsSTU++;
}
HLTDebug("Successfully read in %d STU digits", fNRawDigitsSTU);
}
void AliHLTEMCALTriggerDataMakerComponent::ReadTRUData(UShort_t ndigits, AliHLTCaloTriggerRawDigitDataStruct *triggerdata){
for(UShort_t idig = 0; idig < ndigits; idig++){
fRawIndexesTRU[triggerdata->fID] = fNRawDigitsTRU;
if(triggerdata->fID > fMaxChannel) fMaxChannel = triggerdata->fID;
fTRURawDigitBuffer[fNRawDigitsTRU] = *triggerdata;
triggerdata++;
fNRawDigitsTRU++;
}
HLTDebug("Successfully read in %d TRU digits", fNRawDigitsTRU);
}
Int_t AliHLTEMCALTriggerDataMakerComponent::MakeTriggerData(AliHLTCaloTriggerDataStruct *outputdata, AliHLTUInt32_t &availableSize) {
if(availableSize < sizeof(AliHLTCaloTriggerDataStruct)){
HLTWarning("Not enough space in buffer to write triggers");
return 0;
}
Int_t outputsize = 0, col = 0, row = 0, ntriggers = 0 ;
AliHLTCaloTriggerRawDigitDataStruct tmpdigit;
for(UShort_t indcounter = 0; indcounter <= fMaxChannel; indcounter++){
if(availableSize < sizeof(AliHLTCaloTriggerDataStruct)){
HLTWarning("Buffer exceeded after %d triggers", ntriggers);
break;
}
fGeometry->GetGeometryPtr()->GetPositionInEMCALFromAbsFastORIndex(indcounter, col, row);
if(fRawIndexesTRU[indcounter] >= 0 && fRawIndexesSTU[indcounter] >=0){
CombineTRUSTUDigit(tmpdigit, fTRURawDigitBuffer[fRawIndexesTRU[indcounter]], fSTURawDigitBuffer[fRawIndexesSTU[indcounter]]);
ConvertRawDigit(outputdata, &tmpdigit, col, row);
outputsize += sizeof(AliHLTCaloTriggerDataStruct);
availableSize -= sizeof(AliHLTCaloTriggerDataStruct);
outputdata++;
ntriggers++;
} else if(fRawIndexesTRU[indcounter] >= 0){
ConvertRawDigit(outputdata, &(fTRURawDigitBuffer[fRawIndexesTRU[indcounter]]), col, row);
outputsize += sizeof(AliHLTCaloTriggerDataStruct);
availableSize -= sizeof(AliHLTCaloTriggerDataStruct);
outputdata++;
ntriggers++;
} else if(fRawIndexesSTU[indcounter] >= 0){
ConvertRawDigit(outputdata, &(fSTURawDigitBuffer[fRawIndexesSTU[indcounter]]), col, row);
outputsize += sizeof(AliHLTCaloTriggerDataStruct);
availableSize -= sizeof(AliHLTCaloTriggerDataStruct);
outputdata++;
ntriggers++;
}
}
return outputsize;
}
void AliHLTEMCALTriggerDataMakerComponent::CombineTRUSTUDigit(
AliHLTCaloTriggerRawDigitDataStruct &target,
const AliHLTCaloTriggerRawDigitDataStruct &trudigit,
const AliHLTCaloTriggerRawDigitDataStruct &studigit){
AliHLTCaloTriggerRawDigitDataStruct merged;
target.fID = trudigit.fID;
target.fNTimeSamples = trudigit.fNTimeSamples;
memcpy(target.fTimeSamples, trudigit.fTimeSamples, sizeof(target.fTimeSamples));
target.fNL0Times = trudigit.fNL0Times;
memcpy(target.fL0Times, trudigit.fL0Times, sizeof(target.fL0Times));
target.fL1TimeSum = studigit.fL1TimeSum;
target.fTriggerBits = trudigit.fTriggerBits | studigit.fTriggerBits;
}
void AliHLTEMCALTriggerDataMakerComponent::Reset(){
for(Short_t iter = 0; iter < kMaxChannels; iter++){
fRawIndexesTRU[iter] = -1;
fRawIndexesSTU[iter] = -1;
}
fNRawDigitsTRU = 0;
fNRawDigitsSTU = 0;
fMaxChannel = 0;
}
void AliHLTEMCALTriggerDataMakerComponent::ConvertRawDigit(AliHLTCaloTriggerDataStruct *target, const AliHLTCaloTriggerRawDigitDataStruct *source, Int_t col, Int_t row) {
target->fCol = col;
target->fRow = row;
Int_t amplitude, time;
GetRawDigitMaximumAmplitude(*source, amplitude, time);
target->fAmplitude = static_cast<Float_t>(amplitude);
target->fTime = static_cast<Float_t>(time);
target->fL1TimeSum = source->fL1TimeSum;
target->fNL0Times = source->fNL0Times;
memcpy(target->fL0Times, source->fL0Times, sizeof(UChar_t) * 10);
target->fTriggerBits = source->fTriggerBits;
}
<|endoftext|>
|
<commit_before>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
#ifndef __RD_SDL_SCREEN_MANAGER_HPP__
#define __RD_SDL_SCREEN_MANAGER_HPP__
#include <string>
#include <vector>
#include <map>
#include <SDL.h>
#include <yarp/os/Mutex.h> //-- Right now use yarp mutex. In the future is better to use C++11 std::mutex
#include "ScreenManager.hpp"
#include "Screen.hpp"
#include "ImageManager.hpp"
#include "Player.hpp"
#include "Target.hpp"
#include "Weapon.hpp"
namespace rd{
/**
* @ingroup UserInterfaceLib
*
* @brief Manage game screens using SDL libraries
*
*/
class SDLScreenManager : public ScreenManager
{
public:
//------------------------------- Screen Manager functions -----------------------------------------------------//
//! @brief Set a Screen as current Screen
virtual void setCurrentScreen(Screen* screen);
//! @brief Display the current Screen on the game window
virtual bool show();
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, const std::string & value);
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, Image value); //-- Required by GameScreen and DeadScreen
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, Player value); //-- Required by GameScreen
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, const std::vector<Player> & value); //-- Required by GameScreen
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, const std::vector<Target> & value); //-- Required by GameScreen
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, Weapon value); //-- Required by GameScreen
//! @brief SDL initialization
static bool initSDL();
//! @brief SDL Cleanup
static bool cleanupSDL();
//------------------------------ Configuration ----------------------------------------------------------------//
//! @brief Configures a parameter with a value
virtual bool configure(const std::string & parameter, const std::string & value);
static const std::string PARAM_FULLSCREEN;
//---------------- Manager Stuff ----------------------------------------------------------------------//
virtual bool start();
virtual bool stop();
virtual bool isStopped() const;
/**
* @brief Register this manager in the ScreenManager registry so that can be used
*
* It ensures that only one manager of this type is created (unique instance)
*/
static bool RegisterManager();
//! @brief Destructor. Used to reset the local static reference after destroying this manager
virtual ~SDLScreenManager();
//! @brief String that identifies this manager
static const std::string id;
private:
/**
* @brief Constructor
*
* Constructor for this class is private, since the singleton can only be instantiated once,
* and the instantiation is done at the getScreenManager() method
*/
SDLScreenManager();
//! \brief Stores the unique instance of the SDLScreenManager
static SDLScreenManager * uniqueInstance;
bool stopped;
bool sdl_initialized;
bool fullscreen;
SDL_Window * window;
yarp::os::Mutex mutex;
};
}
#endif //-- __RD_SDL_SCREEN_MANAGER_HPP__
<commit_msg>Declare rd::SDLScreenManager::mutex as mutable<commit_after>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
#ifndef __RD_SDL_SCREEN_MANAGER_HPP__
#define __RD_SDL_SCREEN_MANAGER_HPP__
#include <string>
#include <vector>
#include <map>
#include <SDL.h>
#include <yarp/os/Mutex.h> //-- Right now use yarp mutex. In the future is better to use C++11 std::mutex
#include "ScreenManager.hpp"
#include "Screen.hpp"
#include "ImageManager.hpp"
#include "Player.hpp"
#include "Target.hpp"
#include "Weapon.hpp"
namespace rd{
/**
* @ingroup UserInterfaceLib
*
* @brief Manage game screens using SDL libraries
*
*/
class SDLScreenManager : public ScreenManager
{
public:
//------------------------------- Screen Manager functions -----------------------------------------------------//
//! @brief Set a Screen as current Screen
virtual void setCurrentScreen(Screen* screen);
//! @brief Display the current Screen on the game window
virtual bool show();
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, const std::string & value);
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, Image value); //-- Required by GameScreen and DeadScreen
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, Player value); //-- Required by GameScreen
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, const std::vector<Player> & value); //-- Required by GameScreen
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, const std::vector<Target> & value); //-- Required by GameScreen
//! @brief Update some Screen parameter through the ScreenManager
virtual bool update(const std::string & parameter, Weapon value); //-- Required by GameScreen
//! @brief SDL initialization
static bool initSDL();
//! @brief SDL Cleanup
static bool cleanupSDL();
//------------------------------ Configuration ----------------------------------------------------------------//
//! @brief Configures a parameter with a value
virtual bool configure(const std::string & parameter, const std::string & value);
static const std::string PARAM_FULLSCREEN;
//---------------- Manager Stuff ----------------------------------------------------------------------//
virtual bool start();
virtual bool stop();
virtual bool isStopped() const;
/**
* @brief Register this manager in the ScreenManager registry so that can be used
*
* It ensures that only one manager of this type is created (unique instance)
*/
static bool RegisterManager();
//! @brief Destructor. Used to reset the local static reference after destroying this manager
virtual ~SDLScreenManager();
//! @brief String that identifies this manager
static const std::string id;
private:
/**
* @brief Constructor
*
* Constructor for this class is private, since the singleton can only be instantiated once,
* and the instantiation is done at the getScreenManager() method
*/
SDLScreenManager();
//! \brief Stores the unique instance of the SDLScreenManager
static SDLScreenManager * uniqueInstance;
bool stopped;
bool sdl_initialized;
bool fullscreen;
SDL_Window * window;
mutable yarp::os::Mutex mutex;
};
}
#endif //-- __RD_SDL_SCREEN_MANAGER_HPP__
<|endoftext|>
|
<commit_before>
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <glibmm/random.h>
#include <glibmm/timer.h>
#include <glibmm/init.h>
namespace
{
class MessageQueue
{
public:
MessageQueue();
~MessageQueue();
void producer();
void consumer();
private:
std::mutex mutex_;
std::condition_variable cond_push_;
std::condition_variable cond_pop_;
std::queue<int> queue_;
};
MessageQueue::MessageQueue()
{}
MessageQueue::~MessageQueue()
{}
void MessageQueue::producer()
{
Glib::Rand rand (1234);
for(auto i = 0; i < 200; ++i)
{
{
std::unique_lock<std::mutex> lock (mutex_);
cond_pop_.wait(lock,
[this] () -> bool
{
return queue_.size() < 64;
});
queue_.push(i);
std::cout << '*';
std::cout.flush();
//We unlock before notifying, because that is what the documentation suggests:
//http://en.cppreference.com/w/cpp/thread/condition_variable
lock.unlock();
cond_push_.notify_one();
}
if(rand.get_bool())
continue;
Glib::usleep(rand.get_int_range(0, 100000));
}
}
void MessageQueue::consumer()
{
Glib::Rand rand (4567);
for(;;)
{
{
std::unique_lock<std::mutex> lock (mutex_);
cond_push_.wait(lock,
[this] () -> bool
{
return !queue_.empty();
});
const int i = queue_.front();
queue_.pop();
std::cout << "\x08 \x08";
std::cout.flush();
//We unlock before notifying, because that is what the documentation suggests:
//http://en.cppreference.com/w/cpp/thread/condition_variable
lock.unlock();
cond_pop_.notify_one();
if(i >= 199)
break;
}
if(rand.get_bool())
continue;
Glib::usleep(rand.get_int_range(10000, 200000));
}
}
}
int main(int, char**)
{
Glib::init();
MessageQueue queue;
auto *const producer = new std::thread(
[&queue] ()
{
queue.producer();
});
auto *const consumer = new std::thread(
[&queue] ()
{
queue.consumer();
});
producer->join();
delete producer;
consumer->join();
delete consumer;
std::cout << std::endl;
return 0;
}
<commit_msg>thread example: Use std::unique_ptr<> with std::thread.<commit_after>
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <glibmm/random.h>
#include <glibmm/timer.h>
#include <glibmm/init.h>
namespace
{
class MessageQueue
{
public:
MessageQueue();
~MessageQueue();
void producer();
void consumer();
private:
std::mutex mutex_;
std::condition_variable cond_push_;
std::condition_variable cond_pop_;
std::queue<int> queue_;
};
MessageQueue::MessageQueue()
{}
MessageQueue::~MessageQueue()
{}
void MessageQueue::producer()
{
Glib::Rand rand (1234);
for(auto i = 0; i < 200; ++i)
{
{
std::unique_lock<std::mutex> lock (mutex_);
cond_pop_.wait(lock,
[this] () -> bool
{
return queue_.size() < 64;
});
queue_.push(i);
std::cout << '*';
std::cout.flush();
//We unlock before notifying, because that is what the documentation suggests:
//http://en.cppreference.com/w/cpp/thread/condition_variable
lock.unlock();
cond_push_.notify_one();
}
if(rand.get_bool())
continue;
Glib::usleep(rand.get_int_range(0, 100000));
}
}
void MessageQueue::consumer()
{
Glib::Rand rand (4567);
for(;;)
{
{
std::unique_lock<std::mutex> lock (mutex_);
cond_push_.wait(lock,
[this] () -> bool
{
return !queue_.empty();
});
const int i = queue_.front();
queue_.pop();
std::cout << "\x08 \x08";
std::cout.flush();
//We unlock before notifying, because that is what the documentation suggests:
//http://en.cppreference.com/w/cpp/thread/condition_variable
lock.unlock();
cond_pop_.notify_one();
if(i >= 199)
break;
}
if(rand.get_bool())
continue;
Glib::usleep(rand.get_int_range(10000, 200000));
}
}
}
int main(int, char**)
{
Glib::init();
MessageQueue queue;
//TODO: Use std::make_unique() when we use C++14:
const auto producer = std::unique_ptr<std::thread>(new std::thread(
[&queue] ()
{
queue.producer();
}));
const auto consumer = std::unique_ptr<std::thread>(new std::thread(
[&queue] ()
{
queue.consumer();
}));
producer->join();
consumer->join();
std::cout << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: TKeyColumns.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: oj $ $Date: 2002-10-25 09:01:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONNECTIVITY_TKEYCOLUMNS_HXX
#include "connectivity/TKeyColumns.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_KEYCOLUMN_HXX_
#include "connectivity/sdbcx/VKeyColumn.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef CONNECTIVITY_TABLEHELPER_HXX
#include "connectivity/TTableHelper.hxx"
#endif
using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -------------------------------------------------------------------------
OKeyColumnsHelper::OKeyColumnsHelper( OTableKeyHelper* _pKey,
::osl::Mutex& _rMutex,
const ::std::vector< ::rtl::OUString> &_rVector)
: connectivity::sdbcx::OCollection(*_pKey,sal_True,_rMutex,_rVector)
,m_pKey(_pKey)
{
}
// -------------------------------------------------------------------------
Reference< XNamed > OKeyColumnsHelper::createObject(const ::rtl::OUString& _rName)
{
::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
::rtl::OUString aSchema,aTable;
m_pKey->getTable()->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) >>= aSchema;
m_pKey->getTable()->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) >>= aTable;
// frist get the related column to _rName
Reference< XResultSet > xResult = m_pKey->getTable()->getMetaData()->getImportedKeys(
m_pKey->getTable()->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME)),aSchema,aTable);
::rtl::OUString aRefColumnName;
if ( xResult.is() )
{
Reference< XRow > xRow(xResult,UNO_QUERY);
::rtl::OUString aTemp;
while(xResult->next())
{
aTemp = xRow->getString(4);
if(xRow->getString(8) == _rName && m_pKey->getName() == xRow->getString(12))
{
aRefColumnName = aTemp;
break;
}
}
}
Reference< XNamed > xRet;
// now describe the column _rName and set his related column
xResult = m_pKey->getTable()->getMetaData()->getColumns(
m_pKey->getTable()->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME)),aSchema,aTable,_rName);
if ( xResult.is() )
{
Reference< XRow > xRow(xResult,UNO_QUERY);
if ( xResult->next() )
{
if ( xRow->getString(4) == _rName )
{
sal_Int32 nDataType = xRow->getInt(5);
::rtl::OUString aTypeName(xRow->getString(6));
sal_Int32 nSize = xRow->getInt(7);
sal_Int32 nDec = xRow->getInt(9);
sal_Int32 nNull = xRow->getInt(11);
::rtl::OUString sColumnDef;
try
{
sColumnDef = xRow->getString(13);
}
catch(const SQLException&)
{
// somethimes we get an error when asking for this param
}
OKeyColumn* pRet = new OKeyColumn(aRefColumnName,
_rName,
aTypeName,
sColumnDef,
nNull,
nSize,
nDec,
nDataType,
sal_False,
sal_False,
sal_False,
isCaseSensitive());
xRet = pRet;
}
}
}
return xRet;
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OKeyColumnsHelper::createEmptyObject()
{
return new OKeyColumn(isCaseSensitive());
}
// -------------------------------------------------------------------------
void OKeyColumnsHelper::impl_refresh() throw(::com::sun::star::uno::RuntimeException)
{
m_pKey->refreshColumns();
}
// -----------------------------------------------------------------------------
Reference< XNamed > OKeyColumnsHelper::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
OKeyColumn* pColumn = new OKeyColumn(isCaseSensitive());
Reference<XPropertySet> xProp = pColumn;
::comphelper::copyProperties(_xDescriptor,xProp);
Reference< XNamed > xName(xProp,UNO_QUERY);
OSL_ENSURE(xName.is(),"Must be a XName interface here !");
return xName;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba24 (1.1.240); FILE MERGED 2005/02/09 08:07:35 oj 1.1.240.1: #i26950# remove the need for XNamed<commit_after>/*************************************************************************
*
* $RCSfile: TKeyColumns.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2005-03-10 15:18:01 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONNECTIVITY_TKEYCOLUMNS_HXX
#include "connectivity/TKeyColumns.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_KEYCOLUMN_HXX_
#include "connectivity/sdbcx/VKeyColumn.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef CONNECTIVITY_TABLEHELPER_HXX
#include "connectivity/TTableHelper.hxx"
#endif
using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -------------------------------------------------------------------------
OKeyColumnsHelper::OKeyColumnsHelper( OTableKeyHelper* _pKey,
::osl::Mutex& _rMutex,
const ::std::vector< ::rtl::OUString> &_rVector)
: connectivity::sdbcx::OCollection(*_pKey,sal_True,_rMutex,_rVector)
,m_pKey(_pKey)
{
}
// -------------------------------------------------------------------------
sdbcx::ObjectType OKeyColumnsHelper::createObject(const ::rtl::OUString& _rName)
{
::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
::rtl::OUString aSchema,aTable;
m_pKey->getTable()->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) >>= aSchema;
m_pKey->getTable()->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) >>= aTable;
// frist get the related column to _rName
Reference< XResultSet > xResult = m_pKey->getTable()->getMetaData()->getImportedKeys(
m_pKey->getTable()->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME)),aSchema,aTable);
::rtl::OUString aRefColumnName;
if ( xResult.is() )
{
Reference< XRow > xRow(xResult,UNO_QUERY);
::rtl::OUString aTemp;
while(xResult->next())
{
aTemp = xRow->getString(4);
if(xRow->getString(8) == _rName && m_pKey->getName() == xRow->getString(12))
{
aRefColumnName = aTemp;
break;
}
}
}
sdbcx::ObjectType xRet;
// now describe the column _rName and set his related column
xResult = m_pKey->getTable()->getMetaData()->getColumns(
m_pKey->getTable()->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME)),aSchema,aTable,_rName);
if ( xResult.is() )
{
Reference< XRow > xRow(xResult,UNO_QUERY);
if ( xResult->next() )
{
if ( xRow->getString(4) == _rName )
{
sal_Int32 nDataType = xRow->getInt(5);
::rtl::OUString aTypeName(xRow->getString(6));
sal_Int32 nSize = xRow->getInt(7);
sal_Int32 nDec = xRow->getInt(9);
sal_Int32 nNull = xRow->getInt(11);
::rtl::OUString sColumnDef;
try
{
sColumnDef = xRow->getString(13);
}
catch(const SQLException&)
{
// somethimes we get an error when asking for this param
}
OKeyColumn* pRet = new OKeyColumn(aRefColumnName,
_rName,
aTypeName,
sColumnDef,
nNull,
nSize,
nDec,
nDataType,
sal_False,
sal_False,
sal_False,
isCaseSensitive());
xRet = pRet;
}
}
}
return xRet;
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OKeyColumnsHelper::createEmptyObject()
{
return new OKeyColumn(isCaseSensitive());
}
// -------------------------------------------------------------------------
void OKeyColumnsHelper::impl_refresh() throw(::com::sun::star::uno::RuntimeException)
{
m_pKey->refreshColumns();
}
// -----------------------------------------------------------------------------
sdbcx::ObjectType OKeyColumnsHelper::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
Reference<XPropertySet> xProp = new OKeyColumn(isCaseSensitive());
::comphelper::copyProperties(_xDescriptor,xProp);
return xProp;
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: process.cpp
// Purpose: Implementation of class wxExProcess
// Author: Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/utils.h> // for wxGetEnv
#include <wx/extension/process.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/shell.h>
#include <wx/extension/util.h> // for wxExConfigFirstOf
BEGIN_EVENT_TABLE(wxExProcess, wxProcess)
EVT_MENU(ID_SHELL_COMMAND, wxExProcess::OnCommand)
EVT_MENU(ID_SHELL_COMMAND_STOP, wxExProcess::OnCommand)
EVT_TIMER(-1, wxExProcess::OnTimer)
END_EVENT_TABLE()
wxExSTCEntryDialog* wxExProcess::m_Dialog = NULL;
wxString wxExProcess::m_WorkingDirKey = _("Process folder");
wxExProcess::wxExProcess()
: wxProcess(wxPROCESS_REDIRECT)
, m_Timer(new wxTimer(this))
, m_Busy(false)
, m_Error(false)
, m_Sync(false)
{
m_Command = wxExConfigFirstOf(_("Process"));
}
wxExProcess::~wxExProcess()
{
delete m_Timer;
}
wxExProcess::wxExProcess(const wxExProcess& process)
{
*this = process;
}
wxExProcess& wxExProcess::operator=(const wxExProcess& p)
{
m_Busy = p.m_Busy;
m_Error = p.m_Error;
m_Output = p.m_Output;
m_Sync = p.m_Sync;
m_Timer = new wxTimer(this);
return *this;
}
bool wxExProcess::CheckInput()
{
if (m_Busy)
{
return false;
}
m_Busy = true;
wxString output;
if (IsInputAvailable())
{
wxTextInputStream tis(*GetInputStream());
while (IsInputAvailable())
{
const wxChar c = tis.GetChar();
if (c != 0)
{
output << c;
}
}
}
if (IsErrorAvailable())
{
wxTextInputStream tis(*GetErrorStream());
while (IsErrorAvailable())
{
const wxChar c = tis.GetChar();
if (c != 0)
{
output << c;
}
}
}
m_Busy = false;
if (!output.empty())
{
m_Dialog->GetSTCShell()->AddText(output);
return true;
}
else
{
return false;
}
}
int wxExProcess::ConfigDialog(
wxWindow* parent,
const wxString& title,
bool modal)
{
std::vector<wxExConfigItem> v;
v.push_back(wxExConfigItem(
_("Process"),
CONFIG_COMBOBOX,
wxEmptyString,
true));
v.push_back(wxExConfigItem(
m_WorkingDirKey,
CONFIG_COMBOBOXDIR,
wxEmptyString,
true,
1000));
if (modal)
{
return wxExConfigDialog(parent,
v,
title).ShowModal();
}
else
{
wxExConfigDialog* dlg = new wxExConfigDialog(
parent,
v,
title);
return dlg->Show();
}
}
bool wxExProcess::Execute(
const wxString& command_to_execute,
int flags,
const wxString& wd)
{
m_Error = false;
struct wxExecuteEnv env;
if (command_to_execute.empty())
{
if (wxExConfigFirstOf(_("Process")).empty())
{
if (ConfigDialog(wxTheApp->GetTopWindow()) == wxID_CANCEL)
{
return false;
}
}
m_Command = wxExConfigFirstOf(_("Process"));
env.cwd = wxExConfigFirstOf(m_WorkingDirKey);
}
else
{
m_Command = command_to_execute;
env.cwd = wd;
}
m_Sync = (flags & wxEXEC_SYNC);
// Construct the dialog.
// This is necessary both in sync and async mode,
// as for sync mode the dialog is used for presenting the
// output member.
if (m_Dialog == NULL)
{
m_Dialog = new wxExSTCEntryDialog(
wxTheApp->GetTopWindow(),
wxEmptyString,
wxEmptyString,
wxEmptyString,
wxOK,
true); // use_shell to force STCShell
m_Dialog->SetProcess(this);
m_Dialog->GetSTCShell()->SetEventHandler(this);
}
m_Dialog->GetSTCShell()->EnableShell(!m_Sync);
if (!m_Sync)
{
m_Dialog->SetTitle(m_Command);
m_Dialog->GetSTCShell()->ClearAll();
// If we have entered a shell, then the shell
// itself has no prompt. So put one here.
if (m_Command == "bash" ||
m_Command == "csh" ||
m_Command == "ksh" ||
m_Command == "tcsh" ||
m_Command == "sh")
{
wxString host;
wxGetEnv("HOST", &host);
m_Dialog->GetSTCShell()->SetPrompt(host + ">");
}
else
{
m_Dialog->GetSTCShell()->SetPrompt("");
}
// For asynchronous execution the return value is the process id and zero
// value indicates that the command could not be executed.
if (wxExecute(m_Command, flags, this, &env) > 0)
{
m_Dialog->Show();
if (!CheckInput())
{
m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);
}
m_Timer->Start(100); // each 100 milliseconds
}
else
{
m_Dialog->Hide();
m_Error = true;
}
}
else
{
wxArrayString output;
wxArrayString errors;
// Call wxExecute to execute the command and
// collect the output and the errors.
if (wxExecute(
m_Command,
output,
errors,
flags,
&env) == -1)
{
m_Output.clear();
m_Error = true;
}
else
{
// Set output by converting array strings into normal strings.
m_Output = wxJoin(errors, '\n', '\n') + wxJoin(output, '\n', '\n');
}
}
return !m_Error;
}
bool wxExProcess::IsRunning() const
{
if (
// If we executed a sync process, then it always ended,
// so it is not running.
m_Sync ||
GetPid() <= 0)
{
return false;
}
return Exists(GetPid());
}
wxKillError wxExProcess::Kill(wxSignal sig)
{
if (!IsRunning())
{
return wxKILL_NO_PROCESS;
}
const wxKillError result = wxProcess::Kill(GetPid(), sig);
switch (result)
{
case wxKILL_OK:
wxLogStatus(_("Stopped"));
DeletePendingEvents();
m_Timer->Stop();
m_Dialog->Hide();
break;
case wxKILL_BAD_SIGNAL:
wxLogStatus("no such signal");
break;
case wxKILL_ACCESS_DENIED:
wxLogStatus("permission denied");
break;
case wxKILL_NO_PROCESS:
wxLogStatus("no such process");
break;
case wxKILL_ERROR:
wxLogStatus("another, unspecified error");
break;
default: wxFAIL;
}
return result;
}
void wxExProcess::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case ID_SHELL_COMMAND:
m_Timer->Stop();
m_Dialog->GetSTCShell()->LineEnd();
m_Dialog->GetSTCShell()->AddText(m_Dialog->GetSTCShell()->GetEOL());
if (IsRunning())
{
// send command to process
wxOutputStream* os = GetOutputStream();
if (os != NULL)
{
wxTextOutputStream os(*GetOutputStream());
os.WriteString(event.GetString() + "\n");
}
if (CheckInput())
{
m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);
}
m_Timer->Start();
}
else
{
wxLogStatus("Process is not running");
}
break;
case ID_SHELL_COMMAND_STOP:
if (IsRunning())
{
Kill();
}
break;
default: wxFAIL; break;
}
}
void wxExProcess::OnTerminate(int pid, int status)
{
m_Timer->Stop();
wxLogStatus(_("Ready"));
wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);
wxPostEvent(wxTheApp->GetTopWindow(), event);
// Collect remaining input.
CheckInput();
}
void wxExProcess::OnTimer(wxTimerEvent& event)
{
CheckInput();
}
#if wxUSE_GUI
void wxExProcess::ShowOutput(const wxString& caption) const
{
if (!m_Sync)
{
wxLogStatus("Output only available for sync processes");
}
else if (!m_Error)
{
if (m_Dialog != NULL)
{
m_Dialog->GetSTC()->SetText(m_Output);
m_Dialog->SetTitle(caption.empty() ? m_Command: caption);
m_Dialog->Show();
}
else if (!m_Output.empty())
{
wxLogMessage(m_Output);
}
else
{
wxLogStatus("No output available");
}
}
else
{
// Executing command failed, so no output,
// show failing command.
wxLogError("Could not execute: " + m_Command);
}
}
#endif
<commit_msg>cmd starts answer starts with cr lf<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: process.cpp
// Purpose: Implementation of class wxExProcess
// Author: Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/utils.h> // for wxGetEnv
#include <wx/extension/process.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/shell.h>
#include <wx/extension/util.h> // for wxExConfigFirstOf
BEGIN_EVENT_TABLE(wxExProcess, wxProcess)
EVT_MENU(ID_SHELL_COMMAND, wxExProcess::OnCommand)
EVT_MENU(ID_SHELL_COMMAND_STOP, wxExProcess::OnCommand)
EVT_TIMER(-1, wxExProcess::OnTimer)
END_EVENT_TABLE()
wxExSTCEntryDialog* wxExProcess::m_Dialog = NULL;
wxString wxExProcess::m_WorkingDirKey = _("Process folder");
wxExProcess::wxExProcess()
: wxProcess(wxPROCESS_REDIRECT)
, m_Timer(new wxTimer(this))
, m_Busy(false)
, m_Error(false)
, m_Sync(false)
{
m_Command = wxExConfigFirstOf(_("Process"));
}
wxExProcess::~wxExProcess()
{
delete m_Timer;
}
wxExProcess::wxExProcess(const wxExProcess& process)
{
*this = process;
}
wxExProcess& wxExProcess::operator=(const wxExProcess& p)
{
m_Busy = p.m_Busy;
m_Error = p.m_Error;
m_Output = p.m_Output;
m_Sync = p.m_Sync;
m_Timer = new wxTimer(this);
return *this;
}
bool wxExProcess::CheckInput()
{
if (m_Busy)
{
return false;
}
m_Busy = true;
wxString output;
if (IsInputAvailable())
{
wxTextInputStream tis(*GetInputStream());
while (IsInputAvailable())
{
const wxChar c = tis.GetChar();
if (c != 0)
{
output << c;
}
}
}
if (IsErrorAvailable())
{
wxTextInputStream tis(*GetErrorStream());
while (IsErrorAvailable())
{
const wxChar c = tis.GetChar();
if (c != 0)
{
output << c;
}
}
}
m_Busy = false;
if (!output.empty())
{
m_Dialog->GetSTCShell()->AddText(output);
return true;
}
else
{
return false;
}
}
int wxExProcess::ConfigDialog(
wxWindow* parent,
const wxString& title,
bool modal)
{
std::vector<wxExConfigItem> v;
v.push_back(wxExConfigItem(
_("Process"),
CONFIG_COMBOBOX,
wxEmptyString,
true));
v.push_back(wxExConfigItem(
m_WorkingDirKey,
CONFIG_COMBOBOXDIR,
wxEmptyString,
true,
1000));
if (modal)
{
return wxExConfigDialog(parent,
v,
title).ShowModal();
}
else
{
wxExConfigDialog* dlg = new wxExConfigDialog(
parent,
v,
title);
return dlg->Show();
}
}
bool wxExProcess::Execute(
const wxString& command_to_execute,
int flags,
const wxString& wd)
{
m_Error = false;
struct wxExecuteEnv env;
if (command_to_execute.empty())
{
if (wxExConfigFirstOf(_("Process")).empty())
{
if (ConfigDialog(wxTheApp->GetTopWindow()) == wxID_CANCEL)
{
return false;
}
}
m_Command = wxExConfigFirstOf(_("Process"));
env.cwd = wxExConfigFirstOf(m_WorkingDirKey);
}
else
{
m_Command = command_to_execute;
env.cwd = wd;
}
m_Sync = (flags & wxEXEC_SYNC);
// Construct the dialog.
// This is necessary both in sync and async mode,
// as for sync mode the dialog is used for presenting the
// output member.
if (m_Dialog == NULL)
{
m_Dialog = new wxExSTCEntryDialog(
wxTheApp->GetTopWindow(),
wxEmptyString,
wxEmptyString,
wxEmptyString,
wxOK,
true); // use_shell to force STCShell
m_Dialog->SetProcess(this);
m_Dialog->GetSTCShell()->SetEventHandler(this);
}
m_Dialog->GetSTCShell()->EnableShell(!m_Sync);
if (!m_Sync)
{
m_Dialog->SetTitle(m_Command);
m_Dialog->GetSTCShell()->ClearAll();
// If we have entered a shell, then the shell
// itself has no prompt. So put one here.
if (m_Command == "bash" ||
m_Command == "csh" ||
m_Command == "ksh" ||
m_Command == "tcsh" ||
m_Command == "sh")
{
wxString host;
wxGetEnv("HOST", &host);
m_Dialog->GetSTCShell()->SetPrompt(host + ">");
}
else
{
m_Dialog->GetSTCShell()->SetPrompt("");
}
// For asynchronous execution the return value is the process id and zero
// value indicates that the command could not be executed.
if (wxExecute(m_Command, flags, this, &env) > 0)
{
m_Dialog->Show();
if (!CheckInput())
{
m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);
}
m_Timer->Start(100); // each 100 milliseconds
}
else
{
m_Dialog->Hide();
m_Error = true;
}
}
else
{
wxArrayString output;
wxArrayString errors;
// Call wxExecute to execute the command and
// collect the output and the errors.
if (wxExecute(
m_Command,
output,
errors,
flags,
&env) == -1)
{
m_Output.clear();
m_Error = true;
}
else
{
// Set output by converting array strings into normal strings.
m_Output = wxJoin(errors, '\n', '\n') + wxJoin(output, '\n', '\n');
}
}
return !m_Error;
}
bool wxExProcess::IsRunning() const
{
if (
// If we executed a sync process, then it always ended,
// so it is not running.
m_Sync ||
GetPid() <= 0)
{
return false;
}
return Exists(GetPid());
}
wxKillError wxExProcess::Kill(wxSignal sig)
{
if (!IsRunning())
{
return wxKILL_NO_PROCESS;
}
const wxKillError result = wxProcess::Kill(GetPid(), sig);
switch (result)
{
case wxKILL_OK:
wxLogStatus(_("Stopped"));
DeletePendingEvents();
m_Timer->Stop();
m_Dialog->Hide();
break;
case wxKILL_BAD_SIGNAL:
wxLogStatus("no such signal");
break;
case wxKILL_ACCESS_DENIED:
wxLogStatus("permission denied");
break;
case wxKILL_NO_PROCESS:
wxLogStatus("no such process");
break;
case wxKILL_ERROR:
wxLogStatus("another, unspecified error");
break;
default: wxFAIL;
}
return result;
}
void wxExProcess::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case ID_SHELL_COMMAND:
m_Timer->Stop();
m_Dialog->GetSTCShell()->LineEnd();
if (m_Command != "cmd")
{
m_Dialog->GetSTCShell()->AddText(m_Dialog->GetSTCShell()->GetEOL());
}
if (IsRunning())
{
// send command to process
wxOutputStream* os = GetOutputStream();
if (os != NULL)
{
wxTextOutputStream os(*GetOutputStream());
os.WriteString(event.GetString() + "\n");
}
if (CheckInput())
{
m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);
}
m_Timer->Start();
}
else
{
wxLogStatus("Process is not running");
}
break;
case ID_SHELL_COMMAND_STOP:
if (IsRunning())
{
Kill();
}
break;
default: wxFAIL; break;
}
}
void wxExProcess::OnTerminate(int pid, int status)
{
m_Timer->Stop();
wxLogStatus(_("Ready"));
wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);
wxPostEvent(wxTheApp->GetTopWindow(), event);
// Collect remaining input.
CheckInput();
}
void wxExProcess::OnTimer(wxTimerEvent& event)
{
CheckInput();
}
#if wxUSE_GUI
void wxExProcess::ShowOutput(const wxString& caption) const
{
if (!m_Sync)
{
wxLogStatus("Output only available for sync processes");
}
else if (!m_Error)
{
if (m_Dialog != NULL)
{
m_Dialog->GetSTC()->SetText(m_Output);
m_Dialog->SetTitle(caption.empty() ? m_Command: caption);
m_Dialog->Show();
}
else if (!m_Output.empty())
{
wxLogMessage(m_Output);
}
else
{
wxLogStatus("No output available");
}
}
else
{
// Executing command failed, so no output,
// show failing command.
wxLogError("Could not execute: " + m_Command);
}
}
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: Yservices.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: oj $ $Date: 2002-11-11 08:54:32 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONNECTIVITY_MYSQL_DRIVER_HXX
#include "mysql/YDriver.hxx"
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
using namespace connectivity::mysql;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::registry::XRegistryKey;
using ::com::sun::star::lang::XSingleServiceFactory;
using ::com::sun::star::lang::XMultiServiceFactory;
typedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)
(
const Reference< XMultiServiceFactory > & rServiceManager,
const OUString & rComponentName,
::cppu::ComponentInstantiation pCreateFunction,
const Sequence< OUString > & rServiceNames,
rtl_ModuleCount* _pT
);
//***************************************************************************************
//
// Die vorgeschriebene C-Api muss erfuellt werden!
// Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.
//
//---------------------------------------------------------------------------------------
void REGISTER_PROVIDER(
const OUString& aServiceImplName,
const Sequence< OUString>& Services,
const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)
{
OUString aMainKeyName;
aMainKeyName = OUString::createFromAscii("/");
aMainKeyName += aServiceImplName;
aMainKeyName += OUString::createFromAscii("/UNO/SERVICES");
Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );
OSL_ENSURE(xNewKey.is(), "ADABAS::component_writeInfo : could not create a registry key !");
for (sal_uInt32 i=0; i<Services.getLength(); ++i)
xNewKey->createKey(Services[i]);
}
//---------------------------------------------------------------------------------------
struct ProviderRequest
{
Reference< XSingleServiceFactory > xRet;
Reference< XMultiServiceFactory > const xServiceManager;
OUString const sImplementationName;
ProviderRequest(
void* pServiceManager,
sal_Char const* pImplementationName
)
: xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager))
, sImplementationName(OUString::createFromAscii(pImplementationName))
{
}
inline
sal_Bool CREATE_PROVIDER(
const OUString& Implname,
const Sequence< OUString > & Services,
::cppu::ComponentInstantiation Factory,
createFactoryFunc creator
)
{
if (!xRet.is() && (Implname == sImplementationName))
try
{
xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);
}
catch(...)
{
}
return xRet.is();
}
void* getProvider() const { return xRet.get(); }
};
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **ppEnvTypeName,
uno_Environment **ppEnv
)
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//---------------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(
void* pServiceManager,
void* pRegistryKey
)
{
if (pRegistryKey)
try
{
Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));
REGISTER_PROVIDER(
ODriverDelegator::getImplementationName_Static(),
ODriverDelegator::getSupportedServiceNames_Static(), xKey);
return sal_True;
}
catch (::com::sun::star::registry::InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "ODBC::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !");
}
return sal_False;
}
//---------------------------------------------------------------------------------------
extern "C" void* SAL_CALL component_getFactory(
const sal_Char* pImplementationName,
void* pServiceManager,
void* pRegistryKey)
{
void* pRet = 0;
if (pServiceManager)
{
ProviderRequest aReq(pServiceManager,pImplementationName);
aReq.CREATE_PROVIDER(
ODriverDelegator::getImplementationName_Static(),
ODriverDelegator::getSupportedServiceNames_Static(),
ODriverDelegator_CreateInstance, ::cppu::createSingleFactory)
;
if(aReq.xRet.is())
aReq.xRet->acquire();
pRet = aReq.getProvider();
}
return pRet;
};
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.320); FILE MERGED 2005/09/05 17:24:40 rt 1.1.320.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Yservices.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:32:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONNECTIVITY_MYSQL_DRIVER_HXX
#include "mysql/YDriver.hxx"
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
using namespace connectivity::mysql;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::registry::XRegistryKey;
using ::com::sun::star::lang::XSingleServiceFactory;
using ::com::sun::star::lang::XMultiServiceFactory;
typedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)
(
const Reference< XMultiServiceFactory > & rServiceManager,
const OUString & rComponentName,
::cppu::ComponentInstantiation pCreateFunction,
const Sequence< OUString > & rServiceNames,
rtl_ModuleCount* _pT
);
//***************************************************************************************
//
// Die vorgeschriebene C-Api muss erfuellt werden!
// Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.
//
//---------------------------------------------------------------------------------------
void REGISTER_PROVIDER(
const OUString& aServiceImplName,
const Sequence< OUString>& Services,
const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)
{
OUString aMainKeyName;
aMainKeyName = OUString::createFromAscii("/");
aMainKeyName += aServiceImplName;
aMainKeyName += OUString::createFromAscii("/UNO/SERVICES");
Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );
OSL_ENSURE(xNewKey.is(), "ADABAS::component_writeInfo : could not create a registry key !");
for (sal_uInt32 i=0; i<Services.getLength(); ++i)
xNewKey->createKey(Services[i]);
}
//---------------------------------------------------------------------------------------
struct ProviderRequest
{
Reference< XSingleServiceFactory > xRet;
Reference< XMultiServiceFactory > const xServiceManager;
OUString const sImplementationName;
ProviderRequest(
void* pServiceManager,
sal_Char const* pImplementationName
)
: xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager))
, sImplementationName(OUString::createFromAscii(pImplementationName))
{
}
inline
sal_Bool CREATE_PROVIDER(
const OUString& Implname,
const Sequence< OUString > & Services,
::cppu::ComponentInstantiation Factory,
createFactoryFunc creator
)
{
if (!xRet.is() && (Implname == sImplementationName))
try
{
xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);
}
catch(...)
{
}
return xRet.is();
}
void* getProvider() const { return xRet.get(); }
};
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **ppEnvTypeName,
uno_Environment **ppEnv
)
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//---------------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(
void* pServiceManager,
void* pRegistryKey
)
{
if (pRegistryKey)
try
{
Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));
REGISTER_PROVIDER(
ODriverDelegator::getImplementationName_Static(),
ODriverDelegator::getSupportedServiceNames_Static(), xKey);
return sal_True;
}
catch (::com::sun::star::registry::InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "ODBC::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !");
}
return sal_False;
}
//---------------------------------------------------------------------------------------
extern "C" void* SAL_CALL component_getFactory(
const sal_Char* pImplementationName,
void* pServiceManager,
void* pRegistryKey)
{
void* pRet = 0;
if (pServiceManager)
{
ProviderRequest aReq(pServiceManager,pImplementationName);
aReq.CREATE_PROVIDER(
ODriverDelegator::getImplementationName_Static(),
ODriverDelegator::getSupportedServiceNames_Static(),
ODriverDelegator_CreateInstance, ::cppu::createSingleFactory)
;
if(aReq.xRet.is())
aReq.xRet->acquire();
pRet = aReq.getProvider();
}
return pRet;
};
<|endoftext|>
|
<commit_before>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/profiler/utils/hlo_proto_map.h"
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "tensorflow/compiler/xla/service/hlo.pb.h"
#include "tensorflow/core/profiler/convert/xla_op_utils.h"
#include "tensorflow/core/profiler/utils/tf_xplane_visitor.h"
#include "tensorflow/core/profiler/utils/xplane_schema.h"
#include "tensorflow/core/profiler/utils/xplane_utils.h"
#include "tensorflow/core/profiler/utils/xplane_visitor.h"
namespace tensorflow {
namespace profiler {
namespace {
int NumHeapSimulatorTraceEvents(const xla::HloProto* hlo) {
int result = 0;
for (const auto& trace : hlo->buffer_assignment().heap_simulator_traces()) {
result += trace.events_size();
}
return result;
}
} // namespace
std::vector<std::pair<uint64_t, std::unique_ptr<xla::HloProto>>>
ParseHloProtosFromXSpace(const XSpace& space) {
std::vector<std::pair<uint64_t, std::unique_ptr<xla::HloProto>>> hlo_protos;
const XPlane* raw_plane = FindPlaneWithName(space, kMetadataPlaneName);
if (raw_plane != nullptr) {
XPlaneVisitor plane = CreateTfXPlaneVisitor(raw_plane);
if (raw_plane->stats_size() > 0) {
// Fallback for legacy aggregated XPlane.
// TODO(b/235990417): Remove after 06/14/2023.
plane.ForEachStat([&](const XStatVisitor& stat) {
if (stat.ValueCase() != XStat::kBytesValue) return;
auto hlo_proto = std::make_unique<xla::HloProto>();
absl::string_view byte_value = stat.BytesValue();
if (hlo_proto->ParseFromArray(byte_value.data(), byte_value.size())) {
hlo_protos.emplace_back(stat.Id(), std::move(hlo_proto));
}
});
} else {
const XStatMetadata* hlo_proto_stat_metadata =
plane.GetStatMetadataByType(StatType::kHloProto);
if (hlo_proto_stat_metadata == nullptr) {
// Fallback for legacy XPlane.
// TODO(b/235990417): Remove after 06/14/2023.
hlo_proto_stat_metadata = plane.GetStatMetadata(StatType::kHloProto);
}
if (hlo_proto_stat_metadata != nullptr) {
plane.ForEachEventMetadata(
[&](const XEventMetadataVisitor& event_metadata) {
auto hlo_proto_stat = event_metadata.GetStat(
StatType::kHloProto, *hlo_proto_stat_metadata);
if (!hlo_proto_stat) return;
if (hlo_proto_stat->ValueCase() != XStat::kBytesValue) return;
auto hlo_proto = std::make_unique<xla::HloProto>();
if (hlo_proto->ParseFromString(hlo_proto_stat->BytesValue())) {
hlo_protos.emplace_back(event_metadata.Id(),
std::move(hlo_proto));
}
});
}
}
}
return hlo_protos;
}
void HloProtoMap::AddHloProto(uint64_t program_id,
const xla::HloProto* hlo_proto) {
hlo_protos_by_program_id_.try_emplace(program_id, hlo_proto);
absl::string_view hlo_module_name = hlo_proto->hlo_module().name();
hlo_protos_by_name_.try_emplace(
HloModuleNameWithProgramId(hlo_module_name, program_id), hlo_proto);
}
void HloProtoMap::AddHloProto(uint64_t program_id,
std::unique_ptr<const xla::HloProto> hlo_proto) {
AddHloProto(program_id, hlo_proto.get());
owned_hlo_protos_.push_back(std::move(hlo_proto));
}
void HloProtoMap::AddHloProtosFromXSpace(const XSpace& space) {
for (auto& [program_id, hlo_proto] : ParseHloProtosFromXSpace(space)) {
AddHloProto(program_id, std::move(hlo_proto));
}
}
std::vector<absl::string_view> HloProtoMap::GetModuleList() const {
std::vector<absl::string_view> module_list;
module_list.reserve(hlo_protos_by_name_.size());
for (const auto& [name, hlo_proto] : hlo_protos_by_name_) {
module_list.push_back(name);
}
return module_list;
}
std::vector<absl::string_view> HloProtoMap::GetSortedModuleList() const {
std::vector<absl::string_view> module_list = GetModuleList();
absl::c_sort(module_list);
return module_list;
}
std::vector<absl::string_view> HloProtoMap::GetSortedModuleListByHeapTraceSize()
const {
std::vector<std::pair<absl::string_view, const xla::HloProto*>> hlo_protos(
hlo_protos_by_name_.begin(), hlo_protos_by_name_.end());
// Sort the hlo protos by heap trace size and then by hlo module name.
// This way trivial computations will be on the bottom of the list.
absl::c_stable_sort(hlo_protos, [](const auto& a, const auto& b) {
int num_a = NumHeapSimulatorTraceEvents(a.second);
int num_b = NumHeapSimulatorTraceEvents(b.second);
return std::tie(num_a, b.first) > std::tie(num_b, a.first);
});
std::vector<absl::string_view> module_list;
module_list.reserve(hlo_protos.size());
for (const auto& [name, hlo_proto] : hlo_protos) {
module_list.push_back(name);
}
return module_list;
}
absl::StatusOr<const xla::HloProto*> HloProtoMap::GetHloProtoByModuleName(
absl::string_view module_name) const {
auto iter = hlo_protos_by_name_.find(module_name);
if (iter != hlo_protos_by_name_.end()) {
return iter->second;
}
return absl::NotFoundError(
absl::StrCat("Module name: ", module_name, " is not found."));
}
} // namespace profiler
} // namespace tensorflow
<commit_msg>parsefromarray because RCOM proto compiler did not generate a string view version of parser.<commit_after>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/profiler/utils/hlo_proto_map.h"
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "tensorflow/compiler/xla/service/hlo.pb.h"
#include "tensorflow/core/profiler/convert/xla_op_utils.h"
#include "tensorflow/core/profiler/utils/tf_xplane_visitor.h"
#include "tensorflow/core/profiler/utils/xplane_schema.h"
#include "tensorflow/core/profiler/utils/xplane_utils.h"
#include "tensorflow/core/profiler/utils/xplane_visitor.h"
namespace tensorflow {
namespace profiler {
namespace {
int NumHeapSimulatorTraceEvents(const xla::HloProto* hlo) {
int result = 0;
for (const auto& trace : hlo->buffer_assignment().heap_simulator_traces()) {
result += trace.events_size();
}
return result;
}
} // namespace
std::vector<std::pair<uint64_t, std::unique_ptr<xla::HloProto>>>
ParseHloProtosFromXSpace(const XSpace& space) {
std::vector<std::pair<uint64_t, std::unique_ptr<xla::HloProto>>> hlo_protos;
const XPlane* raw_plane = FindPlaneWithName(space, kMetadataPlaneName);
if (raw_plane != nullptr) {
XPlaneVisitor plane = CreateTfXPlaneVisitor(raw_plane);
if (raw_plane->stats_size() > 0) {
// Fallback for legacy aggregated XPlane.
// TODO(b/235990417): Remove after 06/14/2023.
plane.ForEachStat([&](const XStatVisitor& stat) {
if (stat.ValueCase() != XStat::kBytesValue) return;
auto hlo_proto = std::make_unique<xla::HloProto>();
absl::string_view byte_value = stat.BytesValue();
if (hlo_proto->ParseFromArray(byte_value.data(), byte_value.size())) {
hlo_protos.emplace_back(stat.Id(), std::move(hlo_proto));
}
});
} else {
const XStatMetadata* hlo_proto_stat_metadata =
plane.GetStatMetadataByType(StatType::kHloProto);
if (hlo_proto_stat_metadata == nullptr) {
// Fallback for legacy XPlane.
// TODO(b/235990417): Remove after 06/14/2023.
hlo_proto_stat_metadata = plane.GetStatMetadata(StatType::kHloProto);
}
if (hlo_proto_stat_metadata != nullptr) {
plane.ForEachEventMetadata(
[&](const XEventMetadataVisitor& event_metadata) {
auto hlo_proto_stat = event_metadata.GetStat(
StatType::kHloProto, *hlo_proto_stat_metadata);
if (!hlo_proto_stat) return;
if (hlo_proto_stat->ValueCase() != XStat::kBytesValue) return;
auto hlo_proto = std::make_unique<xla::HloProto>();
absl::string_view byte_value = hlo_proto_stat->BytesValue();
if (hlo_proto->ParseFromArray(byte_value.data(),
byte_value.size())) {
hlo_protos.emplace_back(event_metadata.Id(),
std::move(hlo_proto));
}
});
}
}
}
return hlo_protos;
}
void HloProtoMap::AddHloProto(uint64_t program_id,
const xla::HloProto* hlo_proto) {
hlo_protos_by_program_id_.try_emplace(program_id, hlo_proto);
absl::string_view hlo_module_name = hlo_proto->hlo_module().name();
hlo_protos_by_name_.try_emplace(
HloModuleNameWithProgramId(hlo_module_name, program_id), hlo_proto);
}
void HloProtoMap::AddHloProto(uint64_t program_id,
std::unique_ptr<const xla::HloProto> hlo_proto) {
AddHloProto(program_id, hlo_proto.get());
owned_hlo_protos_.push_back(std::move(hlo_proto));
}
void HloProtoMap::AddHloProtosFromXSpace(const XSpace& space) {
for (auto& [program_id, hlo_proto] : ParseHloProtosFromXSpace(space)) {
AddHloProto(program_id, std::move(hlo_proto));
}
}
std::vector<absl::string_view> HloProtoMap::GetModuleList() const {
std::vector<absl::string_view> module_list;
module_list.reserve(hlo_protos_by_name_.size());
for (const auto& [name, hlo_proto] : hlo_protos_by_name_) {
module_list.push_back(name);
}
return module_list;
}
std::vector<absl::string_view> HloProtoMap::GetSortedModuleList() const {
std::vector<absl::string_view> module_list = GetModuleList();
absl::c_sort(module_list);
return module_list;
}
std::vector<absl::string_view> HloProtoMap::GetSortedModuleListByHeapTraceSize()
const {
std::vector<std::pair<absl::string_view, const xla::HloProto*>> hlo_protos(
hlo_protos_by_name_.begin(), hlo_protos_by_name_.end());
// Sort the hlo protos by heap trace size and then by hlo module name.
// This way trivial computations will be on the bottom of the list.
absl::c_stable_sort(hlo_protos, [](const auto& a, const auto& b) {
int num_a = NumHeapSimulatorTraceEvents(a.second);
int num_b = NumHeapSimulatorTraceEvents(b.second);
return std::tie(num_a, b.first) > std::tie(num_b, a.first);
});
std::vector<absl::string_view> module_list;
module_list.reserve(hlo_protos.size());
for (const auto& [name, hlo_proto] : hlo_protos) {
module_list.push_back(name);
}
return module_list;
}
absl::StatusOr<const xla::HloProto*> HloProtoMap::GetHloProtoByModuleName(
absl::string_view module_name) const {
auto iter = hlo_protos_by_name_.find(module_name);
if (iter != hlo_protos_by_name_.end()) {
return iter->second;
}
return absl::NotFoundError(
absl::StrCat("Module name: ", module_name, " is not found."));
}
} // namespace profiler
} // namespace tensorflow
<|endoftext|>
|
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/gpu/cl/environment.h"
#include <string>
#include <vector>
#include "tensorflow/lite/delegates/gpu/cl/cl_kernel.h"
#include "tensorflow/lite/delegates/gpu/cl/util.h"
#include "tensorflow/lite/delegates/gpu/common/shape.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
std::string GetKernelOneLayerTextureArray() {
return R"(
__kernel void main_function(__write_only image2d_array_t dst) {
int X = (int)(get_global_id(0));
int Y = (int)(get_global_id(1));
write_imagef(dst, (int4)(X, Y, 0, 0), (float4)(2.0, 2.0, 2.0, 2.0));
}
)";
}
// Some Adreno < 600 have bug with one layer texture array. b/131099086
// If we have one layer texture array and will write smt from kernel to this
// texture, we will get zeroes instead of actual values.
// The same kernel will work, if we use texture array with more than one layer.
// With help of this code we can detect this bug.
absl::Status CheckKernelSupportOfOneLayerTextureArray(Environment* env,
bool* result) {
// No bug on Adreno 6xx
if (env->device().GetInfo().adreno_info.gpu_version >= 600) {
*result = true;
return absl::OkStatus();
}
CLKernel kernel;
RETURN_IF_ERROR(env->program_cache()->GetOrCreateCLKernel(
GetKernelOneLayerTextureArray(), "main_function", env->context(),
env->device(), &kernel));
Tensor tensor;
const BHWC shape(1, 4, 4, 4);
RETURN_IF_ERROR(CreateTensor(
env->context(), env->device(), shape,
{DataType::FLOAT32, TensorStorageType::TEXTURE_ARRAY, Layout::HWC},
&tensor));
RETURN_IF_ERROR(kernel.SetMemory(0, tensor.GetMemoryPtr()));
RETURN_IF_ERROR(env->queue()->DispatchImplicit(kernel, {4, 4, 1}, {4, 4, 1}));
TensorFloat32 tensor_gpu;
tensor_gpu.shape = shape;
tensor_gpu.data.resize(shape.DimensionsProduct());
RETURN_IF_ERROR(tensor.ReadData(env->queue(), &tensor_gpu));
*result = true;
for (int i = 0; i < 64; ++i) {
if (tensor_gpu.data[i] != 2.0) {
*result = false;
break;
}
}
return absl::OkStatus();
}
absl::Status CreateEnvironment(Environment* result, bool shared,
cl_context_properties egl_context,
cl_context_properties egl_display) {
CLDevice gpu;
RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));
CLContext context;
if (shared) {
RETURN_IF_ERROR(CreateCLGLContext(gpu, egl_context, egl_display, &context));
} else {
RETURN_IF_ERROR(CreateCLContext(gpu, &context));
}
CLCommandQueue queue;
RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));
ProfilingCommandQueue profiling_queue;
RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));
*result = Environment(std::move(gpu), std::move(context), std::move(queue),
std::move(profiling_queue));
if (result->device().IsAdreno() && result->device().SupportsTextureArray()) {
bool supports_one_layer;
RETURN_IF_ERROR(
CheckKernelSupportOfOneLayerTextureArray(result, &supports_one_layer));
if (!supports_one_layer) {
result->GetDevicePtr()->DisableOneLayerTextureArray();
}
}
return absl::OkStatus();
}
} // namespace
Environment::Environment(CLDevice&& device, CLContext&& context,
CLCommandQueue&& queue,
ProfilingCommandQueue&& profiling_queue)
: device_(std::move(device)),
context_(std::move(context)),
queue_(std::move(queue)),
profiling_queue_(std::move(profiling_queue)) {}
Environment::Environment(Environment&& environment)
: device_(std::move(environment.device_)),
context_(std::move(environment.context_)),
queue_(std::move(environment.queue_)),
profiling_queue_(std::move(environment.profiling_queue_)),
program_cache_(std::move(environment.program_cache_)) {}
Environment& Environment::operator=(Environment&& environment) {
if (this != &environment) {
device_ = std::move(environment.device_);
context_ = std::move(environment.context_);
queue_ = std::move(environment.queue_);
profiling_queue_ = std::move(environment.profiling_queue_);
program_cache_ = std::move(environment.program_cache_);
}
return *this;
}
absl::Status Environment::Init() {
if (device().IsAdreno() && device().SupportsTextureArray()) {
bool supports_one_layer;
RETURN_IF_ERROR(
CheckKernelSupportOfOneLayerTextureArray(this, &supports_one_layer));
if (!supports_one_layer) {
GetDevicePtr()->DisableOneLayerTextureArray();
}
}
return absl::OkStatus();
}
void Environment::SetHighPerformance() const {
// TODO(sorokin) use cl_perf_hint if available
}
void Environment::SetDefaultPerformance() const {
// TODO(sorokin) use cl_perf_hint if available
}
void Environment::SetLowPerformance() const {
// TODO(sorokin) use cl_perf_hint if available
}
std::vector<CalculationsPrecision> Environment::GetSupportedPrecisions() const {
std::vector<CalculationsPrecision> precisions;
for (CalculationsPrecision precision :
{CalculationsPrecision::F32, CalculationsPrecision::F32_F16,
CalculationsPrecision::F16}) {
if (IsSupported(precision)) {
precisions.push_back(precision);
}
}
return precisions;
}
bool Environment::IsSupported(CalculationsPrecision precision) const {
switch (precision) {
case CalculationsPrecision::F32_F16:
case CalculationsPrecision::F16:
return device_.SupportsFP16();
case CalculationsPrecision::F32:
return true;
}
}
std::vector<TensorStorageType> Environment::GetSupportedStorages() const {
std::vector<TensorStorageType> storage_types;
for (auto storage_type :
{TensorStorageType::TEXTURE_2D, TensorStorageType::BUFFER,
TensorStorageType::TEXTURE_ARRAY, TensorStorageType::IMAGE_BUFFER,
TensorStorageType::TEXTURE_3D}) {
if (IsSupported(storage_type)) {
storage_types.push_back(storage_type);
}
}
return storage_types;
}
bool Environment::IsSupported(TensorStorageType storage_type) const {
switch (storage_type) {
case TensorStorageType::TEXTURE_2D:
return !device_.IsAMD();
case TensorStorageType::BUFFER:
return true;
case TensorStorageType::TEXTURE_ARRAY:
return !device_.IsAMD() && device_.SupportsTextureArray();
case TensorStorageType::IMAGE_BUFFER:
return (device_.IsAdreno() || device_.IsAMD() || device_.IsNvidia()) &&
device_.SupportsImageBuffer();
case TensorStorageType::TEXTURE_3D:
return !device_.IsAMD() && device_.SupportsImage3D();
case TensorStorageType::SINGLE_TEXTURE_2D:
return false;
case TensorStorageType::UNKNOWN:
return false;
}
return false;
}
TensorStorageType GetFastestStorageType(const CLDevice& gpu) {
if (gpu.IsAdreno()) {
if (gpu.IsAdreno6xxOrHigher()) {
return TensorStorageType::TEXTURE_ARRAY;
} else {
return TensorStorageType::TEXTURE_2D;
}
} else if (gpu.IsPowerVR()) {
return TensorStorageType::TEXTURE_2D;
} else if (gpu.IsMali()) {
const MaliInfo mali_info = gpu.GetInfo().mali_info;
if (mali_info.IsMaliT8xx() || mali_info.IsBifrostGen3() ||
mali_info.IsValhall()) {
return TensorStorageType::TEXTURE_2D;
} else {
return TensorStorageType::BUFFER;
}
} else if (gpu.IsNvidia()) {
return gpu.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
: TensorStorageType::BUFFER;
} else if (gpu.IsAMD()) {
return gpu.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
: TensorStorageType::BUFFER;
}
return TensorStorageType::BUFFER;
}
TensorStorageType GetStorageTypeWithMinimalMemoryConsumption(
const CLDevice& gpu) {
if (gpu.IsAdreno()) {
if (gpu.IsAdreno3xx() || gpu.IsAdreno4xx()) {
return TensorStorageType::BUFFER;
} else {
return TensorStorageType::IMAGE_BUFFER;
}
} else if (gpu.IsPowerVR()) {
return TensorStorageType::BUFFER;
} else if (gpu.IsMali()) {
return TensorStorageType::BUFFER;
} else if (gpu.IsNvidia()) {
return gpu.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
: TensorStorageType::BUFFER;
} else if (gpu.IsAMD()) {
return gpu.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
: TensorStorageType::BUFFER;
}
return TensorStorageType::BUFFER;
}
absl::Status CreateEnvironment(Environment* result) {
CLDevice gpu;
RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));
CLContext context;
RETURN_IF_ERROR(CreateCLContext(gpu, &context));
CLCommandQueue queue;
RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));
ProfilingCommandQueue profiling_queue;
RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));
*result = Environment(std::move(gpu), std::move(context), std::move(queue),
std::move(profiling_queue));
return result->Init();
}
} // namespace cl
} // namespace gpu
} // namespace tflite
<commit_msg>Added handling of Intel in choosing best storage types.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/gpu/cl/environment.h"
#include <string>
#include <vector>
#include "tensorflow/lite/delegates/gpu/cl/cl_kernel.h"
#include "tensorflow/lite/delegates/gpu/cl/util.h"
#include "tensorflow/lite/delegates/gpu/common/shape.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
std::string GetKernelOneLayerTextureArray() {
return R"(
__kernel void main_function(__write_only image2d_array_t dst) {
int X = (int)(get_global_id(0));
int Y = (int)(get_global_id(1));
write_imagef(dst, (int4)(X, Y, 0, 0), (float4)(2.0, 2.0, 2.0, 2.0));
}
)";
}
// Some Adreno < 600 have bug with one layer texture array. b/131099086
// If we have one layer texture array and will write smt from kernel to this
// texture, we will get zeroes instead of actual values.
// The same kernel will work, if we use texture array with more than one layer.
// With help of this code we can detect this bug.
absl::Status CheckKernelSupportOfOneLayerTextureArray(Environment* env,
bool* result) {
// No bug on Adreno 6xx
if (env->device().GetInfo().adreno_info.gpu_version >= 600) {
*result = true;
return absl::OkStatus();
}
CLKernel kernel;
RETURN_IF_ERROR(env->program_cache()->GetOrCreateCLKernel(
GetKernelOneLayerTextureArray(), "main_function", env->context(),
env->device(), &kernel));
Tensor tensor;
const BHWC shape(1, 4, 4, 4);
RETURN_IF_ERROR(CreateTensor(
env->context(), env->device(), shape,
{DataType::FLOAT32, TensorStorageType::TEXTURE_ARRAY, Layout::HWC},
&tensor));
RETURN_IF_ERROR(kernel.SetMemory(0, tensor.GetMemoryPtr()));
RETURN_IF_ERROR(env->queue()->DispatchImplicit(kernel, {4, 4, 1}, {4, 4, 1}));
TensorFloat32 tensor_gpu;
tensor_gpu.shape = shape;
tensor_gpu.data.resize(shape.DimensionsProduct());
RETURN_IF_ERROR(tensor.ReadData(env->queue(), &tensor_gpu));
*result = true;
for (int i = 0; i < 64; ++i) {
if (tensor_gpu.data[i] != 2.0) {
*result = false;
break;
}
}
return absl::OkStatus();
}
absl::Status CreateEnvironment(Environment* result, bool shared,
cl_context_properties egl_context,
cl_context_properties egl_display) {
CLDevice gpu;
RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));
CLContext context;
if (shared) {
RETURN_IF_ERROR(CreateCLGLContext(gpu, egl_context, egl_display, &context));
} else {
RETURN_IF_ERROR(CreateCLContext(gpu, &context));
}
CLCommandQueue queue;
RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));
ProfilingCommandQueue profiling_queue;
RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));
*result = Environment(std::move(gpu), std::move(context), std::move(queue),
std::move(profiling_queue));
if (result->device().IsAdreno() && result->device().SupportsTextureArray()) {
bool supports_one_layer;
RETURN_IF_ERROR(
CheckKernelSupportOfOneLayerTextureArray(result, &supports_one_layer));
if (!supports_one_layer) {
result->GetDevicePtr()->DisableOneLayerTextureArray();
}
}
return absl::OkStatus();
}
} // namespace
Environment::Environment(CLDevice&& device, CLContext&& context,
CLCommandQueue&& queue,
ProfilingCommandQueue&& profiling_queue)
: device_(std::move(device)),
context_(std::move(context)),
queue_(std::move(queue)),
profiling_queue_(std::move(profiling_queue)) {}
Environment::Environment(Environment&& environment)
: device_(std::move(environment.device_)),
context_(std::move(environment.context_)),
queue_(std::move(environment.queue_)),
profiling_queue_(std::move(environment.profiling_queue_)),
program_cache_(std::move(environment.program_cache_)) {}
Environment& Environment::operator=(Environment&& environment) {
if (this != &environment) {
device_ = std::move(environment.device_);
context_ = std::move(environment.context_);
queue_ = std::move(environment.queue_);
profiling_queue_ = std::move(environment.profiling_queue_);
program_cache_ = std::move(environment.program_cache_);
}
return *this;
}
absl::Status Environment::Init() {
if (device().IsAdreno() && device().SupportsTextureArray()) {
bool supports_one_layer;
RETURN_IF_ERROR(
CheckKernelSupportOfOneLayerTextureArray(this, &supports_one_layer));
if (!supports_one_layer) {
GetDevicePtr()->DisableOneLayerTextureArray();
}
}
return absl::OkStatus();
}
void Environment::SetHighPerformance() const {
// TODO(sorokin) use cl_perf_hint if available
}
void Environment::SetDefaultPerformance() const {
// TODO(sorokin) use cl_perf_hint if available
}
void Environment::SetLowPerformance() const {
// TODO(sorokin) use cl_perf_hint if available
}
std::vector<CalculationsPrecision> Environment::GetSupportedPrecisions() const {
std::vector<CalculationsPrecision> precisions;
for (CalculationsPrecision precision :
{CalculationsPrecision::F32, CalculationsPrecision::F32_F16,
CalculationsPrecision::F16}) {
if (IsSupported(precision)) {
precisions.push_back(precision);
}
}
return precisions;
}
bool Environment::IsSupported(CalculationsPrecision precision) const {
switch (precision) {
case CalculationsPrecision::F32_F16:
case CalculationsPrecision::F16:
return device_.SupportsFP16();
case CalculationsPrecision::F32:
return true;
}
}
std::vector<TensorStorageType> Environment::GetSupportedStorages() const {
std::vector<TensorStorageType> storage_types;
for (auto storage_type :
{TensorStorageType::TEXTURE_2D, TensorStorageType::BUFFER,
TensorStorageType::TEXTURE_ARRAY, TensorStorageType::IMAGE_BUFFER,
TensorStorageType::TEXTURE_3D}) {
if (IsSupported(storage_type)) {
storage_types.push_back(storage_type);
}
}
return storage_types;
}
bool Environment::IsSupported(TensorStorageType storage_type) const {
switch (storage_type) {
case TensorStorageType::TEXTURE_2D:
return !device_.IsAMD();
case TensorStorageType::BUFFER:
return true;
case TensorStorageType::TEXTURE_ARRAY:
return !device_.IsAMD() && device_.SupportsTextureArray();
case TensorStorageType::IMAGE_BUFFER:
return (device_.IsAdreno() || device_.IsAMD() || device_.IsNvidia()) &&
device_.SupportsImageBuffer();
case TensorStorageType::TEXTURE_3D:
return !device_.IsAMD() && device_.SupportsImage3D();
case TensorStorageType::SINGLE_TEXTURE_2D:
return false;
case TensorStorageType::UNKNOWN:
return false;
}
return false;
}
TensorStorageType GetFastestStorageType(const CLDevice& gpu) {
if (gpu.IsAdreno()) {
if (gpu.IsAdreno6xxOrHigher()) {
return TensorStorageType::TEXTURE_ARRAY;
} else {
return TensorStorageType::TEXTURE_2D;
}
} else if (gpu.IsPowerVR()) {
return TensorStorageType::TEXTURE_2D;
} else if (gpu.IsMali()) {
const MaliInfo mali_info = gpu.GetInfo().mali_info;
if (mali_info.IsMaliT8xx() || mali_info.IsBifrostGen3() ||
mali_info.IsValhall()) {
return TensorStorageType::TEXTURE_2D;
} else {
return TensorStorageType::BUFFER;
}
} else if (gpu.IsNvidia()) {
return gpu.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
: TensorStorageType::BUFFER;
} else if (gpu.IsAMD()) {
return gpu.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
: TensorStorageType::BUFFER;
} else if (gpu.IsIntel()) {
return TensorStorageType::BUFFER;
}
return TensorStorageType::BUFFER;
}
TensorStorageType GetStorageTypeWithMinimalMemoryConsumption(
const CLDevice& gpu) {
if (gpu.IsAdreno()) {
if (gpu.IsAdreno3xx() || gpu.IsAdreno4xx()) {
return TensorStorageType::BUFFER;
} else {
return TensorStorageType::IMAGE_BUFFER;
}
} else if (gpu.IsPowerVR()) {
return TensorStorageType::BUFFER;
} else if (gpu.IsMali()) {
return TensorStorageType::BUFFER;
} else if (gpu.IsNvidia()) {
return gpu.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
: TensorStorageType::BUFFER;
} else if (gpu.IsAMD()) {
return gpu.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
: TensorStorageType::BUFFER;
} else if (gpu.IsIntel()) {
return TensorStorageType::BUFFER;
}
return TensorStorageType::BUFFER;
}
absl::Status CreateEnvironment(Environment* result) {
CLDevice gpu;
RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));
CLContext context;
RETURN_IF_ERROR(CreateCLContext(gpu, &context));
CLCommandQueue queue;
RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));
ProfilingCommandQueue profiling_queue;
RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));
*result = Environment(std::move(gpu), std::move(context), std::move(queue),
std::move(profiling_queue));
return result->Init();
}
} // namespace cl
} // namespace gpu
} // namespace tflite
<|endoftext|>
|
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/gpu/gl/kernels/add.h"
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/lite/delegates/gpu/common/convert.h"
#include "tensorflow/lite/delegates/gpu/common/data_type.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/types.h"
namespace tflite {
namespace gpu {
namespace gl {
namespace {
class Add : public NodeShader {
public:
absl::Status GenerateCode(const GenerationContext& ctx,
GeneratedCode* generated_code) const final {
const auto& attr =
absl::any_cast<const ElementwiseAttributes&>(ctx.op_attr);
auto adds =
absl::get_if<Tensor<Linear, DataType::FLOAT32>>(&attr.param);
auto scalar = absl::get_if<float>(&attr.param);
const auto* hwc_tensor =
absl::get_if<Tensor<HWC, DataType::FLOAT32>>(&attr.param);
if (hwc_tensor) {
*generated_code = {
/*parameters=*/{},
/*objects=*/
{{"hwc_buffer",
MakeReadonlyObject(
uint3(static_cast<int>(ctx.input_shapes[0][2]),
static_cast<int>(ctx.input_shapes[0][1]),
DivideRoundUp(
static_cast<int>(ctx.input_shapes[0][3]), 4)),
ConvertToPHWC4(
absl::get<Tensor<HWC, DataType::FLOAT32>>(
attr.param)))}},
/*shared_variables=*/{},
// Declare workload explicitly because shader depends on //
// gid.z. //
/*workload=*/
uint3(static_cast<int>(ctx.input_shapes[0][2]),
static_cast<int>(ctx.input_shapes[0][1]),
DivideRoundUp(static_cast<int>(ctx.input_shapes[0][3]),
4)),
/*workgroup=*/uint3(),
/*source_code=*/"value_0 += "
"$hwc_buffer[gid.x, gid.y, gid.z]$;",
/*input=*/IOStructure::AUTO,
/*output=*/IOStructure::AUTO,
};
return absl::OkStatus();
}
if (!adds && !scalar) {
// check if it is a broadcast
if (ctx.input_shapes.size() == 2 &&
ctx.input_shapes[0] != ctx.input_shapes[1] &&
ctx.input_shapes[1][1] == 1 &&
ctx.input_shapes[1][2] == 1 &&
ctx.input_shapes[0][3] == ctx.input_shapes[1][3]) {
// TODO(b/147771327): investigate why input_data_1[gid.z]
// worked before
*generated_code = {
/*parameters=*/{},
/*objects=*/{},
/*shared_variables=*/{},
/*workload=*/uint3(),
/*workgroup=*/uint3(),
/*source_code=*/
"value_0 = $input_data_0[gid.x, gid.y, gid.z]$ + "
" $input_data_1[0, 0, gid.z]$;",
/*input=*/IOStructure::ONLY_DEFINITIONS,
/*output=*/IOStructure::AUTO,
};
return absl::OkStatus();
}
std::string code = "value_0 = value_0";
for (int index = 1; index < ctx.input_shapes.size(); ++index) {
if (ctx.input_shapes[index] != ctx.input_shapes[0]) {
return absl::InvalidArgumentError(
"Shapes are not equal");
}
absl::StrAppend(&code, " + value_", index);
}
absl::StrAppend(&code, ";");
*generated_code = {
/*parameters=*/{},
/*objects=*/{},
/*shared_variables=*/{},
/*workload=*/uint3(),
/*workgroup=*/uint3(),
/*source_code=*/std::move(code),
/*input=*/IOStructure::AUTO,
/*output=*/IOStructure::AUTO,
};
return absl::OkStatus();
}
if (scalar) {
*generated_code = {
/*parameters=*/{{"scalar", *scalar}},
/*objects=*/{},
/*shared_variables=*/{},
/*workload=*/uint3(),
/*workgroup=*/uint3(),
/*source_code=*/"value_0 += $scalar$;",
/*input=*/IOStructure::AUTO,
/*output=*/IOStructure::AUTO,
};
return absl::OkStatus();
}
*generated_code = {
/*parameters=*/{},
/*objects=*/{{"add_buffer", MakeReadonlyObject(adds->data)}},
/*shared_variables=*/{},
// Declare workload explicitly because shader depends on gid.z.
/*workload=*/
uint3(ctx.input_shapes[0][2], ctx.input_shapes[0][1],
DivideRoundUp(ctx.input_shapes[0][3], 4)),
/*workgroup=*/uint3(),
/*source_code=*/"value_0 += $add_buffer[gid.z]$;",
/*input=*/IOStructure::AUTO,
/*output=*/IOStructure::AUTO,
};
return absl::OkStatus();
}
};
} // namespace
std::unique_ptr<NodeShader> NewAddNodeShader() {
return absl::make_unique<Add>();
}
} // namespace gl
} // namespace gpu
} // namespace tflite
<commit_msg>Revert, set default indent 2, wrapped param indent to 4<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/gpu/gl/kernels/add.h"
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/lite/delegates/gpu/common/convert.h"
#include "tensorflow/lite/delegates/gpu/common/data_type.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/types.h"
namespace tflite {
namespace gpu {
namespace gl {
namespace {
class Add : public NodeShader {
public:
absl::Status GenerateCode(const GenerationContext& ctx,
GeneratedCode* generated_code) const final {
const auto& attr =
absl::any_cast<const ElementwiseAttributes&>(ctx.op_attr);
auto adds = absl::get_if<Tensor<Linear, DataType::FLOAT32>>(&attr.param);
auto scalar = absl::get_if<float>(&attr.param);
const auto* hwc_tensor =
absl::get_if<Tensor<HWC, DataType::FLOAT32>>(&attr.param);
if (hwc_tensor) {
*generated_code = {
/*parameters=*/{},
/*objects=*/
{{"hwc_buffer",
MakeReadonlyObject(
uint3(static_cast<int>(ctx.input_shapes[0][2]),
static_cast<int>(ctx.input_shapes[0][1]),
DivideRoundUp(static_cast<int>(ctx.input_shapes[0][3]), 4)),
ConvertToPHWC4(
absl::get<Tensor<HWC, DataType::FLOAT32>>(attr.param)))}},
/*shared_variables=*/{},
// Declare workload explicitly because shader depends on gid.z.
/*workload=*/
uint3(static_cast<int>(ctx.input_shapes[0][2]),
static_cast<int>(ctx.input_shapes[0][1]),
DivideRoundUp(static_cast<int>(ctx.input_shapes[0][3]), 4)),
/*workgroup=*/uint3(),
/*source_code=*/"value_0 += $hwc_buffer[gid.x, gid.y, gid.z]$;",
/*input=*/IOStructure::AUTO,
/*output=*/IOStructure::AUTO,
};
return absl::OkStatus();
}
if (!adds && !scalar) {
// check if it is a broadcast
if (ctx.input_shapes.size() == 2 &&
ctx.input_shapes[0] != ctx.input_shapes[1] &&
ctx.input_shapes[1][1] == 1 && ctx.input_shapes[1][2] == 1 &&
ctx.input_shapes[0][3] == ctx.input_shapes[1][3]) {
// TODO(b/147771327): investigate why input_data_1[gid.z] worked before
*generated_code = {
/*parameters=*/{},
/*objects=*/{},
/*shared_variables=*/{},
/*workload=*/uint3(),
/*workgroup=*/uint3(),
/*source_code=*/
"value_0 = $input_data_0[gid.x, gid.y, gid.z]$ + "
" $input_data_1[0, 0, gid.z]$;",
/*input=*/IOStructure::ONLY_DEFINITIONS,
/*output=*/IOStructure::AUTO,
};
return absl::OkStatus();
}
std::string code = "value_0 = value_0";
for (int index = 1; index < ctx.input_shapes.size(); ++index) {
if (ctx.input_shapes[index] != ctx.input_shapes[0]) {
return absl::InvalidArgumentError("Shapes are not equal");
}
absl::StrAppend(&code, " + value_", index);
}
absl::StrAppend(&code, ";");
*generated_code = {
/*parameters=*/{},
/*objects=*/{},
/*shared_variables=*/{},
/*workload=*/uint3(),
/*workgroup=*/uint3(),
/*source_code=*/std::move(code),
/*input=*/IOStructure::AUTO,
/*output=*/IOStructure::AUTO,
};
return absl::OkStatus();
}
if (scalar) {
*generated_code = {
/*parameters=*/{{"scalar", *scalar}},
/*objects=*/{},
/*shared_variables=*/{},
/*workload=*/uint3(),
/*workgroup=*/uint3(),
/*source_code=*/"value_0 += $scalar$;",
/*input=*/IOStructure::AUTO,
/*output=*/IOStructure::AUTO,
};
return absl::OkStatus();
}
*generated_code = {
/*parameters=*/{},
/*objects=*/{{"add_buffer", MakeReadonlyObject(adds->data)}},
/*shared_variables=*/{},
// Declare workload explicitly because shader depends on gid.z.
/*workload=*/
uint3(ctx.input_shapes[0][2], ctx.input_shapes[0][1],
DivideRoundUp(ctx.input_shapes[0][3], 4)),
/*workgroup=*/uint3(),
/*source_code=*/"value_0 += $add_buffer[gid.z]$;",
/*input=*/IOStructure::AUTO,
/*output=*/IOStructure::AUTO,
};
return absl::OkStatus();
}
};
} // namespace
std::unique_ptr<NodeShader> NewAddNodeShader() {
return absl::make_unique<Add>();
}
} // namespace gl
} // namespace gpu
} // namespace tflite
<|endoftext|>
|
<commit_before>/*
* msvQVTKButtons.cpp
* VTKButtons
*
* Created by Roberto Mucci on 13/01/12.
* Copyright 2012 B3C. All rights reserved.
*
* See License at: http://tiny.cc/QXJ4D
*
*/
#include "msvQVTKButtons.h"
#include <QImage>
#include <QDir>
#include "msvQVTKAnimate.h"
#include <vtkSmartPointer.h>
#include <vtkAlgorithmOutput.h>
#include <vtkQImageToImageSource.h>
#include <vtkTextProperty.h>
#include <vtkProperty2D.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRendererCollection.h>
#include <vtkButtonWidget.h>
#include <vtkTexturedButtonRepresentation.h>
#include <vtkTexturedButtonRepresentation2D.h>
#include <vtkBalloonRepresentation.h>
#include <vtkCommand.h>
#include <vtkEllipticalButtonSource.h>
#include <vtkTexturedButtonRepresentation.h>
#include <vtkRenderWindow.h>
#include <vtkWindowToImageFilter.h>
#include <vtkDataSetMapper.h>
#include <vtkDataSet.h>
#include <vtkCamera.h>
#include <vtkPointData.h>
#define VTK_CREATE(type, name) vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
// Callback respondign to vtkCommand::StateChangedEvent
class vtkButtonCallback : public vtkCommand {
public:
static vtkButtonCallback *New() {
return new vtkButtonCallback;
}
virtual void Execute(vtkObject *caller, unsigned long, void*) {
Q_UNUSED(caller);
msvQVTKAnimate* animateCamera = new msvQVTKAnimate();
if (flyTo) {
animateCamera->execute(renderer, bounds, 200);
} else {
renderer->ResetCamera(bounds);
}
if(animateCamera) {
delete animateCamera;
}
//selection
}
void setBounds(double b[6]) {
bounds[0] = b[0];
bounds[1] = b[1];
bounds[2] = b[2];
bounds[3] = b[3];
bounds[4] = b[4];
bounds[5] = b[5];
}
void setFlyTo(bool fly) {
flyTo = fly;
}
vtkButtonCallback():toolButton(NULL), renderer(0), flyTo(true) {}
msvQVTKButtons *toolButton;
vtkRenderer *renderer;
double bounds[6];
bool flyTo;
};
// Callback respondign to vtkCommand::HighlightEvent
class MSV_QT_WIDGETS_EXPORT vtkButtonHighLightCallback : public vtkCommand {
public:
static vtkButtonHighLightCallback *New() {
return new vtkButtonHighLightCallback;
}
virtual void Execute(vtkObject *caller, unsigned long, void*) {
vtkTexturedButtonRepresentation2D *rep = reinterpret_cast<vtkTexturedButtonRepresentation2D*>(caller);
int highlightState = rep->GetHighlightState();
if ( highlightState == vtkButtonRepresentation::HighlightHovering && previousHighlightState == vtkButtonRepresentation::HighlightNormal ) {
//show tooltip (not if previous state was selecting
toolButton->setShowTooltip(true);
} else if ( highlightState == vtkButtonRepresentation::HighlightNormal) {
//hide tooltip
toolButton->setShowTooltip(false);
}
previousHighlightState = highlightState;
}
vtkButtonHighLightCallback():toolButton(NULL), previousHighlightState(0) {}
msvQVTKButtons *toolButton;
int previousHighlightState;
};
msvQVTKButtons::msvQVTKButtons(QObject *parent) : msvQVTKButtonsInterface(), m_FlyTo(true), m_OnCenter(false) {
m_ButtonCallback = vtkButtonCallback::New();
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->toolButton = this;
m_HighlightCallback = vtkButtonHighLightCallback::New();
reinterpret_cast<vtkButtonHighLightCallback*>(m_HighlightCallback)->toolButton = this;
button()->AddObserver(vtkCommand::StateChangedEvent,m_ButtonCallback);
button()->GetRepresentation()->AddObserver(vtkCommand::HighlightEvent,m_HighlightCallback);
}
msvQVTKButtons::~msvQVTKButtons() {
button()->Delete();
if(m_Window) {
m_Window->Delete();
}
}
void msvQVTKButtons::setCurrentRenderer(vtkRenderer *renderer) {
msvQVTKButtonsInterface::setCurrentRenderer(renderer);
if(renderer) {
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->renderer = renderer;
} else {
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->renderer = NULL;
}
}
void msvQVTKButtons::setBounds(double b[6]) {
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->setBounds(b);
int i = 0;
for( ; i<6 ; i++ ) {
m_Bounds[i] = b[i];
}
update();
}
void msvQVTKButtons::calculatePosition() {
//modify position of the vtkButton
double bds[3];
if (m_OnCenter) {
bds[0] = (m_Bounds[1] + m_Bounds[0])*.5;
bds[1] = (m_Bounds[3] + m_Bounds[2])*.5;
bds[2] = (m_Bounds[5] + m_Bounds[4])*.5;
} else {
//on the corner of the bounding box of the VME.
bds[0] = m_Bounds[0];
bds[1] = m_Bounds[2];
bds[2] = m_Bounds[4];
}
int size[2]; size[0] = 16; size[1] = 16;
vtkTexturedButtonRepresentation2D *rep = static_cast<vtkTexturedButtonRepresentation2D *>(button()->GetRepresentation());
rep->PlaceWidget(bds, size);
rep->Modified();
button()->SetRepresentation(rep);
}
void msvQVTKButtons::update() {
calculatePosition();
msvQVTKButtonsInterface::update();
if(m_ButtonCallback) {
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->flyTo = m_FlyTo;
if(reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->renderer) {
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->renderer->GetRenderWindow()->Render();
}
}
}
void msvQVTKButtons::setFlyTo(bool active) {
m_FlyTo = active;
update();
}
QImage msvQVTKButtons::getPreview(int width, int height) {
if(m_Data) {
double bounds[6];
m_Data->GetBounds(bounds);
// create pipe
vtkWindowToImageFilter *previewer = vtkWindowToImageFilter::New();
vtkDataSetMapper *mapper = vtkDataSetMapper::New();
vtkActor *actor = vtkActor::New();
vtkRenderer *renderer = vtkRenderer::New();
if(m_Window == NULL) {
m_Window = vtkRenderWindow::New();
m_Window->SetDisplayId(NULL);
}
mapper->SetInput(m_Data);
mapper->Update();
actor->SetMapper(mapper);
// offscreen rendering
m_Window->OffScreenRenderingOn();
m_Window->AddRenderer(renderer);
m_Window->Start();
m_Window->SetSize(width,height);
renderer->AddActor(actor);
renderer->ResetCamera(bounds);
// Extract the image from the 'hidden' renderer
previewer->SetInput(m_Window);
previewer->Modified();
previewer->Update();
// Convert image data to QImage and return
vtkImageData* vtkImage = previewer->GetOutput();
if(!vtkImage)
return QImage();
vtkUnsignedCharArray* scalars = vtkUnsignedCharArray::SafeDownCast(vtkImage->GetPointData()->GetScalars());
if(!width || !height || !scalars)
return QImage();
QImage qImage(width, height, QImage::Format_ARGB32);
vtkIdType tupleIndex=0;
int qImageBitIndex=0;
QRgb* qImageBits = (QRgb*)qImage.bits();
unsigned char* scalarTuples = scalars->GetPointer(0);
for(int j=0; j<height; j++) {
for(int i=0; i<width; i++) {
unsigned char* tuple = scalarTuples+(tupleIndex++*3);
QRgb color = qRgba(tuple[0], tuple[1], tuple[2], 255);
*(qImageBits+(qImageBitIndex++))=color;
}
}
previewer->SetInput(NULL);
previewer->Delete();
mapper->SetInput(NULL);
mapper->Delete();
actor->SetMapper(NULL);
actor->Delete();
m_Window->RemoveRenderer(renderer);
//destroy pipe
renderer->Delete();
return qImage;
}
return QImage();
}
void msvQVTKButtons::setData(vtkDataSet *data) {
m_Data = data;
}
<commit_msg>Fix a problem on preview creation<commit_after>/*
* msvQVTKButtons.cpp
* VTKButtons
*
* Created by Roberto Mucci on 13/01/12.
* Copyright 2012 B3C. All rights reserved.
*
* See License at: http://tiny.cc/QXJ4D
*
*/
#include "msvQVTKButtons.h"
#include <QImage>
#include <QDir>
#include "msvQVTKAnimate.h"
#include <vtkSmartPointer.h>
#include <vtkAlgorithmOutput.h>
#include <vtkQImageToImageSource.h>
#include <vtkTextProperty.h>
#include <vtkProperty2D.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRendererCollection.h>
#include <vtkButtonWidget.h>
#include <vtkTexturedButtonRepresentation.h>
#include <vtkTexturedButtonRepresentation2D.h>
#include <vtkBalloonRepresentation.h>
#include <vtkCommand.h>
#include <vtkEllipticalButtonSource.h>
#include <vtkTexturedButtonRepresentation.h>
#include <vtkRenderWindow.h>
#include <vtkWindowToImageFilter.h>
#include <vtkDataSetMapper.h>
#include <vtkDataSet.h>
#include <vtkCamera.h>
#include <vtkPointData.h>
#define VTK_CREATE(type, name) vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
// Callback respondign to vtkCommand::StateChangedEvent
class vtkButtonCallback : public vtkCommand {
public:
static vtkButtonCallback *New() {
return new vtkButtonCallback;
}
virtual void Execute(vtkObject *caller, unsigned long, void*) {
Q_UNUSED(caller);
msvQVTKAnimate* animateCamera = new msvQVTKAnimate();
if (flyTo) {
animateCamera->execute(renderer, bounds, 200);
} else {
renderer->ResetCamera(bounds);
}
if(animateCamera) {
delete animateCamera;
}
//selection
}
void setBounds(double b[6]) {
bounds[0] = b[0];
bounds[1] = b[1];
bounds[2] = b[2];
bounds[3] = b[3];
bounds[4] = b[4];
bounds[5] = b[5];
}
void setFlyTo(bool fly) {
flyTo = fly;
}
vtkButtonCallback():toolButton(NULL), renderer(0), flyTo(true) {}
msvQVTKButtons *toolButton;
vtkRenderer *renderer;
double bounds[6];
bool flyTo;
};
// Callback respondign to vtkCommand::HighlightEvent
class MSV_QT_WIDGETS_EXPORT vtkButtonHighLightCallback : public vtkCommand {
public:
static vtkButtonHighLightCallback *New() {
return new vtkButtonHighLightCallback;
}
virtual void Execute(vtkObject *caller, unsigned long, void*) {
vtkTexturedButtonRepresentation2D *rep = reinterpret_cast<vtkTexturedButtonRepresentation2D*>(caller);
int highlightState = rep->GetHighlightState();
if ( highlightState == vtkButtonRepresentation::HighlightHovering && previousHighlightState == vtkButtonRepresentation::HighlightNormal ) {
//show tooltip (not if previous state was selecting
toolButton->setShowTooltip(true);
} else if ( highlightState == vtkButtonRepresentation::HighlightNormal) {
//hide tooltip
toolButton->setShowTooltip(false);
}
previousHighlightState = highlightState;
}
vtkButtonHighLightCallback():toolButton(NULL), previousHighlightState(0) {}
msvQVTKButtons *toolButton;
int previousHighlightState;
};
msvQVTKButtons::msvQVTKButtons(QObject *parent) : msvQVTKButtonsInterface(), m_FlyTo(true), m_OnCenter(false), m_Window(NULL) {
m_ButtonCallback = vtkButtonCallback::New();
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->toolButton = this;
m_HighlightCallback = vtkButtonHighLightCallback::New();
reinterpret_cast<vtkButtonHighLightCallback*>(m_HighlightCallback)->toolButton = this;
button()->AddObserver(vtkCommand::StateChangedEvent,m_ButtonCallback);
button()->GetRepresentation()->AddObserver(vtkCommand::HighlightEvent,m_HighlightCallback);
}
msvQVTKButtons::~msvQVTKButtons() {
button()->Delete();
if(m_Window) {
m_Window->Delete();
}
}
void msvQVTKButtons::setCurrentRenderer(vtkRenderer *renderer) {
msvQVTKButtonsInterface::setCurrentRenderer(renderer);
if(renderer) {
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->renderer = renderer;
} else {
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->renderer = NULL;
}
}
void msvQVTKButtons::setBounds(double b[6]) {
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->setBounds(b);
int i = 0;
for( ; i<6 ; i++ ) {
m_Bounds[i] = b[i];
}
update();
}
void msvQVTKButtons::calculatePosition() {
//modify position of the vtkButton
double bds[3];
if (m_OnCenter) {
bds[0] = (m_Bounds[1] + m_Bounds[0])*.5;
bds[1] = (m_Bounds[3] + m_Bounds[2])*.5;
bds[2] = (m_Bounds[5] + m_Bounds[4])*.5;
} else {
//on the corner of the bounding box of the VME.
bds[0] = m_Bounds[0];
bds[1] = m_Bounds[2];
bds[2] = m_Bounds[4];
}
int size[2]; size[0] = 16; size[1] = 16;
vtkTexturedButtonRepresentation2D *rep = static_cast<vtkTexturedButtonRepresentation2D *>(button()->GetRepresentation());
rep->PlaceWidget(bds, size);
rep->Modified();
button()->SetRepresentation(rep);
}
void msvQVTKButtons::update() {
calculatePosition();
msvQVTKButtonsInterface::update();
if(m_ButtonCallback) {
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->flyTo = m_FlyTo;
if(reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->renderer) {
reinterpret_cast<vtkButtonCallback*>(m_ButtonCallback)->renderer->GetRenderWindow()->Render();
}
}
}
void msvQVTKButtons::setFlyTo(bool active) {
m_FlyTo = active;
update();
}
QImage msvQVTKButtons::getPreview(int width, int height) {
if(m_Data) {
double bounds[6];
m_Data->GetBounds(bounds);
// create pipe
vtkWindowToImageFilter *previewer = vtkWindowToImageFilter::New();
vtkDataSetMapper *mapper = vtkDataSetMapper::New();
vtkActor *actor = vtkActor::New();
vtkRenderer *renderer = vtkRenderer::New();
if(m_Window == NULL) {
m_Window = vtkRenderWindow::New();
m_Window->SetDisplayId(NULL);
}
mapper->SetInput(m_Data);
mapper->Update();
actor->SetMapper(mapper);
// offscreen rendering
m_Window->OffScreenRenderingOn();
m_Window->AddRenderer(renderer);
m_Window->Start();
m_Window->SetSize(width,height);
renderer->AddActor(actor);
renderer->ResetCamera(bounds);
// Extract the image from the 'hidden' renderer
previewer->SetInput(m_Window);
previewer->Modified();
previewer->Update();
// Convert image data to QImage and return
vtkImageData* vtkImage = previewer->GetOutput();
if(!vtkImage)
return QImage();
vtkUnsignedCharArray* scalars = vtkUnsignedCharArray::SafeDownCast(vtkImage->GetPointData()->GetScalars());
if(!width || !height || !scalars)
return QImage();
QImage qImage(width, height, QImage::Format_ARGB32);
vtkIdType tupleIndex=0;
int qImageBitIndex=0;
QRgb* qImageBits = (QRgb*)qImage.bits();
unsigned char* scalarTuples = scalars->GetPointer(0);
for(int j=0; j<height; j++) {
for(int i=0; i<width; i++) {
unsigned char* tuple = scalarTuples+(tupleIndex++*3);
QRgb color = qRgba(tuple[0], tuple[1], tuple[2], 255);
*(qImageBits+(qImageBitIndex++))=color;
}
}
previewer->SetInput(NULL);
previewer->Delete();
mapper->SetInput(NULL);
mapper->Delete();
actor->SetMapper(NULL);
actor->Delete();
m_Window->RemoveRenderer(renderer);
//destroy pipe
renderer->Delete();
return qImage;
}
return QImage();
}
void msvQVTKButtons::setData(vtkDataSet *data) {
m_Data = data;
}
<|endoftext|>
|
<commit_before>// Test for direct coverage writing with dlopen.
// Test normal exit, coverage level 1.
// RUN: %clangxx_asan -fsanitize-coverage=func -DSHARED %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=func -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android
// RUN: rm -rf %T/coverage-android
// RUN: adb shell mkdir -p %device/coverage-android/direct
// RUN: mkdir -p %T/coverage-android/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android/direct:verbosity=1 %run %t
// RUN: adb pull %device/coverage-android/direct %T/coverage-android/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK1 %s
// Test sudden death, coverage level 1.
// RUN: %clangxx_asan -fsanitize-coverage=func -DSHARED -DKILL %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=func -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android-kill
// RUN: rm -rf %T/coverage-android-kill
// RUN: adb shell mkdir -p %device/coverage-android-kill/direct
// RUN: mkdir -p %T/coverage-android-kill/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android-kill/direct:verbosity=1 not %run %t
// RUN: adb pull %device/coverage-android-kill/direct %T/coverage-android-kill/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android-kill/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK1 %s
// Test normal exit, coverage level 2.
// RUN: %clangxx_asan -fsanitize-coverage=bb -DSHARED %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=bb -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android
// RUN: rm -rf %T/coverage-android
// RUN: adb shell mkdir -p %device/coverage-android/direct
// RUN: mkdir -p %T/coverage-android/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android/direct:verbosity=1 %run %t
// RUN: adb pull %device/coverage-android/direct %T/coverage-android/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK2 %s
// Test sudden death, coverage level 2.
// RUN: %clangxx_asan -fsanitize-coverage=bb -DSHARED -DKILL %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=bb -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android-kill
// RUN: rm -rf %T/coverage-android-kill
// RUN: adb shell mkdir -p %device/coverage-android-kill/direct
// RUN: mkdir -p %T/coverage-android-kill/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android-kill/direct:verbosity=1 not %run %t
// RUN: adb pull %device/coverage-android-kill/direct %T/coverage-android-kill/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android-kill/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK2 %s
// Test normal exit, coverage level 3.
// RUN: %clangxx_asan -fsanitize-coverage=edge -DSHARED %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=edge -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android
// RUN: rm -rf %T/coverage-android
// RUN: adb shell mkdir -p %device/coverage-android/direct
// RUN: mkdir -p %T/coverage-android/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android/direct:verbosity=1 %run %t
// RUN: adb pull %device/coverage-android/direct %T/coverage-android/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK3 %s
// Test sudden death, coverage level 3.
// RUN: %clangxx_asan -fsanitize-coverage=edge -DSHARED -DKILL %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=edge -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android-kill
// RUN: rm -rf %T/coverage-android-kill
// RUN: adb shell mkdir -p %device/coverage-android-kill/direct
// RUN: mkdir -p %T/coverage-android-kill/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android-kill/direct:verbosity=1 not %run %t
// RUN: adb pull %device/coverage-android-kill/direct %T/coverage-android-kill/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android-kill/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK3 %s
#include <assert.h>
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#ifdef SHARED
extern "C" {
void bar() {
printf("bar\n");
#ifdef KILL
kill(getpid(), SIGKILL);
#endif
}
}
#else
volatile int sink;
int main(int argc, char **argv) {
fprintf(stderr, "PID: %d\n", getpid());
void *handle1 =
dlopen(SO_DIR "/libcoverage_android_test_1.so", RTLD_LAZY);
assert(handle1);
if (argc == 0)
sink = 0;
void (*bar1)() = (void (*)())dlsym(handle1, "bar");
assert(bar1);
bar1();
return 0;
}
#endif
// CHECK1: 2 PCs total
// CHECK2: 4 PCs total
// CHECK3: 5 PCs total
<commit_msg>[asan] Disable android-coverage test on anything other than arm.<commit_after>// Test for direct coverage writing with dlopen.
// Test normal exit, coverage level 1.
// RUN: %clangxx_asan -fsanitize-coverage=func -DSHARED %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=func -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android
// RUN: rm -rf %T/coverage-android
// RUN: adb shell mkdir -p %device/coverage-android/direct
// RUN: mkdir -p %T/coverage-android/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android/direct:verbosity=1 %run %t
// RUN: adb pull %device/coverage-android/direct %T/coverage-android/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK1 %s
// Test sudden death, coverage level 1.
// RUN: %clangxx_asan -fsanitize-coverage=func -DSHARED -DKILL %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=func -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android-kill
// RUN: rm -rf %T/coverage-android-kill
// RUN: adb shell mkdir -p %device/coverage-android-kill/direct
// RUN: mkdir -p %T/coverage-android-kill/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android-kill/direct:verbosity=1 not %run %t
// RUN: adb pull %device/coverage-android-kill/direct %T/coverage-android-kill/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android-kill/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK1 %s
// Test normal exit, coverage level 2.
// RUN: %clangxx_asan -fsanitize-coverage=bb -DSHARED %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=bb -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android
// RUN: rm -rf %T/coverage-android
// RUN: adb shell mkdir -p %device/coverage-android/direct
// RUN: mkdir -p %T/coverage-android/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android/direct:verbosity=1 %run %t
// RUN: adb pull %device/coverage-android/direct %T/coverage-android/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK2 %s
// Test sudden death, coverage level 2.
// RUN: %clangxx_asan -fsanitize-coverage=bb -DSHARED -DKILL %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=bb -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android-kill
// RUN: rm -rf %T/coverage-android-kill
// RUN: adb shell mkdir -p %device/coverage-android-kill/direct
// RUN: mkdir -p %T/coverage-android-kill/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android-kill/direct:verbosity=1 not %run %t
// RUN: adb pull %device/coverage-android-kill/direct %T/coverage-android-kill/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android-kill/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK2 %s
// Test normal exit, coverage level 3.
// RUN: %clangxx_asan -fsanitize-coverage=edge -DSHARED %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=edge -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android
// RUN: rm -rf %T/coverage-android
// RUN: adb shell mkdir -p %device/coverage-android/direct
// RUN: mkdir -p %T/coverage-android/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android/direct:verbosity=1 %run %t
// RUN: adb pull %device/coverage-android/direct %T/coverage-android/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK3 %s
// Test sudden death, coverage level 3.
// RUN: %clangxx_asan -fsanitize-coverage=edge -DSHARED -DKILL %s -shared -o %T/libcoverage_android_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=edge -DSO_DIR=\"%device\" %s -o %t
// RUN: adb shell rm -rf %device/coverage-android-kill
// RUN: rm -rf %T/coverage-android-kill
// RUN: adb shell mkdir -p %device/coverage-android-kill/direct
// RUN: mkdir -p %T/coverage-android-kill/direct
// RUN: %env_asan_opts=coverage=1:coverage_direct=1:coverage_dir=%device/coverage-android-kill/direct:verbosity=1 not %run %t
// RUN: adb pull %device/coverage-android-kill/direct %T/coverage-android-kill/direct
// RUN: ls; pwd
// RUN: cd %T/coverage-android-kill/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov |& FileCheck --check-prefix=CHECK3 %s
// PC counts in CHECK lines are platform dependent and match arm32 at the moment.
// sancov tool does not support Android well enough to match function names
// REQUIRES: arm
#include <assert.h>
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#ifdef SHARED
extern "C" {
void bar() {
printf("bar\n");
#ifdef KILL
kill(getpid(), SIGKILL);
#endif
}
}
#else
volatile int sink;
int main(int argc, char **argv) {
fprintf(stderr, "PID: %d\n", getpid());
void *handle1 =
dlopen(SO_DIR "/libcoverage_android_test_1.so", RTLD_LAZY);
assert(handle1);
if (argc == 0)
sink = 0;
void (*bar1)() = (void (*)())dlsym(handle1, "bar");
assert(bar1);
bar1();
return 0;
}
#endif
// CHECK1: 2 PCs total
// CHECK2: 4 PCs total
// CHECK3: 5 PCs total
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2017-2019 CS Systemes d'Information (CS SI)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.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 "otbMultiImageFileWriter.h"
#include "otbImageIOFactory.h"
namespace otb
{
MultiImageFileWriter::MultiImageFileWriter() : m_NumberOfDivisions(0), m_CurrentDivision(0), m_DivisionProgress(0.0), m_IsObserving(true), m_ObserverID(0)
{
// By default, we use tiled streaming, with automatic tile size
// We don't set any parameter, so the memory size is retrieved from the OTB configuration options
this->SetAutomaticAdaptativeStreaming();
// add a fake output to drive memory estimation
this->SetNthOutput(0, FakeOutputType::New());
}
void MultiImageFileWriter::SetNumberOfDivisionsStrippedStreaming(unsigned int nbDivisions)
{
typedef NumberOfDivisionsStrippedStreamingManager<FakeOutputType> NumberOfDivisionsStrippedStreamingManagerType;
NumberOfDivisionsStrippedStreamingManagerType::Pointer streamingManager = NumberOfDivisionsStrippedStreamingManagerType::New();
streamingManager->SetNumberOfDivisions(nbDivisions);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetNumberOfDivisionsTiledStreaming(unsigned int nbDivisions)
{
typedef NumberOfDivisionsTiledStreamingManager<FakeOutputType> NumberOfDivisionsTiledStreamingManagerType;
NumberOfDivisionsTiledStreamingManagerType::Pointer streamingManager = NumberOfDivisionsTiledStreamingManagerType::New();
streamingManager->SetNumberOfDivisions(nbDivisions);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetNumberOfLinesStrippedStreaming(unsigned int nbLinesPerStrip)
{
typedef NumberOfLinesStrippedStreamingManager<FakeOutputType> NumberOfLinesStrippedStreamingManagerType;
NumberOfLinesStrippedStreamingManagerType::Pointer streamingManager = NumberOfLinesStrippedStreamingManagerType::New();
streamingManager->SetNumberOfLinesPerStrip(nbLinesPerStrip);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetAutomaticStrippedStreaming(unsigned int availableRAM, double bias)
{
typedef RAMDrivenStrippedStreamingManager<FakeOutputType> RAMDrivenStrippedStreamingManagerType;
RAMDrivenStrippedStreamingManagerType::Pointer streamingManager = RAMDrivenStrippedStreamingManagerType::New();
streamingManager->SetAvailableRAMInMB(availableRAM);
streamingManager->SetBias(bias);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetTileDimensionTiledStreaming(unsigned int tileDimension)
{
typedef TileDimensionTiledStreamingManager<FakeOutputType> TileDimensionTiledStreamingManagerType;
TileDimensionTiledStreamingManagerType::Pointer streamingManager = TileDimensionTiledStreamingManagerType::New();
streamingManager->SetTileDimension(tileDimension);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetAutomaticTiledStreaming(unsigned int availableRAM, double bias)
{
typedef RAMDrivenTiledStreamingManager<FakeOutputType> RAMDrivenTiledStreamingManagerType;
RAMDrivenTiledStreamingManagerType::Pointer streamingManager = RAMDrivenTiledStreamingManagerType::New();
streamingManager->SetAvailableRAMInMB(availableRAM);
streamingManager->SetBias(bias);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetAutomaticAdaptativeStreaming(unsigned int availableRAM, double bias)
{
typedef RAMDrivenAdaptativeStreamingManager<FakeOutputType> RAMDrivenAdaptativeStreamingManagerType;
RAMDrivenAdaptativeStreamingManagerType::Pointer streamingManager = RAMDrivenAdaptativeStreamingManagerType::New();
streamingManager->SetAvailableRAMInMB(availableRAM);
streamingManager->SetBias(bias);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::InitializeStreaming()
{
// const ImageBaseType* inputPtr = this->GetInput(0);
if (m_SinkList.size() == 0)
itkExceptionMacro("At least one input must be connected to the writer\n");
const ImageBaseType* inputPtr = m_SinkList[0]->GetInput();
if (!inputPtr)
itkExceptionMacro("At least one input must be connected to the writer\n");
/** Control if the ImageIO is CanStreamWrite */
m_NumberOfDivisions = 1;
bool canStream = true;
bool isBuffered = true;
for (unsigned int inputIndex = 0; inputIndex < m_SinkList.size(); ++inputIndex)
{
if (!m_SinkList[inputIndex]->CanStreamWrite())
{
canStream = false;
}
if (m_SinkList[inputIndex]->GetInput()->GetBufferedRegion() != m_SinkList[inputIndex]->GetInput()->GetLargestPossibleRegion())
{
isBuffered = false;
}
}
if (canStream == false)
{
otbWarningMacro(<< "One of the selected ImageIO does not support streaming.");
this->SetNumberOfDivisionsStrippedStreaming(m_NumberOfDivisions);
FakeOutputType* fakeOut = static_cast<FakeOutputType*>(this->itk::ProcessObject::GetOutput(0));
RegionType region = fakeOut->GetLargestPossibleRegion();
m_StreamingManager->PrepareStreaming(fakeOut, region);
}
/** Compare the buffered region with the inputRegion which is the largest
* possible region or a user defined region through extended filename
* Not sure that if this modification is needed */
else if (isBuffered)
{
otbMsgDevMacro(<< "Buffered region is the largest possible region, there is"
" no need for streaming.");
this->SetNumberOfDivisionsStrippedStreaming(m_NumberOfDivisions);
FakeOutputType* fakeOut = static_cast<FakeOutputType*>(this->itk::ProcessObject::GetOutput(0));
RegionType region = fakeOut->GetLargestPossibleRegion();
m_StreamingManager->PrepareStreaming(fakeOut, region);
}
else
{
/**
* Determine of number of pieces to divide the input. This will be the
* first estimated on the fake output, which has the same size as the
* first input. Then there is a check that each input can be split into
* this number of pieces.
*/
FakeOutputType* fakeOut = static_cast<FakeOutputType*>(this->itk::ProcessObject::GetOutput(0));
RegionType region = fakeOut->GetLargestPossibleRegion();
m_StreamingManager->PrepareStreaming(fakeOut, region);
m_NumberOfDivisions = m_StreamingManager->GetNumberOfSplits();
// Check this number of division is compatible with all inputs
bool nbDivValid = false;
while ((!nbDivValid) && 1 < m_NumberOfDivisions)
{
unsigned int smallestNbDiv = m_NumberOfDivisions;
for (unsigned int i = 0; i < m_SinkList.size(); ++i)
{
unsigned int div = m_StreamingManager->GetSplitter()->GetNumberOfSplits(m_SinkList[i]->GetRegionToWrite(), m_NumberOfDivisions);
smallestNbDiv = std::min(div, smallestNbDiv);
}
if (smallestNbDiv == m_NumberOfDivisions)
{
nbDivValid = true;
}
else
{
m_NumberOfDivisions = smallestNbDiv;
}
}
if (m_NumberOfDivisions == 1)
{
otbWarningMacro("Can't find a common split scheme between all inputs, streaming disabled\n");
}
otbMsgDebugMacro(<< "Number Of Stream Divisions : " << m_NumberOfDivisions);
}
}
void MultiImageFileWriter::ResetAllRequestedRegions(ImageBaseType* imagePtr)
{
RegionType nullRegion = imagePtr->GetLargestPossibleRegion();
nullRegion.SetSize(0, 0);
nullRegion.SetSize(1, 0);
imagePtr->SetRequestedRegion(nullRegion);
if (imagePtr->GetSource())
{
itk::ProcessObject::DataObjectPointerArray inputs = imagePtr->GetSource()->GetInputs();
for (itk::ProcessObject::DataObjectPointerArray::iterator it = inputs.begin(); it != inputs.end(); ++it)
{
ImageBaseType* inputImagePtr = dynamic_cast<ImageBaseType*>(it->GetPointer());
if (inputImagePtr != NULL)
{
ResetAllRequestedRegions(inputImagePtr);
}
}
}
}
void MultiImageFileWriter::UpdateOutputInformation()
{
for (unsigned int inputIndex = 0; inputIndex < m_SinkList.size(); ++inputIndex)
{
m_SinkList[inputIndex]->WriteImageInformation();
}
this->GenerateOutputInformation();
}
void MultiImageFileWriter::UpdateOutputData(itk::DataObject* itkNotUsed(output))
{
/**
* prevent chasing our tail
*/
if (this->m_Updating)
{
return;
}
// Initialize streaming
this->InitializeStreaming();
this->SetAbortGenerateData(0);
this->SetProgress(0.0);
this->m_Updating = true;
/**
* Tell all Observers that the filter is starting
*/
this->InvokeEvent(itk::StartEvent());
this->UpdateProgress(0);
m_CurrentDivision = 0;
m_DivisionProgress = 0;
/** Loop over the number of pieces, set and propagate requested regions then
* update pipeline upstream
*/
int numInputs = m_SinkList.size(); // this->GetNumberOfInputs();
m_StreamRegionList.resize(numInputs);
itkDebugMacro("Number of streaming divisions: " << m_NumberOfDivisions);
// Add observer only to first input
if (numInputs > 0)
{
m_IsObserving = false;
m_ObserverID = 0;
typedef itk::MemberCommand<Self> CommandType;
typedef CommandType::Pointer CommandPointerType;
CommandPointerType command = CommandType::New();
command->SetCallbackFunction(this, &Self::ObserveSourceFilterProgress);
itk::ProcessObject* src = this->GetInput(0)->GetSource();
// The first input might not have a source (e.g. in memory image)
if (src)
{
m_ObserverID = src->AddObserver(itk::ProgressEvent(), command);
m_IsObserving = true;
}
}
for (m_CurrentDivision = 0; m_CurrentDivision < m_NumberOfDivisions && !this->GetAbortGenerateData();
m_CurrentDivision++, m_DivisionProgress = 0, this->UpdateFilterProgress())
{
// Update all stream regions
for (int inputIndex = 0; inputIndex < numInputs; ++inputIndex)
{
m_StreamRegionList[inputIndex] = GetStreamRegion(inputIndex);
}
// NOTE : this reset was probably designed to work with the next section
// Where the final requested region is the "union" between the computed
// requested region and the current requested region.
// Reset requested regions for all images
for (int inputIndex = 0; inputIndex < numInputs; ++inputIndex)
{
ResetAllRequestedRegions(m_SinkList[inputIndex]->GetInput());
}
for (int inputIndex = 0; inputIndex < numInputs; ++inputIndex)
{
ImageBaseType::Pointer inputPtr = m_SinkList[inputIndex]->GetInput();
RegionType inputRequestedRegion = m_StreamRegionList[inputIndex];
const RegionType& currentInputRequestedRegion = inputPtr->GetRequestedRegion();
if (currentInputRequestedRegion != inputPtr->GetLargestPossibleRegion() && currentInputRequestedRegion.GetNumberOfPixels() != 0)
{
IndexType startIndex = currentInputRequestedRegion.GetIndex();
IndexType lastIndex = currentInputRequestedRegion.GetUpperIndex();
startIndex[0] = std::min(startIndex[0], inputRequestedRegion.GetIndex(0));
startIndex[1] = std::min(startIndex[1], inputRequestedRegion.GetIndex(1));
lastIndex[0] = std::max(lastIndex[0], inputRequestedRegion.GetUpperIndex()[0]);
lastIndex[1] = std::max(lastIndex[1], inputRequestedRegion.GetUpperIndex()[1]);
inputRequestedRegion.SetIndex(startIndex);
inputRequestedRegion.SetUpperIndex(lastIndex);
}
inputPtr->SetRequestedRegion(inputRequestedRegion);
inputPtr->PropagateRequestedRegion();
}
/** Call GenerateData to write streams to files if needed */
this->GenerateData();
}
/**
* If we ended due to aborting, push the progress up to 1.0 (since
* it probably didn't end there)
*/
if (!this->GetAbortGenerateData())
{
this->UpdateProgress(1.0);
}
// Notify end event observers
this->InvokeEvent(itk::EndEvent());
if (m_IsObserving)
{
ImageBaseType::Pointer inputPtr = m_SinkList[0]->GetInput(); // const_cast<ImageBaseType *>(this->GetInput(0));
itk::ProcessObject* source = inputPtr->GetSource();
m_IsObserving = false;
source->RemoveObserver(m_ObserverID);
}
/**
* Release any inputs if marked for release
*/
this->ReleaseInputs();
// Mark that we are no longer updating the data in this filter
this->m_Updating = false;
}
void MultiImageFileWriter::GenerateInputRequestedRegion()
{
Superclass::GenerateInputRequestedRegion();
// Approximate conversion of output requested region into each input,
// but this is only to have a consistent pipeline memory estimation.
int numInputs = m_SinkList.size(); // this->GetNumberOfInputs();
FakeOutputType* fakeOut = static_cast<FakeOutputType*>(this->itk::ProcessObject::GetOutput(0));
if (numInputs)
{
RegionType refLargest = fakeOut->GetLargestPossibleRegion();
RegionType refRequest = fakeOut->GetRequestedRegion();
IndexType idxLargest = refLargest.GetIndex();
SizeType sizeLargest = refLargest.GetSize();
IndexType idxRequest = refRequest.GetIndex();
SizeType sizeRequest = refRequest.GetSize();
for (int i = 0; i < numInputs; ++i)
{
ImageBaseType* inputPtr = m_SinkList[i]->GetInput();
if (!inputPtr)
{
return;
}
RegionType region = inputPtr->GetLargestPossibleRegion();
IndexType idx = region.GetIndex();
SizeType size = region.GetSize();
idx[0] += size[0] * (idxRequest[0] - idxLargest[0]) / sizeLargest[0];
idx[1] += size[1] * (idxRequest[1] - idxLargest[1]) / sizeLargest[1];
size[0] *= sizeRequest[0] / sizeLargest[0];
size[1] *= sizeRequest[1] / sizeLargest[1];
region.SetIndex(idx);
region.SetSize(size);
inputPtr->SetRequestedRegion(region);
}
}
}
void MultiImageFileWriter::GenerateData()
{
int numInputs = m_SinkList.size();
for (int inputIndex = 0; inputIndex < numInputs; ++inputIndex)
{
auto region = m_StreamRegionList[inputIndex];
auto shiftIndex = m_SinkList[inputIndex]->GetRegionToWrite().GetIndex();
auto index = region.GetIndex();
index[0] -= shiftIndex[0];
index[1] -= shiftIndex[1];
region.SetIndex(index);
m_SinkList[inputIndex]->Write(region);
}
}
MultiImageFileWriter::RegionType MultiImageFileWriter::GetStreamRegion(int inputIndex)
{
const SinkBase::Pointer sink = m_SinkList[inputIndex];
RegionType region = sink->GetRegionToWrite();
m_StreamingManager->GetSplitter()->GetSplit(m_CurrentDivision, m_NumberOfDivisions, region);
return region;
}
} // end of namespace otb
<commit_msg>BUG: use double instead of int in division to prevent the requested region from having size 0<commit_after>/*
* Copyright (C) 2017-2019 CS Systemes d'Information (CS SI)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.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 "otbMultiImageFileWriter.h"
#include "otbImageIOFactory.h"
namespace otb
{
MultiImageFileWriter::MultiImageFileWriter() : m_NumberOfDivisions(0), m_CurrentDivision(0), m_DivisionProgress(0.0), m_IsObserving(true), m_ObserverID(0)
{
// By default, we use tiled streaming, with automatic tile size
// We don't set any parameter, so the memory size is retrieved from the OTB configuration options
this->SetAutomaticAdaptativeStreaming();
// add a fake output to drive memory estimation
this->SetNthOutput(0, FakeOutputType::New());
}
void MultiImageFileWriter::SetNumberOfDivisionsStrippedStreaming(unsigned int nbDivisions)
{
typedef NumberOfDivisionsStrippedStreamingManager<FakeOutputType> NumberOfDivisionsStrippedStreamingManagerType;
NumberOfDivisionsStrippedStreamingManagerType::Pointer streamingManager = NumberOfDivisionsStrippedStreamingManagerType::New();
streamingManager->SetNumberOfDivisions(nbDivisions);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetNumberOfDivisionsTiledStreaming(unsigned int nbDivisions)
{
typedef NumberOfDivisionsTiledStreamingManager<FakeOutputType> NumberOfDivisionsTiledStreamingManagerType;
NumberOfDivisionsTiledStreamingManagerType::Pointer streamingManager = NumberOfDivisionsTiledStreamingManagerType::New();
streamingManager->SetNumberOfDivisions(nbDivisions);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetNumberOfLinesStrippedStreaming(unsigned int nbLinesPerStrip)
{
typedef NumberOfLinesStrippedStreamingManager<FakeOutputType> NumberOfLinesStrippedStreamingManagerType;
NumberOfLinesStrippedStreamingManagerType::Pointer streamingManager = NumberOfLinesStrippedStreamingManagerType::New();
streamingManager->SetNumberOfLinesPerStrip(nbLinesPerStrip);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetAutomaticStrippedStreaming(unsigned int availableRAM, double bias)
{
typedef RAMDrivenStrippedStreamingManager<FakeOutputType> RAMDrivenStrippedStreamingManagerType;
RAMDrivenStrippedStreamingManagerType::Pointer streamingManager = RAMDrivenStrippedStreamingManagerType::New();
streamingManager->SetAvailableRAMInMB(availableRAM);
streamingManager->SetBias(bias);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetTileDimensionTiledStreaming(unsigned int tileDimension)
{
typedef TileDimensionTiledStreamingManager<FakeOutputType> TileDimensionTiledStreamingManagerType;
TileDimensionTiledStreamingManagerType::Pointer streamingManager = TileDimensionTiledStreamingManagerType::New();
streamingManager->SetTileDimension(tileDimension);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetAutomaticTiledStreaming(unsigned int availableRAM, double bias)
{
typedef RAMDrivenTiledStreamingManager<FakeOutputType> RAMDrivenTiledStreamingManagerType;
RAMDrivenTiledStreamingManagerType::Pointer streamingManager = RAMDrivenTiledStreamingManagerType::New();
streamingManager->SetAvailableRAMInMB(availableRAM);
streamingManager->SetBias(bias);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::SetAutomaticAdaptativeStreaming(unsigned int availableRAM, double bias)
{
typedef RAMDrivenAdaptativeStreamingManager<FakeOutputType> RAMDrivenAdaptativeStreamingManagerType;
RAMDrivenAdaptativeStreamingManagerType::Pointer streamingManager = RAMDrivenAdaptativeStreamingManagerType::New();
streamingManager->SetAvailableRAMInMB(availableRAM);
streamingManager->SetBias(bias);
m_StreamingManager = streamingManager;
}
void MultiImageFileWriter::InitializeStreaming()
{
// const ImageBaseType* inputPtr = this->GetInput(0);
if (m_SinkList.size() == 0)
itkExceptionMacro("At least one input must be connected to the writer\n");
const ImageBaseType* inputPtr = m_SinkList[0]->GetInput();
if (!inputPtr)
itkExceptionMacro("At least one input must be connected to the writer\n");
/** Control if the ImageIO is CanStreamWrite */
m_NumberOfDivisions = 1;
bool canStream = true;
bool isBuffered = true;
for (unsigned int inputIndex = 0; inputIndex < m_SinkList.size(); ++inputIndex)
{
if (!m_SinkList[inputIndex]->CanStreamWrite())
{
canStream = false;
}
if (m_SinkList[inputIndex]->GetInput()->GetBufferedRegion() != m_SinkList[inputIndex]->GetInput()->GetLargestPossibleRegion())
{
isBuffered = false;
}
}
if (canStream == false)
{
otbWarningMacro(<< "One of the selected ImageIO does not support streaming.");
this->SetNumberOfDivisionsStrippedStreaming(m_NumberOfDivisions);
FakeOutputType* fakeOut = static_cast<FakeOutputType*>(this->itk::ProcessObject::GetOutput(0));
RegionType region = fakeOut->GetLargestPossibleRegion();
m_StreamingManager->PrepareStreaming(fakeOut, region);
}
/** Compare the buffered region with the inputRegion which is the largest
* possible region or a user defined region through extended filename
* Not sure that if this modification is needed */
else if (isBuffered)
{
otbMsgDevMacro(<< "Buffered region is the largest possible region, there is"
" no need for streaming.");
this->SetNumberOfDivisionsStrippedStreaming(m_NumberOfDivisions);
FakeOutputType* fakeOut = static_cast<FakeOutputType*>(this->itk::ProcessObject::GetOutput(0));
RegionType region = fakeOut->GetLargestPossibleRegion();
m_StreamingManager->PrepareStreaming(fakeOut, region);
}
else
{
/**
* Determine of number of pieces to divide the input. This will be the
* first estimated on the fake output, which has the same size as the
* first input. Then there is a check that each input can be split into
* this number of pieces.
*/
FakeOutputType* fakeOut = static_cast<FakeOutputType*>(this->itk::ProcessObject::GetOutput(0));
RegionType region = fakeOut->GetLargestPossibleRegion();
m_StreamingManager->PrepareStreaming(fakeOut, region);
m_NumberOfDivisions = m_StreamingManager->GetNumberOfSplits();
// Check this number of division is compatible with all inputs
bool nbDivValid = false;
while ((!nbDivValid) && 1 < m_NumberOfDivisions)
{
unsigned int smallestNbDiv = m_NumberOfDivisions;
for (unsigned int i = 0; i < m_SinkList.size(); ++i)
{
unsigned int div = m_StreamingManager->GetSplitter()->GetNumberOfSplits(m_SinkList[i]->GetRegionToWrite(), m_NumberOfDivisions);
smallestNbDiv = std::min(div, smallestNbDiv);
}
if (smallestNbDiv == m_NumberOfDivisions)
{
nbDivValid = true;
}
else
{
m_NumberOfDivisions = smallestNbDiv;
}
}
if (m_NumberOfDivisions == 1)
{
otbWarningMacro("Can't find a common split scheme between all inputs, streaming disabled\n");
}
otbMsgDebugMacro(<< "Number Of Stream Divisions : " << m_NumberOfDivisions);
}
}
void MultiImageFileWriter::ResetAllRequestedRegions(ImageBaseType* imagePtr)
{
RegionType nullRegion = imagePtr->GetLargestPossibleRegion();
nullRegion.SetSize(0, 0);
nullRegion.SetSize(1, 0);
imagePtr->SetRequestedRegion(nullRegion);
if (imagePtr->GetSource())
{
itk::ProcessObject::DataObjectPointerArray inputs = imagePtr->GetSource()->GetInputs();
for (itk::ProcessObject::DataObjectPointerArray::iterator it = inputs.begin(); it != inputs.end(); ++it)
{
ImageBaseType* inputImagePtr = dynamic_cast<ImageBaseType*>(it->GetPointer());
if (inputImagePtr != NULL)
{
ResetAllRequestedRegions(inputImagePtr);
}
}
}
}
void MultiImageFileWriter::UpdateOutputInformation()
{
for (unsigned int inputIndex = 0; inputIndex < m_SinkList.size(); ++inputIndex)
{
m_SinkList[inputIndex]->WriteImageInformation();
}
this->GenerateOutputInformation();
}
void MultiImageFileWriter::UpdateOutputData(itk::DataObject* itkNotUsed(output))
{
/**
* prevent chasing our tail
*/
if (this->m_Updating)
{
return;
}
// Initialize streaming
this->InitializeStreaming();
this->SetAbortGenerateData(0);
this->SetProgress(0.0);
this->m_Updating = true;
/**
* Tell all Observers that the filter is starting
*/
this->InvokeEvent(itk::StartEvent());
this->UpdateProgress(0);
m_CurrentDivision = 0;
m_DivisionProgress = 0;
/** Loop over the number of pieces, set and propagate requested regions then
* update pipeline upstream
*/
int numInputs = m_SinkList.size(); // this->GetNumberOfInputs();
m_StreamRegionList.resize(numInputs);
itkDebugMacro("Number of streaming divisions: " << m_NumberOfDivisions);
// Add observer only to first input
if (numInputs > 0)
{
m_IsObserving = false;
m_ObserverID = 0;
typedef itk::MemberCommand<Self> CommandType;
typedef CommandType::Pointer CommandPointerType;
CommandPointerType command = CommandType::New();
command->SetCallbackFunction(this, &Self::ObserveSourceFilterProgress);
itk::ProcessObject* src = this->GetInput(0)->GetSource();
// The first input might not have a source (e.g. in memory image)
if (src)
{
m_ObserverID = src->AddObserver(itk::ProgressEvent(), command);
m_IsObserving = true;
}
}
for (m_CurrentDivision = 0; m_CurrentDivision < m_NumberOfDivisions && !this->GetAbortGenerateData();
m_CurrentDivision++, m_DivisionProgress = 0, this->UpdateFilterProgress())
{
// Update all stream regions
for (int inputIndex = 0; inputIndex < numInputs; ++inputIndex)
{
m_StreamRegionList[inputIndex] = GetStreamRegion(inputIndex);
}
// NOTE : this reset was probably designed to work with the next section
// Where the final requested region is the "union" between the computed
// requested region and the current requested region.
// Reset requested regions for all images
for (int inputIndex = 0; inputIndex < numInputs; ++inputIndex)
{
ResetAllRequestedRegions(m_SinkList[inputIndex]->GetInput());
}
for (int inputIndex = 0; inputIndex < numInputs; ++inputIndex)
{
ImageBaseType::Pointer inputPtr = m_SinkList[inputIndex]->GetInput();
RegionType inputRequestedRegion = m_StreamRegionList[inputIndex];
const RegionType& currentInputRequestedRegion = inputPtr->GetRequestedRegion();
if (currentInputRequestedRegion != inputPtr->GetLargestPossibleRegion() && currentInputRequestedRegion.GetNumberOfPixels() != 0)
{
IndexType startIndex = currentInputRequestedRegion.GetIndex();
IndexType lastIndex = currentInputRequestedRegion.GetUpperIndex();
startIndex[0] = std::min(startIndex[0], inputRequestedRegion.GetIndex(0));
startIndex[1] = std::min(startIndex[1], inputRequestedRegion.GetIndex(1));
lastIndex[0] = std::max(lastIndex[0], inputRequestedRegion.GetUpperIndex()[0]);
lastIndex[1] = std::max(lastIndex[1], inputRequestedRegion.GetUpperIndex()[1]);
inputRequestedRegion.SetIndex(startIndex);
inputRequestedRegion.SetUpperIndex(lastIndex);
}
inputPtr->SetRequestedRegion(inputRequestedRegion);
inputPtr->PropagateRequestedRegion();
}
/** Call GenerateData to write streams to files if needed */
this->GenerateData();
}
/**
* If we ended due to aborting, push the progress up to 1.0 (since
* it probably didn't end there)
*/
if (!this->GetAbortGenerateData())
{
this->UpdateProgress(1.0);
}
// Notify end event observers
this->InvokeEvent(itk::EndEvent());
if (m_IsObserving)
{
ImageBaseType::Pointer inputPtr = m_SinkList[0]->GetInput(); // const_cast<ImageBaseType *>(this->GetInput(0));
itk::ProcessObject* source = inputPtr->GetSource();
m_IsObserving = false;
source->RemoveObserver(m_ObserverID);
}
/**
* Release any inputs if marked for release
*/
this->ReleaseInputs();
// Mark that we are no longer updating the data in this filter
this->m_Updating = false;
}
void MultiImageFileWriter::GenerateInputRequestedRegion()
{
Superclass::GenerateInputRequestedRegion();
// Approximate conversion of output requested region into each input,
// but this is only to have a consistent pipeline memory estimation.
int numInputs = m_SinkList.size(); // this->GetNumberOfInputs();
FakeOutputType* fakeOut = static_cast<FakeOutputType*>(this->itk::ProcessObject::GetOutput(0));
if (numInputs)
{
RegionType refLargest = fakeOut->GetLargestPossibleRegion();
RegionType refRequest = fakeOut->GetRequestedRegion();
IndexType idxLargest = refLargest.GetIndex();
SizeType sizeLargest = refLargest.GetSize();
IndexType idxRequest = refRequest.GetIndex();
SizeType sizeRequest = refRequest.GetSize();
for (int i = 0; i < numInputs; ++i)
{
ImageBaseType* inputPtr = m_SinkList[i]->GetInput();
if (!inputPtr)
{
return;
}
RegionType region = inputPtr->GetLargestPossibleRegion();
IndexType idx = region.GetIndex();
SizeType size = region.GetSize();
idx[0] += size[0] * (idxRequest[0] - idxLargest[0]) / sizeLargest[0];
idx[1] += size[1] * (idxRequest[1] - idxLargest[1]) / sizeLargest[1];
size[0] *= (double) sizeRequest[0] / sizeLargest[0];
size[1] *= (double) sizeRequest[1] / sizeLargest[1];
region.SetIndex(idx);
region.SetSize(size);
inputPtr->SetRequestedRegion(region);
}
}
}
void MultiImageFileWriter::GenerateData()
{
int numInputs = m_SinkList.size();
for (int inputIndex = 0; inputIndex < numInputs; ++inputIndex)
{
auto region = m_StreamRegionList[inputIndex];
auto shiftIndex = m_SinkList[inputIndex]->GetRegionToWrite().GetIndex();
auto index = region.GetIndex();
index[0] -= shiftIndex[0];
index[1] -= shiftIndex[1];
region.SetIndex(index);
m_SinkList[inputIndex]->Write(region);
}
}
MultiImageFileWriter::RegionType MultiImageFileWriter::GetStreamRegion(int inputIndex)
{
const SinkBase::Pointer sink = m_SinkList[inputIndex];
RegionType region = sink->GetRegionToWrite();
m_StreamingManager->GetSplitter()->GetSplit(m_CurrentDivision, m_NumberOfDivisions, region);
return region;
}
} // end of namespace otb
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
// AliFlowTrackSimpleCuts:
// A simple track cut class to the the AliFlowTrackSimple
// for basic kinematic cuts
//
// author: N. van der Kolk (kolk@nikhef.nl)
// mods: Mikolaj Krzewicki (mikolaj.krzewicki@cern.ch)
#include <limits.h>
#include <float.h>
#include "TNamed.h"
#include "TParticle.h"
#include "TParticlePDG.h"
#include "AliFlowTrackSimpleCuts.h"
#include "AliFlowTrackSimple.h"
ClassImp(AliFlowTrackSimpleCuts)
//-----------------------------------------------------------------------
AliFlowTrackSimpleCuts::AliFlowTrackSimpleCuts():
TNamed(),
fCutPt(kFALSE),
fPtMax(FLT_MAX),
fPtMin(-FLT_MAX),
fCutEta(kFALSE),
fEtaMax(FLT_MAX),
fEtaMin(-FLT_MAX),
fCutPhi(kFALSE),
fPhiMax(FLT_MAX),
fPhiMin(-FLT_MAX),
fCutPID(kFALSE),
fPID(0),
fCutCharge(kFALSE),
fCharge(0)
{
//constructor
}
////-----------------------------------------------------------------------
//AliFlowTrackSimpleCuts::AliFlowTrackSimpleCuts(const AliFlowTrackSimpleCuts& someCuts):
// TNamed(),
// fCutPt(someCuts.fCutPt),
// fPtMax(someCuts.fPtMax),
// fPtMin(someCuts.fPtMin),
// fCutEta(someCuts.fCutEta),
// fEtaMax(someCuts.fEtaMax),
// fEtaMin(someCuts.fEtaMin),
// fCutPhi(someCuts.fCutPhi),
// fPhiMax(someCuts.fPhiMax),
// fPhiMin(someCuts.fPhiMin),
// fCutPID(someCuts.fCutPID),
// fPID(someCuts.fPID),
// fCutCharge(someCuts.fCutCharge),
// fCharge(someCuts.fCharge)
//{
// //copy constructor
//}
//
////-----------------------------------------------------------------------
//AliFlowTrackSimpleCuts& AliFlowTrackSimpleCuts::operator=(const AliFlowTrackSimpleCuts& someCuts)
//{
// TNamed::operator=(someCuts);
// fCutPt = someCuts.fCutPt;
// fPtMax = someCuts.fPtMax;
// fPtMin = someCuts.fPtMin;
// fCutEta = someCuts.fCutEta;
// fEtaMax = someCuts.fEtaMax;
// fEtaMin = someCuts.fEtaMin;
// fCutPhi = someCuts.fCutPhi;
// fPhiMax = someCuts.fPhiMax;
// fPhiMin = someCuts.fPhiMin;
// fCutPID = someCuts.fCutPID;
// fPID = someCuts.fPID;
// fCutCharge = someCuts.fCutCharge;
// fCharge = someCuts.fCharge;
//
// return *this;
//}
//-----------------------------------------------------------------------
Bool_t AliFlowTrackSimpleCuts::IsSelected(TObject* obj, Int_t id)
{
//check cuts
TParticle* p = dynamic_cast<TParticle*>(obj);
if (p) return PassesCuts(p);
AliFlowTrackSimple* ts = dynamic_cast<AliFlowTrackSimple*>(obj);
if (ts) return PassesCuts(ts);
return kFALSE; //default when passed a wrong type of object
}
//-----------------------------------------------------------------------
Bool_t AliFlowTrackSimpleCuts::PassesCuts(const AliFlowTrackSimple *track) const
{
//simple method to check if the simple track passes the simple cuts
if(fCutPt) {if (track->Pt() < fPtMin || track->Pt() >= fPtMax ) return kFALSE;}
if(fCutEta) {if (track->Eta() < fEtaMin || track->Eta() >= fEtaMax ) return kFALSE;}
if(fCutPhi) {if (track->Phi() < fPhiMin || track->Phi() >= fPhiMax ) return kFALSE;}
if(fCutCharge) {if (track->Charge() != fCharge) return kFALSE;}
//if(fCutPID) {if (track->PID() != fPID) return kFALSE;}
return kTRUE;
}
//-----------------------------------------------------------------------
Bool_t AliFlowTrackSimpleCuts::PassesCuts(TParticle* track) const
{
//simple method to check if the simple track passes the simple cuts
if(fCutPt) {if (track->Pt() < fPtMin || track->Pt() >= fPtMax ) return kFALSE;}
if(fCutEta) {if (track->Eta() < fEtaMin || track->Eta() >= fEtaMax ) return kFALSE;}
if(fCutPhi) {if (track->Phi() < fPhiMin || track->Phi() >= fPhiMax ) return kFALSE;}
//if(fCutPID) {if (track->GetPdgCode() != fPID) return kFALSE;}
//getting the charge from a tparticle is expensive
//only do it if neccesary
if (fCutCharge)
{
TParticlePDG* ppdg = track->GetPDG();
Int_t charge = TMath::Nint(ppdg->Charge()/3.0); //mc particles have charge in units of 1/3e
return (charge==fCharge);
}
return kTRUE;
}
<commit_msg>fix warning<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
// AliFlowTrackSimpleCuts:
// A simple track cut class to the the AliFlowTrackSimple
// for basic kinematic cuts
//
// author: N. van der Kolk (kolk@nikhef.nl)
// mods: Mikolaj Krzewicki (mikolaj.krzewicki@cern.ch)
#include <limits.h>
#include <float.h>
#include "TNamed.h"
#include "TParticle.h"
#include "TParticlePDG.h"
#include "AliFlowTrackSimpleCuts.h"
#include "AliFlowTrackSimple.h"
ClassImp(AliFlowTrackSimpleCuts)
//-----------------------------------------------------------------------
AliFlowTrackSimpleCuts::AliFlowTrackSimpleCuts():
TNamed(),
fCutPt(kFALSE),
fPtMax(FLT_MAX),
fPtMin(-FLT_MAX),
fCutEta(kFALSE),
fEtaMax(FLT_MAX),
fEtaMin(-FLT_MAX),
fCutPhi(kFALSE),
fPhiMax(FLT_MAX),
fPhiMin(-FLT_MAX),
fCutPID(kFALSE),
fPID(0),
fCutCharge(kFALSE),
fCharge(0)
{
//constructor
}
////-----------------------------------------------------------------------
//AliFlowTrackSimpleCuts::AliFlowTrackSimpleCuts(const AliFlowTrackSimpleCuts& someCuts):
// TNamed(),
// fCutPt(someCuts.fCutPt),
// fPtMax(someCuts.fPtMax),
// fPtMin(someCuts.fPtMin),
// fCutEta(someCuts.fCutEta),
// fEtaMax(someCuts.fEtaMax),
// fEtaMin(someCuts.fEtaMin),
// fCutPhi(someCuts.fCutPhi),
// fPhiMax(someCuts.fPhiMax),
// fPhiMin(someCuts.fPhiMin),
// fCutPID(someCuts.fCutPID),
// fPID(someCuts.fPID),
// fCutCharge(someCuts.fCutCharge),
// fCharge(someCuts.fCharge)
//{
// //copy constructor
//}
//
////-----------------------------------------------------------------------
//AliFlowTrackSimpleCuts& AliFlowTrackSimpleCuts::operator=(const AliFlowTrackSimpleCuts& someCuts)
//{
// TNamed::operator=(someCuts);
// fCutPt = someCuts.fCutPt;
// fPtMax = someCuts.fPtMax;
// fPtMin = someCuts.fPtMin;
// fCutEta = someCuts.fCutEta;
// fEtaMax = someCuts.fEtaMax;
// fEtaMin = someCuts.fEtaMin;
// fCutPhi = someCuts.fCutPhi;
// fPhiMax = someCuts.fPhiMax;
// fPhiMin = someCuts.fPhiMin;
// fCutPID = someCuts.fCutPID;
// fPID = someCuts.fPID;
// fCutCharge = someCuts.fCutCharge;
// fCharge = someCuts.fCharge;
//
// return *this;
//}
//-----------------------------------------------------------------------
Bool_t AliFlowTrackSimpleCuts::IsSelected(TObject* obj, Int_t)
{
//check cuts
TParticle* p = dynamic_cast<TParticle*>(obj);
if (p) return PassesCuts(p);
AliFlowTrackSimple* ts = dynamic_cast<AliFlowTrackSimple*>(obj);
if (ts) return PassesCuts(ts);
return kFALSE; //default when passed a wrong type of object
}
//-----------------------------------------------------------------------
Bool_t AliFlowTrackSimpleCuts::PassesCuts(const AliFlowTrackSimple *track) const
{
//simple method to check if the simple track passes the simple cuts
if(fCutPt) {if (track->Pt() < fPtMin || track->Pt() >= fPtMax ) return kFALSE;}
if(fCutEta) {if (track->Eta() < fEtaMin || track->Eta() >= fEtaMax ) return kFALSE;}
if(fCutPhi) {if (track->Phi() < fPhiMin || track->Phi() >= fPhiMax ) return kFALSE;}
if(fCutCharge) {if (track->Charge() != fCharge) return kFALSE;}
//if(fCutPID) {if (track->PID() != fPID) return kFALSE;}
return kTRUE;
}
//-----------------------------------------------------------------------
Bool_t AliFlowTrackSimpleCuts::PassesCuts(TParticle* track) const
{
//simple method to check if the simple track passes the simple cuts
if(fCutPt) {if (track->Pt() < fPtMin || track->Pt() >= fPtMax ) return kFALSE;}
if(fCutEta) {if (track->Eta() < fEtaMin || track->Eta() >= fEtaMax ) return kFALSE;}
if(fCutPhi) {if (track->Phi() < fPhiMin || track->Phi() >= fPhiMax ) return kFALSE;}
//if(fCutPID) {if (track->GetPdgCode() != fPID) return kFALSE;}
//getting the charge from a tparticle is expensive
//only do it if neccesary
if (fCutCharge)
{
TParticlePDG* ppdg = track->GetPDG();
Int_t charge = TMath::Nint(ppdg->Charge()/3.0); //mc particles have charge in units of 1/3e
return (charge==fCharge);
}
return kTRUE;
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2008-2016 the Urho3D project.
//
// 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 "../../Precompiled.h"
#include "../../Database/DatabaseEvents.h"
#include "../../IO/Log.h"
namespace Urho3D
{
DbConnection::DbConnection(Context* context, const String& connectionString) :
Object(context),
connectionString_(connectionString),
connectionImpl_(0)
{
if (sqlite3_open(connectionString.CString(), &connectionImpl_) != SQLITE_OK)
{
URHO3D_LOGERRORF("Could not connect: %s", sqlite3_errmsg(connectionImpl_));
sqlite3_close(connectionImpl_);
connectionImpl_ = 0;
}
}
DbConnection::~DbConnection()
{
Finalize();
if (sqlite3_close(connectionImpl_) != SQLITE_OK)
{
// This should not happen after finalizing the connection, log error in Release but assert in Debug
URHO3D_LOGERRORF("Could not disconnect: %s", sqlite3_errmsg(connectionImpl_));
assert(false);
}
connectionImpl_ = 0;
}
void DbConnection::Finalize()
{
// TODO
}
DbResult DbConnection::Execute(const String& sql, bool useCursorEvent)
{
DbResult result;
const char* zLeftover = 0;
sqlite3_stmt* pStmt = 0;
assert(connectionImpl_);
int rc = sqlite3_prepare_v2(connectionImpl_, sql.Trimmed().CString(), -1, &pStmt, &zLeftover);
if (rc != SQLITE_OK)
{
URHO3D_LOGERRORF("Could not execute: %s", sqlite3_errmsg(connectionImpl_));
assert(!pStmt);
return result;
}
if (*zLeftover)
{
URHO3D_LOGERROR("Could not execute: only one SQL statement is allowed");
sqlite3_finalize(pStmt);
return result;
}
unsigned numCols = (unsigned)sqlite3_column_count(pStmt);
result.columns_.Resize(numCols);
for (unsigned i = 0; i < numCols; ++i)
result.columns_[i] = sqlite3_column_name(pStmt, i);
bool filtered = false;
bool aborted = false;
while (1)
{
rc = sqlite3_step(pStmt);
if (rc == SQLITE_ROW)
{
VariantVector colValues(numCols);
for (unsigned i = 0; i < numCols; ++i)
{
int type = sqlite3_column_type(pStmt, i);
if (type != SQLITE_NULL)
{
// We can only bind primitive data type that our Variant class supports
switch (type)
{
case SQLITE_INTEGER:
colValues[i] = sqlite3_column_int(pStmt, i);
if (String(sqlite3_column_decltype(pStmt, i)).Compare("BOOLEAN", false) == 0)
colValues[i] = colValues[i] != 0;
break;
case SQLITE_FLOAT:
colValues[i] = sqlite3_column_double(pStmt, i);
break;
default:
// All other types are stored using their string representation in the Variant
colValues[i] = (const char*)sqlite3_column_text(pStmt, i);
break;
}
}
}
if (useCursorEvent)
{
using namespace DbCursor;
VariantMap& eventData = GetEventDataMap();
eventData[P_DBCONNECTION] = this;
eventData[P_RESULTIMPL] = pStmt;
eventData[P_SQL] = sql;
eventData[P_NUMCOLS] = numCols;
eventData[P_COLVALUES] = colValues;
eventData[P_COLHEADERS] = result.columns_;
eventData[P_FILTER] = false;
eventData[P_ABORT] = false;
SendEvent(E_DBCURSOR, eventData);
filtered = eventData[P_FILTER].GetBool();
aborted = eventData[P_ABORT].GetBool();
}
if (!filtered)
result.rows_.Push(colValues);
if (aborted)
{
sqlite3_finalize(pStmt);
break;
}
}
else if (rc != SQLITE_DONE)
URHO3D_LOGERRORF("Could not execute: %s", sqlite3_errmsg(connectionImpl_));
if (rc != SQLITE_ROW)
{
sqlite3_finalize(pStmt);
break;
}
}
result.numAffectedRows_ = numCols ? -1 : sqlite3_changes(connectionImpl_);
return result;
}
}
<commit_msg>Fixed an issue for SQLite queries where String::Trimmed was returning a corrupted version of the query string<commit_after>//
// Copyright (c) 2008-2016 the Urho3D project.
//
// 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 "../../Precompiled.h"
#include "../../Database/DatabaseEvents.h"
#include "../../IO/Log.h"
namespace Urho3D
{
DbConnection::DbConnection(Context* context, const String& connectionString) :
Object(context),
connectionString_(connectionString),
connectionImpl_(0)
{
if (sqlite3_open(connectionString.CString(), &connectionImpl_) != SQLITE_OK)
{
URHO3D_LOGERRORF("Could not connect: %s", sqlite3_errmsg(connectionImpl_));
sqlite3_close(connectionImpl_);
connectionImpl_ = 0;
}
}
DbConnection::~DbConnection()
{
Finalize();
if (sqlite3_close(connectionImpl_) != SQLITE_OK)
{
// This should not happen after finalizing the connection, log error in Release but assert in Debug
URHO3D_LOGERRORF("Could not disconnect: %s", sqlite3_errmsg(connectionImpl_));
assert(false);
}
connectionImpl_ = 0;
}
void DbConnection::Finalize()
{
// TODO
}
DbResult DbConnection::Execute(const String& sql, bool useCursorEvent)
{
DbResult result;
const char* zLeftover = 0;
sqlite3_stmt* pStmt = 0;
assert(connectionImpl_);
// 2016-10-09: Prevent string corruption when trimmed is returned.
String trimmedSqlStr = sql.Trimmed();
const char* cSqlStr = trimmedSqlStr.CString();
int rc = sqlite3_prepare_v2(connectionImpl_, cSqlStr, -1, &pStmt, &zLeftover);
if (rc != SQLITE_OK)
{
URHO3D_LOGERRORF("Could not execute: %s", sqlite3_errmsg(connectionImpl_));
assert(!pStmt);
return result;
}
if (*zLeftover)
{
URHO3D_LOGERROR("Could not execute: only one SQL statement is allowed");
sqlite3_finalize(pStmt);
return result;
}
unsigned numCols = (unsigned)sqlite3_column_count(pStmt);
result.columns_.Resize(numCols);
for (unsigned i = 0; i < numCols; ++i)
result.columns_[i] = sqlite3_column_name(pStmt, i);
bool filtered = false;
bool aborted = false;
while (1)
{
rc = sqlite3_step(pStmt);
if (rc == SQLITE_ROW)
{
VariantVector colValues(numCols);
for (unsigned i = 0; i < numCols; ++i)
{
int type = sqlite3_column_type(pStmt, i);
if (type != SQLITE_NULL)
{
// We can only bind primitive data type that our Variant class supports
switch (type)
{
case SQLITE_INTEGER:
colValues[i] = sqlite3_column_int(pStmt, i);
if (String(sqlite3_column_decltype(pStmt, i)).Compare("BOOLEAN", false) == 0)
colValues[i] = colValues[i] != 0;
break;
case SQLITE_FLOAT:
colValues[i] = sqlite3_column_double(pStmt, i);
break;
default:
// All other types are stored using their string representation in the Variant
colValues[i] = (const char*)sqlite3_column_text(pStmt, i);
break;
}
}
}
if (useCursorEvent)
{
using namespace DbCursor;
VariantMap& eventData = GetEventDataMap();
eventData[P_DBCONNECTION] = this;
eventData[P_RESULTIMPL] = pStmt;
eventData[P_SQL] = sql;
eventData[P_NUMCOLS] = numCols;
eventData[P_COLVALUES] = colValues;
eventData[P_COLHEADERS] = result.columns_;
eventData[P_FILTER] = false;
eventData[P_ABORT] = false;
SendEvent(E_DBCURSOR, eventData);
filtered = eventData[P_FILTER].GetBool();
aborted = eventData[P_ABORT].GetBool();
}
if (!filtered)
result.rows_.Push(colValues);
if (aborted)
{
sqlite3_finalize(pStmt);
break;
}
}
else if (rc != SQLITE_DONE)
URHO3D_LOGERRORF("Could not execute: %s", sqlite3_errmsg(connectionImpl_));
if (rc != SQLITE_ROW)
{
sqlite3_finalize(pStmt);
break;
}
}
result.numAffectedRows_ = numCols ? -1 : sqlite3_changes(connectionImpl_);
return result;
}
}
<|endoftext|>
|
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "Copyright (c) 2012-2013 Tokutek Inc. All rights reserved."
#ident "$Id$"
#include <stdio.h> // rename(),
#include <fcntl.h> // open()
#include <unistd.h> // close(), write(), read(), unlink(), truncate(), etc.
#include <sys/stat.h> // mkdir()
#include <errno.h>
#include <dlfcn.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include "backup_internal.h"
#include "glassbox.h"
#include "manager.h"
#include "raii-malloc.h"
#include "real_syscalls.h"
#include "backup_debug.h"
#include "directory_set.h"
#if DEBUG_HOTBACKUP
#define WARN(string, arg) HotBackup::InterposeWarn(string, arg);
#define TRACE(string, arg) HotBackup::InterposeTrace(string, arg);
#define ERROR(string, arg) HotBackup::InterposeError(string, arg);
#else
#define WARN(string,arg)
#define TRACE(string,arg)
#define ERROR(string,arg)
#endif
manager the_manager;
//***************************************
//
// Interposed public API:
//
//***************************************
///////////////////////////////////////////////////////////////////////////////
//
// open() -
//
// Description:
//
// Either creates or opens a file in both the source directory
// and the backup directory.
//
extern "C" int open(const char* file, int oflag, ...) {
int fd = 0;
TRACE("open() intercepted, file = ", file);
if (oflag & O_CREAT) {
va_list ap;
va_start(ap, oflag);
mode_t mode = va_arg(ap, mode_t);
va_end(ap);
the_manager.lock_file_op();
fd = call_real_open(file, oflag, mode);
if (fd >= 0 && the_manager.is_alive()) {
int ignore __attribute__((unused)) = the_manager.open(fd, file, oflag); // if there's an error in this call, it's been reported. The application doesn't want to see the error.
}
the_manager.unlock_file_op();
} else {
fd = call_real_open(file, oflag);
if (fd >= 0) {
struct stat stats;
int r = fstat(fd, &stats);
if(r != 0) {
goto out;
}
// TODO: What happens if we can't tell that the file is a FIFO? Should we just the backup? Skip this file?
if (!S_ISFIFO(stats.st_mode) && the_manager.is_alive()) {
int ignore __attribute__((unused)) = the_manager.open(fd, file, oflag); // if there's an error in the call, it's reported. The application doesn't want to hear about it.
}
}
}
out:
return fd;
}
///////////////////////////////////////////////////////////////////////////////
//
// close() -
//
// Description:
//
// Closes the file associated with the provided file descriptor
// in both the source and backup directories.
//
extern "C" int close(int fd) {
int r = 0;
TRACE("close() intercepted, fd = ", fd);
if (the_manager.is_alive()) {
the_manager.close(fd); // The application doesn't want to hear about problems. The backup manager has been notified.
}
r = call_real_close(fd);
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// write() -
//
// Description:
//
// Writes to the file associated with the given file descriptor
// in both the source and backup directories.
//
extern "C" ssize_t write(int fd, const void *buf, size_t nbyte) {
TRACE("write() intercepted, fd = ", fd);
ssize_t r = 0;
if (the_manager.is_alive()) {
// Moved the write down into manager where a lock can be obtained.
r = the_manager.write(fd, buf, nbyte);
} else {
r = call_real_write(fd, buf, nbyte);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// read() -
//
// Description:
//
// Reads data into the given buffer from the source directory.
//
// Note:
//
// The backup manager needs to know that the offset for the
// given file descriptor has changed, even though no bytes are
// read from the backup copy of the same file.
//
extern "C" ssize_t read(int fd, void *buf, size_t nbyte) {
TRACE("read() intercepted, fd = ", fd);
ssize_t r = 0;
if (the_manager.is_alive()) {
// Moved the read down into manager, where a lock can be obtained.
r = the_manager.read(fd, buf, nbyte);
} else {
r = call_real_read(fd, buf, nbyte);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// pwrite() -
//
// Description:
//
// Writes to the file associated with the given file descriptor
// in both the source and backup directories.
//
extern "C" ssize_t pwrite(int fd, const void *buf, size_t nbyte, off_t offset) {
TRACE("pwrite() intercepted, fd = ", fd);
ssize_t r = 0;
if (the_manager.is_alive()) {
r = the_manager.pwrite(fd, buf, nbyte, offset);
} else {
r = call_real_pwrite(fd, buf, nbyte, offset);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
off_t lseek(int fd, off_t offset, int whence) {
TRACE("lseek() intercepted fd =", fd);
off_t r = 0;
if (the_manager.is_alive()) {
r = the_manager.lseek(fd, offset, whence);
} else {
r = call_real_lseek(fd, offset, whence);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// ftruncate() -
//
// Description:
//
// Deletes a portion of the file based on the given file descriptor.
//
extern "C" int ftruncate(int fd, off_t length) {
TRACE("ftruncate() intercepted, fd = ", fd);
int r = 0;
if (the_manager.is_alive()) {
r = the_manager.ftruncate(fd, length);
} else {
r = call_real_ftruncate(fd, length);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// truncate() -
//
// Description:
//
// Deletes a portion of the given file based on the given length.
//
extern "C" int truncate(const char *path, off_t length) {
int r = 0;
TRACE("truncate() intercepted, path = ", path);
if (the_manager.is_alive()) {
r = the_manager.truncate(path, length);
} else {
r = call_real_truncate(path, length);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// unlink() -
//
// Description:
//
extern "C" int unlink(const char *path) {
int r = 0;
TRACE("unlink() intercepted, path = ", path);
if (the_manager.is_alive()) {
the_manager.lock_file_op();
r = the_manager.unlink(path);
the_manager.unlock_file_op();
} else {
r = call_real_unlink(path);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// rename() -
//
// Description:
//
extern "C" int rename(const char *oldpath, const char *newpath) {
int r = 0;
TRACE("rename() intercepted","");
TRACE("-> oldpath = ", oldpath);
TRACE("-> newpath = ", newpath);
if (the_manager.is_alive()) {
the_manager.lock_file_op();
r = the_manager.rename(oldpath, newpath);
the_manager.unlock_file_op();
} else {
r = call_real_rename(oldpath, newpath);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// mkdir() -
//
// Description:
//
int mkdir(const char *pathname, mode_t mode) {
int r = 0;
TRACE("mkidr() intercepted", pathname);
r = call_real_mkdir(pathname, mode);
if (r == 0 && the_manager.is_alive()) {
// Don't try to write if there was an error in the application.
the_manager.mkdir(pathname);
}
return r;
}
extern "C" int tokubackup_create_backup(const char *source_dirs[], const char *dest_dirs[], int dir_count,
backup_poll_fun_t poll_fun, void *poll_extra,
backup_error_fun_t error_fun, void *error_extra) throw() {
for (int i=0; i<dir_count; i++) {
if (source_dirs[i]==NULL) {
error_fun(EINVAL, "One of the source directories is NULL", error_extra);
return EINVAL;
}
if (dest_dirs[i]==NULL) {
error_fun(EINVAL, "One of the destination directories is NULL", error_extra);
return EINVAL;
}
//int r = the_manager.add_directory(source_dirs[i], dest_dirs[i], poll_fun, poll_extra, error_fun, error_extra);
//if (r!=0) return r;
}
// Check to make sure that the source and destination directories are
// actually different.
{
with_object_to_free<char*> full_source (call_real_realpath(source_dirs[0], NULL));
if (full_source.value == NULL) {
error_fun(ENOENT, "Could not resolve source directory path.", error_extra);
return ENOENT;
}
with_object_to_free<char*> full_destination(call_real_realpath(dest_dirs[0], NULL));
if (full_destination.value == NULL) {
error_fun(ENOENT, "Could not resolve destination directory path.", error_extra);
return ENOENT;
}
if (strcmp(full_source.value, full_destination.value) == 0) {
error_fun(EINVAL, "Source and destination directories are the same.", error_extra);
return EINVAL;
}
}
backup_callbacks calls(poll_fun, poll_extra, error_fun, error_extra, &get_throttle);
// HUGE ASSUMPTION: - There is a 1:1 correspondence between source
// and destination directories.
directory_set dirs(dir_count, source_dirs, dest_dirs);
// TODO: Possibly change order IF you can't perform Validate() or
// dirs that have been realpath()'d. Or... Put the validate call
// deeper into the do_backup stack.
int r = dirs.update_to_full_path();
if (r != 0) {
return EINVAL;
}
/******
NOTE: This might be better to check here. However, tests expect
validation to be deeper in the stack.
r = dirs.validate(); if (r != 0) { return EINVAL; }
*****/
return the_manager.do_backup(&dirs, &calls);
}
extern "C" void tokubackup_throttle_backup(unsigned long bytes_per_second) throw() {
the_manager.set_throttle(bytes_per_second);
}
unsigned long get_throttle(void) throw() {
return the_manager.get_throttle();
}
char *malloc_snprintf(size_t size, const char *format, ...) throw() {
va_list ap;
va_start(ap, format);
char *result = (char*)malloc(size);
vsnprintf(result, size, format, ap);
va_end(ap);
return result;
}
const char *tokubackup_version_string = "tokubackup 1.1 $Revision: 56100 $";
#ifdef GLASSBOX
void backup_pause_disable(bool b) throw() {
the_manager.pause_disable(b);
}
void backup_set_keep_capturing(bool b) throw()
// Effect: see backup_internal.h
{
the_manager.set_keep_capturing(b);
}
bool backup_is_capturing(void) throw() {
return the_manager.is_capturing();
}
bool backup_done_copying(void) throw() {
return the_manager.is_done_copying();
}
void backup_set_start_copying(bool b) throw() {
the_manager.set_start_copying(b);
}
#endif
<commit_msg>Bumping up version number to match addition of multi-directory support.<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "Copyright (c) 2012-2013 Tokutek Inc. All rights reserved."
#ident "$Id$"
#include <stdio.h> // rename(),
#include <fcntl.h> // open()
#include <unistd.h> // close(), write(), read(), unlink(), truncate(), etc.
#include <sys/stat.h> // mkdir()
#include <errno.h>
#include <dlfcn.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include "backup_internal.h"
#include "glassbox.h"
#include "manager.h"
#include "raii-malloc.h"
#include "real_syscalls.h"
#include "backup_debug.h"
#include "directory_set.h"
#if DEBUG_HOTBACKUP
#define WARN(string, arg) HotBackup::InterposeWarn(string, arg);
#define TRACE(string, arg) HotBackup::InterposeTrace(string, arg);
#define ERROR(string, arg) HotBackup::InterposeError(string, arg);
#else
#define WARN(string,arg)
#define TRACE(string,arg)
#define ERROR(string,arg)
#endif
manager the_manager;
//***************************************
//
// Interposed public API:
//
//***************************************
///////////////////////////////////////////////////////////////////////////////
//
// open() -
//
// Description:
//
// Either creates or opens a file in both the source directory
// and the backup directory.
//
extern "C" int open(const char* file, int oflag, ...) {
int fd = 0;
TRACE("open() intercepted, file = ", file);
if (oflag & O_CREAT) {
va_list ap;
va_start(ap, oflag);
mode_t mode = va_arg(ap, mode_t);
va_end(ap);
the_manager.lock_file_op();
fd = call_real_open(file, oflag, mode);
if (fd >= 0 && the_manager.is_alive()) {
int ignore __attribute__((unused)) = the_manager.open(fd, file, oflag); // if there's an error in this call, it's been reported. The application doesn't want to see the error.
}
the_manager.unlock_file_op();
} else {
fd = call_real_open(file, oflag);
if (fd >= 0) {
struct stat stats;
int r = fstat(fd, &stats);
if(r != 0) {
goto out;
}
// TODO: What happens if we can't tell that the file is a FIFO? Should we just the backup? Skip this file?
if (!S_ISFIFO(stats.st_mode) && the_manager.is_alive()) {
int ignore __attribute__((unused)) = the_manager.open(fd, file, oflag); // if there's an error in the call, it's reported. The application doesn't want to hear about it.
}
}
}
out:
return fd;
}
///////////////////////////////////////////////////////////////////////////////
//
// close() -
//
// Description:
//
// Closes the file associated with the provided file descriptor
// in both the source and backup directories.
//
extern "C" int close(int fd) {
int r = 0;
TRACE("close() intercepted, fd = ", fd);
if (the_manager.is_alive()) {
the_manager.close(fd); // The application doesn't want to hear about problems. The backup manager has been notified.
}
r = call_real_close(fd);
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// write() -
//
// Description:
//
// Writes to the file associated with the given file descriptor
// in both the source and backup directories.
//
extern "C" ssize_t write(int fd, const void *buf, size_t nbyte) {
TRACE("write() intercepted, fd = ", fd);
ssize_t r = 0;
if (the_manager.is_alive()) {
// Moved the write down into manager where a lock can be obtained.
r = the_manager.write(fd, buf, nbyte);
} else {
r = call_real_write(fd, buf, nbyte);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// read() -
//
// Description:
//
// Reads data into the given buffer from the source directory.
//
// Note:
//
// The backup manager needs to know that the offset for the
// given file descriptor has changed, even though no bytes are
// read from the backup copy of the same file.
//
extern "C" ssize_t read(int fd, void *buf, size_t nbyte) {
TRACE("read() intercepted, fd = ", fd);
ssize_t r = 0;
if (the_manager.is_alive()) {
// Moved the read down into manager, where a lock can be obtained.
r = the_manager.read(fd, buf, nbyte);
} else {
r = call_real_read(fd, buf, nbyte);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// pwrite() -
//
// Description:
//
// Writes to the file associated with the given file descriptor
// in both the source and backup directories.
//
extern "C" ssize_t pwrite(int fd, const void *buf, size_t nbyte, off_t offset) {
TRACE("pwrite() intercepted, fd = ", fd);
ssize_t r = 0;
if (the_manager.is_alive()) {
r = the_manager.pwrite(fd, buf, nbyte, offset);
} else {
r = call_real_pwrite(fd, buf, nbyte, offset);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
off_t lseek(int fd, off_t offset, int whence) {
TRACE("lseek() intercepted fd =", fd);
off_t r = 0;
if (the_manager.is_alive()) {
r = the_manager.lseek(fd, offset, whence);
} else {
r = call_real_lseek(fd, offset, whence);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// ftruncate() -
//
// Description:
//
// Deletes a portion of the file based on the given file descriptor.
//
extern "C" int ftruncate(int fd, off_t length) {
TRACE("ftruncate() intercepted, fd = ", fd);
int r = 0;
if (the_manager.is_alive()) {
r = the_manager.ftruncate(fd, length);
} else {
r = call_real_ftruncate(fd, length);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// truncate() -
//
// Description:
//
// Deletes a portion of the given file based on the given length.
//
extern "C" int truncate(const char *path, off_t length) {
int r = 0;
TRACE("truncate() intercepted, path = ", path);
if (the_manager.is_alive()) {
r = the_manager.truncate(path, length);
} else {
r = call_real_truncate(path, length);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// unlink() -
//
// Description:
//
extern "C" int unlink(const char *path) {
int r = 0;
TRACE("unlink() intercepted, path = ", path);
if (the_manager.is_alive()) {
the_manager.lock_file_op();
r = the_manager.unlink(path);
the_manager.unlock_file_op();
} else {
r = call_real_unlink(path);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// rename() -
//
// Description:
//
extern "C" int rename(const char *oldpath, const char *newpath) {
int r = 0;
TRACE("rename() intercepted","");
TRACE("-> oldpath = ", oldpath);
TRACE("-> newpath = ", newpath);
if (the_manager.is_alive()) {
the_manager.lock_file_op();
r = the_manager.rename(oldpath, newpath);
the_manager.unlock_file_op();
} else {
r = call_real_rename(oldpath, newpath);
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// mkdir() -
//
// Description:
//
int mkdir(const char *pathname, mode_t mode) {
int r = 0;
TRACE("mkidr() intercepted", pathname);
r = call_real_mkdir(pathname, mode);
if (r == 0 && the_manager.is_alive()) {
// Don't try to write if there was an error in the application.
the_manager.mkdir(pathname);
}
return r;
}
extern "C" int tokubackup_create_backup(const char *source_dirs[], const char *dest_dirs[], int dir_count,
backup_poll_fun_t poll_fun, void *poll_extra,
backup_error_fun_t error_fun, void *error_extra) throw() {
for (int i=0; i<dir_count; i++) {
if (source_dirs[i]==NULL) {
error_fun(EINVAL, "One of the source directories is NULL", error_extra);
return EINVAL;
}
if (dest_dirs[i]==NULL) {
error_fun(EINVAL, "One of the destination directories is NULL", error_extra);
return EINVAL;
}
//int r = the_manager.add_directory(source_dirs[i], dest_dirs[i], poll_fun, poll_extra, error_fun, error_extra);
//if (r!=0) return r;
}
// Check to make sure that the source and destination directories are
// actually different.
{
with_object_to_free<char*> full_source (call_real_realpath(source_dirs[0], NULL));
if (full_source.value == NULL) {
error_fun(ENOENT, "Could not resolve source directory path.", error_extra);
return ENOENT;
}
with_object_to_free<char*> full_destination(call_real_realpath(dest_dirs[0], NULL));
if (full_destination.value == NULL) {
error_fun(ENOENT, "Could not resolve destination directory path.", error_extra);
return ENOENT;
}
if (strcmp(full_source.value, full_destination.value) == 0) {
error_fun(EINVAL, "Source and destination directories are the same.", error_extra);
return EINVAL;
}
}
backup_callbacks calls(poll_fun, poll_extra, error_fun, error_extra, &get_throttle);
// HUGE ASSUMPTION: - There is a 1:1 correspondence between source
// and destination directories.
directory_set dirs(dir_count, source_dirs, dest_dirs);
// TODO: Possibly change order IF you can't perform Validate() or
// dirs that have been realpath()'d. Or... Put the validate call
// deeper into the do_backup stack.
int r = dirs.update_to_full_path();
if (r != 0) {
return EINVAL;
}
/******
NOTE: This might be better to check here. However, tests expect
validation to be deeper in the stack.
r = dirs.validate(); if (r != 0) { return EINVAL; }
*****/
return the_manager.do_backup(&dirs, &calls);
}
extern "C" void tokubackup_throttle_backup(unsigned long bytes_per_second) throw() {
the_manager.set_throttle(bytes_per_second);
}
unsigned long get_throttle(void) throw() {
return the_manager.get_throttle();
}
char *malloc_snprintf(size_t size, const char *format, ...) throw() {
va_list ap;
va_start(ap, format);
char *result = (char*)malloc(size);
vsnprintf(result, size, format, ap);
va_end(ap);
return result;
}
const char *tokubackup_version_string = "tokubackup 1.2 $Revision: 56100 $";
#ifdef GLASSBOX
void backup_pause_disable(bool b) throw() {
the_manager.pause_disable(b);
}
void backup_set_keep_capturing(bool b) throw()
// Effect: see backup_internal.h
{
the_manager.set_keep_capturing(b);
}
bool backup_is_capturing(void) throw() {
return the_manager.is_capturing();
}
bool backup_done_copying(void) throw() {
return the_manager.is_done_copying();
}
void backup_set_start_copying(bool b) throw() {
the_manager.set_start_copying(b);
}
#endif
<|endoftext|>
|
<commit_before>#include "Halide.h"
#include <stdio.h>
#include <memory>
int error_occurred = false;
void halide_error(void *ctx, const char *msg) {
printf("Expected: %s\n", msg);
error_occurred = true;
}
using namespace Halide;
int main(int argc, char **argv) {
uint8_t c[4096];
memset(c, 42, sizeof(c));
buffer_t buf;
memset(&buf, 0, sizeof(buf));
buf.host = c;
buf.extent[0] = 4096;
buf.extent[1] = 4096;
buf.extent[2] = 256;
buf.stride[0] = 1;
buf.stride[1] = 0;
buf.stride[2] = 0;
buf.elem_size = 1;
Buffer param_buf(UInt(8), &buf);
ImageParam input(UInt(8), 3);
input.set(param_buf);
RDom r(0, input.extent(0), 0, input.extent(1), 0, input.extent(2));
Var x;
Func grand_total;
grand_total() = cast<uint64_t>(sum(cast<uint64_t>(input(r.x, r.y, r.z))));
grand_total.set_error_handler(&halide_error);
Target t = get_jit_target_from_environment();
t.set_feature(Target::LargeBuffers);
grand_total.compile_jit(t);
Image<uint64_t> result = grand_total.realize();
assert(!error_occurred);
assert(result(0) == (uint64_t)4096*4096*256*42);
grand_total.compile_jit(t.without_feature(Target::LargeBuffers));
result = grand_total.realize();
assert(error_occurred);
printf("Success!\n");
}
<commit_msg>Fix 32-bit test<commit_after>#include "Halide.h"
#include <stdio.h>
#include <memory>
int error_occurred = false;
void halide_error(void *ctx, const char *msg) {
printf("Expected: %s\n", msg);
error_occurred = true;
}
using namespace Halide;
int main(int argc, char **argv) {
uint8_t c[4096];
memset(c, 42, sizeof(c));
buffer_t buf;
memset(&buf, 0, sizeof(buf));
buf.host = c;
buf.extent[0] = 4096;
buf.extent[1] = 4096;
buf.extent[2] = 256;
buf.stride[0] = 1;
buf.stride[1] = 0;
buf.stride[2] = 0;
buf.elem_size = 1;
Buffer param_buf(UInt(8), &buf);
ImageParam input(UInt(8), 3);
input.set(param_buf);
Var x;
Func grand_total;
grand_total() = cast<uint64_t>(input(0, 0, 0) + input(input.extent(0)-1, input.extent(1)-1, input.extent(2)-1));
grand_total.set_error_handler(&halide_error);
Target t = get_jit_target_from_environment();
if (t.bits == 32) {
printf("Skipping test on 32-bit targets\n");
return 0;
}
t.set_feature(Target::LargeBuffers);
grand_total.compile_jit(t);
Image<uint64_t> result = grand_total.realize();
assert(!error_occurred);
assert(result(0) == (uint64_t)4096*4096*256*42);
grand_total.compile_jit(t.without_feature(Target::LargeBuffers));
result = grand_total.realize();
assert(error_occurred);
printf("Success!\n");
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkMapper.h"
#include "mitkDataTreeNode.h"
#include "mitkBaseRenderer.h"
const std::string mitk::Mapper::XML_NODE_NAME = "mapper";
mitk::Mapper::Mapper()
: m_TimeStep( 0 )
{
}
mitk::Mapper::~Mapper()
{
}
mitk::BaseData* mitk::Mapper::GetData() const
{
return m_DataTreeNode->GetData();
}
mitk::DataTreeNode* mitk::Mapper::GetDataTreeNode() const
{
itkDebugMacro("returning DataTreeNode address " << this->m_DataTreeNode );
return this->m_DataTreeNode.GetPointer();
}
bool mitk::Mapper::GetColor(float rgb[3], mitk::BaseRenderer* renderer, const char* name) const
{
const mitk::DataTreeNode* node=GetDataTreeNode();
if(node==NULL)
return false;
return node->GetColor(rgb, renderer, name);
}
bool mitk::Mapper::GetVisibility(bool &visible, mitk::BaseRenderer* renderer, const char* name) const
{
const mitk::DataTreeNode* node=GetDataTreeNode();
if(node==NULL)
return false;
return node->GetVisibility(visible, renderer, name);
}
bool mitk::Mapper::GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const char* name) const
{
const mitk::DataTreeNode* node=GetDataTreeNode();
if(node==NULL)
return false;
return node->GetOpacity(opacity, renderer, name);
}
bool mitk::Mapper::GetLevelWindow(mitk::LevelWindow& levelWindow, mitk::BaseRenderer* renderer, const char* name) const
{
const mitk::DataTreeNode* node=GetDataTreeNode();
if(node==NULL)
return false;
return node->GetLevelWindow(levelWindow, renderer, name);
}
bool mitk::Mapper::IsVisible(mitk::BaseRenderer* renderer, const char* name) const
{
bool visible=true;
GetVisibility(visible, renderer, name);
return visible;
}
void mitk::Mapper::GenerateData()
{
}
void mitk::Mapper::GenerateData(mitk::BaseRenderer* /*renderer*/)
{
}
void mitk::Mapper::CalculateTimeStep( mitk::BaseRenderer *renderer )
{
m_TimeStep = renderer->GetTimeStep();
/*
//
// get the world time
//
const Geometry2D* worldGeometry = renderer->GetCurrentWorldGeometry2D();
assert( worldGeometry != NULL );
ScalarType time = worldGeometry->GetTimeBounds()[ 0 ];
//
// convert the world time in time steps of the input object
//
int m_TimeStep=0;
if ( time > ScalarTypeNumericTraits::NonpositiveMin() )
{
m_TimeStep = inputTimeGeometry->MSToTimeStep( time );
}
*/
}
void mitk::Mapper::Update(mitk::BaseRenderer *renderer)
{
const DataTreeNode* node = GetDataTreeNode();
assert(node!=NULL);
this->CalculateTimeStep( renderer );
//safty cause there are datatreenodes, that have no defined data (video-nodes and root)
unsigned int dataMTime = 0;
mitk::BaseData::Pointer data = static_cast<mitk::BaseData *>(node->GetData());
if (data.IsNotNull())
{
dataMTime = data->GetMTime();
}
if(
(m_LastUpdateTime < GetMTime()) ||
(m_LastUpdateTime < node->GetDataReferenceChangedTime()) ||
(m_LastUpdateTime < dataMTime) ||
(m_LastUpdateTime < renderer->GetTimeStepUpdateTime())
)
{
this->GenerateData();
m_LastUpdateTime.Modified();
}
this->GenerateData(renderer);
}
const std::string& mitk::Mapper::GetXMLNodeName() const
{
return XML_NODE_NAME;
}
<commit_msg>BUG: When calculating the current time step, and no renderer is available (renderer == NULL), use time step 0. This was previously causing a crash, particularly in mitkCountourMapper2DTest<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkMapper.h"
#include "mitkDataTreeNode.h"
#include "mitkBaseRenderer.h"
const std::string mitk::Mapper::XML_NODE_NAME = "mapper";
mitk::Mapper::Mapper()
: m_TimeStep( 0 )
{
}
mitk::Mapper::~Mapper()
{
}
mitk::BaseData* mitk::Mapper::GetData() const
{
return m_DataTreeNode->GetData();
}
mitk::DataTreeNode* mitk::Mapper::GetDataTreeNode() const
{
itkDebugMacro("returning DataTreeNode address " << this->m_DataTreeNode );
return this->m_DataTreeNode.GetPointer();
}
bool mitk::Mapper::GetColor(float rgb[3], mitk::BaseRenderer* renderer, const char* name) const
{
const mitk::DataTreeNode* node=GetDataTreeNode();
if(node==NULL)
return false;
return node->GetColor(rgb, renderer, name);
}
bool mitk::Mapper::GetVisibility(bool &visible, mitk::BaseRenderer* renderer, const char* name) const
{
const mitk::DataTreeNode* node=GetDataTreeNode();
if(node==NULL)
return false;
return node->GetVisibility(visible, renderer, name);
}
bool mitk::Mapper::GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const char* name) const
{
const mitk::DataTreeNode* node=GetDataTreeNode();
if(node==NULL)
return false;
return node->GetOpacity(opacity, renderer, name);
}
bool mitk::Mapper::GetLevelWindow(mitk::LevelWindow& levelWindow, mitk::BaseRenderer* renderer, const char* name) const
{
const mitk::DataTreeNode* node=GetDataTreeNode();
if(node==NULL)
return false;
return node->GetLevelWindow(levelWindow, renderer, name);
}
bool mitk::Mapper::IsVisible(mitk::BaseRenderer* renderer, const char* name) const
{
bool visible=true;
GetVisibility(visible, renderer, name);
return visible;
}
void mitk::Mapper::GenerateData()
{
}
void mitk::Mapper::GenerateData(mitk::BaseRenderer* /*renderer*/)
{
}
void mitk::Mapper::CalculateTimeStep( mitk::BaseRenderer *renderer )
{
if ( renderer != NULL )
{
m_TimeStep = renderer->GetTimeStep();
}
else
{
m_TimeStep = 0;
}
/*
//
// get the world time
//
const Geometry2D* worldGeometry = renderer->GetCurrentWorldGeometry2D();
assert( worldGeometry != NULL );
ScalarType time = worldGeometry->GetTimeBounds()[ 0 ];
//
// convert the world time in time steps of the input object
//
int m_TimeStep=0;
if ( time > ScalarTypeNumericTraits::NonpositiveMin() )
{
m_TimeStep = inputTimeGeometry->MSToTimeStep( time );
}
*/
}
void mitk::Mapper::Update(mitk::BaseRenderer *renderer)
{
const DataTreeNode* node = GetDataTreeNode();
assert(node!=NULL);
this->CalculateTimeStep( renderer );
//safty cause there are datatreenodes, that have no defined data (video-nodes and root)
unsigned int dataMTime = 0;
mitk::BaseData::Pointer data = static_cast<mitk::BaseData *>(node->GetData());
if (data.IsNotNull())
{
dataMTime = data->GetMTime();
}
if(
(m_LastUpdateTime < GetMTime()) ||
(m_LastUpdateTime < node->GetDataReferenceChangedTime()) ||
(m_LastUpdateTime < dataMTime) ||
(m_LastUpdateTime < renderer->GetTimeStepUpdateTime())
)
{
this->GenerateData();
m_LastUpdateTime.Modified();
}
this->GenerateData(renderer);
}
const std::string& mitk::Mapper::GetXMLNodeName() const
{
return XML_NODE_NAME;
}
<|endoftext|>
|
<commit_before>//
// Class AliRsnFunction
//
// This class defines a base classe to implement a function
// which uses the internal RSN package event format (AliRsnEvent).
// It contains some default flags which turn out to be useful:
// - a flag to select only the "true" pairs (tracks from same resonance)
// - a flag to know if the computation is done over two events (mixing)
//
// Any kind of analysis object should be implemented as inheriting from this
// because the AliRsnAnalyzer which executes the analysis will accept a collection
// of such objects, in order to have a unique format of processing method
//
// The user who implements a kind of computation type should inherit from
// this class and override the virtual functions defined in it, which
// initialize the final output histogram and define how to process data.
//
//
// author: A. Pulvirenti (email: alberto.pulvirenti@ct.infn.it)
//
#include <TString.h>
#include <TAxis.h>
#include "AliLog.h"
#include "AliRsnDaughter.h"
#include "AliRsnEvent.h"
#include "AliRsnPairDef.h"
#include "AliRsnMother.h"
#include "AliRsnValue.h"
#include "AliRsnFunction.h"
ClassImp(AliRsnFunction)
//________________________________________________________________________________________
AliRsnFunction::AliRsnFunction(Bool_t useTH1) :
TObject(),
fPairDef(0x0),
fAxisList("AliRsnValue", 0),
fPair(0x0),
fEvent(0x0),
fUseTH1(useTH1),
fSize(0),
fH1(0x0),
fHSparse(0x0)
{
//
// Constructor.
//
}
//________________________________________________________________________________________
AliRsnFunction::AliRsnFunction(const AliRsnFunction ©) :
TObject(copy),
fPairDef(copy.fPairDef),
fAxisList(copy.fAxisList),
fPair(copy.fPair),
fEvent(copy.fEvent),
fUseTH1(copy.fUseTH1),
fSize(copy.fSize),
fH1(0x0),
fHSparse(0x0)
{
//
// Copy constructor.
//
}
//________________________________________________________________________________________
const AliRsnFunction& AliRsnFunction::operator=(const AliRsnFunction& copy)
{
//
// Assignment operator.
//
//SetName(copy.GetName());
//SetTitle(copy.GetTitle());
fPairDef = copy.fPairDef;
fPair = copy.fPair;
fEvent = copy.fEvent;
fUseTH1 = copy.fUseTH1;
fSize = copy.fSize;
if (fH1) delete fH1;
fH1 = 0x0;
if (fHSparse) delete fHSparse;
fHSparse = 0x0;
return (*this);
}
//________________________________________________________________________________________
const char* AliRsnFunction::GetName() const
{
//
// Defines the name of this object according to
// the function type and binning
//
TString name("");
TObjArrayIter next(&fAxisList);
AliRsnValue *axis = 0;
while ((axis = (AliRsnValue*)next())) {
if (name.Length() > 1) name += '_';
name += axis->GetName();
}
return name.Data();
}
//________________________________________________________________________________________
void AliRsnFunction::AddAxis(AliRsnValue *const axis)
{
AliDebug(AliLog::kDebug+2,"<-");
Int_t size = fAxisList.GetEntries();
new(fAxisList[size]) AliRsnValue(*axis);
AliDebug(AliLog::kDebug+2,"->");
if (fAxisList.GetEntries() > 3)
{
AliWarning("A TH1-type output cannot add more than 3 axes: switching to THnSparse -- THIS COULD CAUSE VERY LARGE FILES!!!");
fUseTH1 = kFALSE;
}
}
//________________________________________________________________________________________
TH1* AliRsnFunction::CreateHistogram(const char *histoName, const char *histoTitle)
{
//
// Creates and returns the histogram defined using
// arguments fo name and title, and the first histoDef for binning.
// Variable-sized histogram binning is always called, due to use of histoDef,
// even if the bins are equal, since they are defined in this class.
// Eventually present histoDef's in other slots of array (1, 2) are ignored.
//
// This version produces a THnSparseF.
//
fSize = fAxisList.GetEntries();
if (!fSize) {
AliError("No axes defined");
return 0x0;
}
else if (fSize < 1 || fSize > 3)
{
AliError("Too few or too many axes defined");
return 0x0;
}
// retrieve binnings for main and secondary axes
AliRsnValue *fcnAxis;
TArrayD array[3];
for (Int_t i = 0; i < fSize; i++)
{
fcnAxis = (AliRsnValue*)fAxisList.At(i);
if (!fcnAxis)
{
AliError("Empty axis");
array[i].Set(2);
array[i][0] = -1E5;
array[i][1] = -1E5;
continue;
}
else
{
array[i] = fcnAxis->GetArray();
}
}
// create histogram depending on the number of axes
switch (fSize)
{
case 1:
fH1 = new TH1F(histoName, histoTitle, array[0].GetSize() - 1, array[0].GetArray());
break;
case 2:
fH1 = new TH2F(histoName, histoTitle, array[0].GetSize() - 1, array[0].GetArray(), array[1].GetSize() - 1, array[1].GetArray());
break;
case 3:
fH1 = new TH3F(histoName, histoTitle, array[0].GetSize() - 1, array[0].GetArray(), array[1].GetSize() - 1, array[1].GetArray(), array[2].GetSize() - 1, array[2].GetArray());
break;
}
fH1->Sumw2();
return fH1;
}
//________________________________________________________________________________________
THnSparseF* AliRsnFunction::CreateHistogramSparse(const char *histoName, const char *histoTitle)
{
//
// Creates and returns the histogram defined using
// arguments fo name and title, and the first histoDef for binning.
// Variable-sized histogram binning is always called, due to use of histoDef,
// even if the bins are equal, since they are defined in this class.
// Eventually present histoDef's in other slots of array (1, 2) are ignored.
//
// This version produces a THnSparseF.
//
fSize = fAxisList.GetEntries();
if (!fSize) {
AliError("No axes defined");
return 0x0;
}
// initialize the array of number of bins for each axis
// taking it from the stored values, while for the bins
// they are set as summied and defined later
Double_t dummyD;
Int_t *nbins = new Int_t[fSize];
AliRsnValue *fcnAxis = 0;
for (Int_t i = 0; i < fSize; i++)
{
fcnAxis = (AliRsnValue*)fAxisList.At(i);
if (!fcnAxis)
{
nbins[i] = 1;
AliError("Empty axis");
continue;
}
nbins[i] = fcnAxis->GetArray().GetSize() - 1;
}
// create histogram
fHSparse = new THnSparseF(histoName, histoTitle, fSize, nbins, &dummyD, &dummyD);
fHSparse->Sumw2();
// update the various axes using the definitions given in the array of axes here
for (Int_t i = 0; i < fSize; i++)
{
fcnAxis = (AliRsnValue*)fAxisList.At(i);
if (!fcnAxis) {
AliError("Empty axis: doing unique bin betweeen -100000 and 100000");
continue;
}
fHSparse->SetBinEdges(i, fcnAxis->GetArray().GetArray());
}
return fHSparse;
}
//________________________________________________________________________________________
Bool_t AliRsnFunction::Fill()
{
//
// Fill function histogram with values computed from given input object.
//
AliDebug(AliLog::kDebug +2,"->");
Int_t i;
Double_t *values = new Double_t[fSize];
AliRsnValue *fcnAxis = 0;
for (i = 0; i < fSize; i++) {
fcnAxis = (AliRsnValue*)fAxisList.At(i);
if (!fcnAxis)
{
values[i] = 0.0;
continue;
}
if (fcnAxis->Eval(fPair, fPairDef, fEvent)) values[i] = (Double_t)((Float_t)fcnAxis->GetValue());
}
// fill histogram
if (fUseTH1)
{
// check presence of output histogram
if (!fH1) {
AliError("Required a TH1 which is not initialized");
delete [] values;
return kFALSE;
}
// fill according to dimensions
switch (fSize)
{
case 1:
{
TH1F *h1 = (TH1F*)fH1;
h1->Fill(values[0]);
}
break;
case 2:
{
TH2F *h2 = (TH2F*)fH1;
h2->Fill(values[0], values[1]);
}
break;
case 3:
{
TH3F *h3 = (TH3F*)fH1;
h3->Fill(values[0], values[1], values[2]);
}
break;
default:
AliError(Form("Wrong size : %d", fSize));
delete [] values;
return kFALSE;
}
}
else
{
// check presence of output histogram
if (!fHSparse) {
AliError("Required a THnSparseF which is not initialized");
return kFALSE;
}
fHSparse->Fill(values);
}
delete [] values;
AliDebug(AliLog::kDebug +2,"->");
return kTRUE;
}
<commit_msg>Bugfix: clean allocated temporary memory in CreateHistogramSparse<commit_after>//
// Class AliRsnFunction
//
// This class defines a base classe to implement a function
// which uses the internal RSN package event format (AliRsnEvent).
// It contains some default flags which turn out to be useful:
// - a flag to select only the "true" pairs (tracks from same resonance)
// - a flag to know if the computation is done over two events (mixing)
//
// Any kind of analysis object should be implemented as inheriting from this
// because the AliRsnAnalyzer which executes the analysis will accept a collection
// of such objects, in order to have a unique format of processing method
//
// The user who implements a kind of computation type should inherit from
// this class and override the virtual functions defined in it, which
// initialize the final output histogram and define how to process data.
//
//
// author: A. Pulvirenti (email: alberto.pulvirenti@ct.infn.it)
//
#include <TString.h>
#include <TAxis.h>
#include "AliLog.h"
#include "AliRsnDaughter.h"
#include "AliRsnEvent.h"
#include "AliRsnPairDef.h"
#include "AliRsnMother.h"
#include "AliRsnValue.h"
#include "AliRsnFunction.h"
ClassImp(AliRsnFunction)
//________________________________________________________________________________________
AliRsnFunction::AliRsnFunction(Bool_t useTH1) :
TObject(),
fPairDef(0x0),
fAxisList("AliRsnValue", 0),
fPair(0x0),
fEvent(0x0),
fUseTH1(useTH1),
fSize(0),
fH1(0x0),
fHSparse(0x0)
{
//
// Constructor.
//
}
//________________________________________________________________________________________
AliRsnFunction::AliRsnFunction(const AliRsnFunction ©) :
TObject(copy),
fPairDef(copy.fPairDef),
fAxisList(copy.fAxisList),
fPair(copy.fPair),
fEvent(copy.fEvent),
fUseTH1(copy.fUseTH1),
fSize(copy.fSize),
fH1(0x0),
fHSparse(0x0)
{
//
// Copy constructor.
//
}
//________________________________________________________________________________________
const AliRsnFunction& AliRsnFunction::operator=(const AliRsnFunction& copy)
{
//
// Assignment operator.
//
//SetName(copy.GetName());
//SetTitle(copy.GetTitle());
fPairDef = copy.fPairDef;
fPair = copy.fPair;
fEvent = copy.fEvent;
fUseTH1 = copy.fUseTH1;
fSize = copy.fSize;
if (fH1) delete fH1;
fH1 = 0x0;
if (fHSparse) delete fHSparse;
fHSparse = 0x0;
return (*this);
}
//________________________________________________________________________________________
const char* AliRsnFunction::GetName() const
{
//
// Defines the name of this object according to
// the function type and binning
//
TString name("");
TObjArrayIter next(&fAxisList);
AliRsnValue *axis = 0;
while ((axis = (AliRsnValue*)next())) {
if (name.Length() > 1) name += '_';
name += axis->GetName();
}
return name.Data();
}
//________________________________________________________________________________________
void AliRsnFunction::AddAxis(AliRsnValue *const axis)
{
AliDebug(AliLog::kDebug+2,"<-");
Int_t size = fAxisList.GetEntries();
new(fAxisList[size]) AliRsnValue(*axis);
AliDebug(AliLog::kDebug+2,"->");
if (fAxisList.GetEntries() > 3)
{
AliWarning("A TH1-type output cannot add more than 3 axes: switching to THnSparse -- THIS COULD CAUSE VERY LARGE FILES!!!");
fUseTH1 = kFALSE;
}
}
//________________________________________________________________________________________
TH1* AliRsnFunction::CreateHistogram(const char *histoName, const char *histoTitle)
{
//
// Creates and returns the histogram defined using
// arguments fo name and title, and the first histoDef for binning.
// Variable-sized histogram binning is always called, due to use of histoDef,
// even if the bins are equal, since they are defined in this class.
// Eventually present histoDef's in other slots of array (1, 2) are ignored.
//
// This version produces a THnSparseF.
//
fSize = fAxisList.GetEntries();
if (!fSize) {
AliError("No axes defined");
return 0x0;
}
else if (fSize < 1 || fSize > 3)
{
AliError("Too few or too many axes defined");
return 0x0;
}
// retrieve binnings for main and secondary axes
AliRsnValue *fcnAxis;
TArrayD array[3];
for (Int_t i = 0; i < fSize; i++)
{
fcnAxis = (AliRsnValue*)fAxisList.At(i);
if (!fcnAxis)
{
AliError("Empty axis");
array[i].Set(2);
array[i][0] = -1E5;
array[i][1] = -1E5;
continue;
}
else
{
array[i] = fcnAxis->GetArray();
}
}
// create histogram depending on the number of axes
switch (fSize)
{
case 1:
fH1 = new TH1F(histoName, histoTitle, array[0].GetSize() - 1, array[0].GetArray());
break;
case 2:
fH1 = new TH2F(histoName, histoTitle, array[0].GetSize() - 1, array[0].GetArray(), array[1].GetSize() - 1, array[1].GetArray());
break;
case 3:
fH1 = new TH3F(histoName, histoTitle, array[0].GetSize() - 1, array[0].GetArray(), array[1].GetSize() - 1, array[1].GetArray(), array[2].GetSize() - 1, array[2].GetArray());
break;
}
fH1->Sumw2();
return fH1;
}
//________________________________________________________________________________________
THnSparseF* AliRsnFunction::CreateHistogramSparse(const char *histoName, const char *histoTitle)
{
//
// Creates and returns the histogram defined using
// arguments fo name and title, and the first histoDef for binning.
// Variable-sized histogram binning is always called, due to use of histoDef,
// even if the bins are equal, since they are defined in this class.
// Eventually present histoDef's in other slots of array (1, 2) are ignored.
//
// This version produces a THnSparseF.
//
fSize = fAxisList.GetEntries();
if (!fSize) {
AliError("No axes defined");
return 0x0;
}
// initialize the array of number of bins for each axis
// taking it from the stored values, while for the bins
// they are set as summied and defined later
Double_t dummyD;
Int_t *nbins = new Int_t[fSize];
AliRsnValue *fcnAxis = 0;
for (Int_t i = 0; i < fSize; i++)
{
fcnAxis = (AliRsnValue*)fAxisList.At(i);
if (!fcnAxis)
{
nbins[i] = 1;
AliError("Empty axis");
continue;
}
nbins[i] = fcnAxis->GetArray().GetSize() - 1;
}
// create histogram
fHSparse = new THnSparseF(histoName, histoTitle, fSize, nbins, &dummyD, &dummyD);
fHSparse->Sumw2();
// update the various axes using the definitions given in the array of axes here
for (Int_t i = 0; i < fSize; i++)
{
fcnAxis = (AliRsnValue*)fAxisList.At(i);
if (!fcnAxis) {
AliError("Empty axis: doing unique bin betweeen -100000 and 100000");
continue;
}
fHSparse->SetBinEdges(i, fcnAxis->GetArray().GetArray());
}
delete [] nbins;
return fHSparse;
}
//________________________________________________________________________________________
Bool_t AliRsnFunction::Fill()
{
//
// Fill function histogram with values computed from given input object.
//
AliDebug(AliLog::kDebug +2,"->");
Int_t i;
Double_t *values = new Double_t[fSize];
AliRsnValue *fcnAxis = 0;
for (i = 0; i < fSize; i++) {
fcnAxis = (AliRsnValue*)fAxisList.At(i);
if (!fcnAxis)
{
values[i] = 0.0;
continue;
}
if (fcnAxis->Eval(fPair, fPairDef, fEvent)) values[i] = (Double_t)((Float_t)fcnAxis->GetValue());
}
// fill histogram
if (fUseTH1)
{
// check presence of output histogram
if (!fH1) {
AliError("Required a TH1 which is not initialized");
delete [] values;
return kFALSE;
}
// fill according to dimensions
switch (fSize)
{
case 1:
{
TH1F *h1 = (TH1F*)fH1;
h1->Fill(values[0]);
}
break;
case 2:
{
TH2F *h2 = (TH2F*)fH1;
h2->Fill(values[0], values[1]);
}
break;
case 3:
{
TH3F *h3 = (TH3F*)fH1;
h3->Fill(values[0], values[1], values[2]);
}
break;
default:
AliError(Form("Wrong size : %d", fSize));
delete [] values;
return kFALSE;
}
}
else
{
// check presence of output histogram
if (!fHSparse) {
AliError("Required a THnSparseF which is not initialized");
return kFALSE;
}
fHSparse->Fill(values);
}
delete [] values;
AliDebug(AliLog::kDebug +2,"->");
return kTRUE;
}
<|endoftext|>
|
<commit_before>#include "../window.h"
#include "../resources.h"
#include <tween/tween.h>
#include <coreutils/format.h>
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unordered_map>
#include <functional>
#include <bcm_host.h>
using namespace std;
//bool initEGL(EGLConfig& eglConfig, EGLContext& eglContext, EGLDisplay& eglDisplay);
bool initEGL(EGLConfig& eglConfig, EGLContext& eglContext, EGLDisplay& eglDisplay, EGLSurface &eglSurface, EGLNativeWindowType nativeWin);
namespace grappix {
Window::Window() : RenderTarget(), winOpen(false), bmCounter(0), lockIt(false) {
NO_CLICK.x = NO_CLICK.y = NO_CLICK.button = -1;
}
void Window::open(bool fs) {
open(0,0,fs);
}
std::deque<int> Window::key_buffer;
static uint8_t pressed_keys[256];
Window::click Window::NO_CLICK = { -1, -1, -1};
static function<void(uint32_t)> renderLoopFunction;
static EGL_DISPMANX_WINDOW_T nativewindow;
static EGLConfig eglConfig;
static EGLContext eglContext;
static EGLDisplay eglDisplay;
static EGLSurface eglSurface;
void Window::open(int w, int h, bool fs) {
if(winOpen)
return;
bcm_host_init();
DISPMANX_ELEMENT_HANDLE_T dispman_element;
DISPMANX_DISPLAY_HANDLE_T dispman_display;
DISPMANX_UPDATE_HANDLE_T dispman_update;
VC_RECT_T dst_rect;
VC_RECT_T src_rect;
uint32_t display_width;
uint32_t display_height;
// create an EGL window surface, passing context width/height
int success = graphics_get_display_size(0 /* LCD */, &display_width, &display_height);
if(success < 0)
throw display_exception("Cound not get display size");
// You can hardcode the resolution here:
//display_width = 640;
//display_height = 480;
LOGD("Display %dx%d", display_width, display_height);
//display_width = 640;
//display_height = 480;
dst_rect.x = 0;
dst_rect.y = 0;
dst_rect.width = display_width;
dst_rect.height = display_height;
src_rect.x = 0;
src_rect.y = 0;
src_rect.width = display_width << 16;
src_rect.height = display_height << 16;
dispman_display = vc_dispmanx_display_open(0 /* LCD */);
dispman_update = vc_dispmanx_update_start(0);
dispman_element = vc_dispmanx_element_add(dispman_update,
dispman_display, 0/*layer*/, &dst_rect, 0/*src*/,
&src_rect, DISPMANX_PROTECTION_NONE, nullptr /*alpha*/,
nullptr/*clamp*/, DISPMANX_NO_ROTATE);
LOGD("Dispelement %d", dispman_element);
nativewindow.element = dispman_element;
nativewindow.width = display_width;
nativewindow.height = display_height;
vc_dispmanx_update_submit_sync(dispman_update);
initEGL(eglConfig, eglContext, eglDisplay, eglSurface, &nativewindow);
//eglSurface = eglCreateWindowSurface(eglDisplay, eglConfig, &nativewindow, NULL);
/*
LOGI("Surface %p", eglSurface);
if (eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext) == EGL_FALSE) {
LOGI("Unable to eglMakeCurrent");
return;
}
*/
setup(display_width, display_height);
memset(pressed_keys, 0, sizeof(pressed_keys));
keyboardThread = thread([=]() {
uint8_t buf[8];
int k = ::open("/dev/hidraw0", O_RDONLY);
fprintf(stderr, "Reading kbd");
while(true) {
read(k, buf, 8);
for(int i=2; i<5; i++) {
auto k = buf[i];
if(k) {
if(!pressed_keys[k]) {
fprintf(stderr, utils::format("Got key %02x\n", k).c_str());
key_buffer.push_back(k);
}
pressed_keys[k] = 2;
}
}
for(int i=0; i<256; i++) {
if(pressed_keys[i])
pressed_keys[i]--;
}
}
});
keyboardThread.detach();
atexit([](){
if(!renderLoopFunction) {
while(screen.is_open()) {
screen.update_callbacks();
screen.flip();
}
}
});
};
void Window::render_loop(function<void(uint32_t)> f, int fps) {
renderLoopFunction = f;
//atexit([](){
auto lastMs = utils::getms();
while(screen.is_open()) {
screen.update_callbacks();
auto ms = utils::getms();
uint32_t rate = ms - lastMs;
lastMs = ms;
renderLoopFunction(rate);
//while(screen.locked()) {
// utils::sleepms(5);
//}
}
//});
}
void Window::flip() {
if(eglDisplay != EGL_NO_DISPLAY) {
eglSwapBuffers(eglDisplay, eglSurface);
//eglQuerySurface(eglDisplay, eglSurface, EGL_WIDTH, &screenWidth);
//eglQuerySurface(eglDisplay, eglSurface, EGL_HEIGHT, &screenHeight);
}
auto t = chrono::high_resolution_clock::now();
auto ms = chrono::duration_cast<chrono::microseconds>(t - startTime).count();
tween::Tween::updateTweens(ms / 1000000.0f);
}
bool Window::mouse_pressed() {
return false;
}
tuple<int, int> Window::mouse_position() {
return make_tuple(-1,-1);
}
bool Window::key_pressed(key k) {
auto rawkey = translate[k];
return (pressed_keys[rawkey] != 0);
}
bool Window::key_pressed(char k) {
int rawkey = k - 'A' + 0x4;
return (pressed_keys[rawkey] != 0);
}
Window::click Window::get_click(bool peek) {
/* if(click_buffer.size() > 0) {
auto k = click_buffer.front();
if(!peek)
click_buffer.pop_front();
return k;
}*/
return NO_CLICK;
}
unordered_map<int, int> Window::translate = {
{ ENTER, 0x28 },
{ SPACE, 0x2C },
{ RIGHT, 0x4f },
{ LEFT, 0x50 },
{ DOWN, 0x51 },
{ UP, 0x52 },
{ ESCAPE, 0x29 },
{ BACKSPACE, 0x2a },
};
Window::key Window::get_key(bool peek) {
if(key_buffer.size() > 0) {
auto k = key_buffer.front();
if(!peek)
key_buffer.pop_front();
if(k >= 0x04 && k <= 0x20)
k += ('A'-0x04);
else {
for(auto t : translate) {
LOGD("?? %02x", t.second);
if(t.second == k)
return (key)t.first;
}
}
LOGD(">> %02x", (key)k);
return (key)k;
}
return NO_KEY;
};
Window screen;
}<commit_msg>Function keys for PI<commit_after>#include "../window.h"
#include "../resources.h"
#include <tween/tween.h>
#include <coreutils/format.h>
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unordered_map>
#include <functional>
#include <bcm_host.h>
using namespace std;
//bool initEGL(EGLConfig& eglConfig, EGLContext& eglContext, EGLDisplay& eglDisplay);
bool initEGL(EGLConfig& eglConfig, EGLContext& eglContext, EGLDisplay& eglDisplay, EGLSurface &eglSurface, EGLNativeWindowType nativeWin);
namespace grappix {
Window::Window() : RenderTarget(), winOpen(false), bmCounter(0), lockIt(false) {
NO_CLICK.x = NO_CLICK.y = NO_CLICK.button = -1;
}
void Window::open(bool fs) {
open(0,0,fs);
}
std::deque<int> Window::key_buffer;
static uint8_t pressed_keys[256];
Window::click Window::NO_CLICK = { -1, -1, -1};
static function<void(uint32_t)> renderLoopFunction;
static EGL_DISPMANX_WINDOW_T nativewindow;
static EGLConfig eglConfig;
static EGLContext eglContext;
static EGLDisplay eglDisplay;
static EGLSurface eglSurface;
void Window::open(int w, int h, bool fs) {
if(winOpen)
return;
bcm_host_init();
DISPMANX_ELEMENT_HANDLE_T dispman_element;
DISPMANX_DISPLAY_HANDLE_T dispman_display;
DISPMANX_UPDATE_HANDLE_T dispman_update;
VC_RECT_T dst_rect;
VC_RECT_T src_rect;
uint32_t display_width;
uint32_t display_height;
// create an EGL window surface, passing context width/height
int success = graphics_get_display_size(0 /* LCD */, &display_width, &display_height);
if(success < 0)
throw display_exception("Cound not get display size");
// You can hardcode the resolution here:
//display_width = 640;
//display_height = 480;
LOGD("Display %dx%d", display_width, display_height);
//display_width = 640;
//display_height = 480;
dst_rect.x = 0;
dst_rect.y = 0;
dst_rect.width = display_width;
dst_rect.height = display_height;
src_rect.x = 0;
src_rect.y = 0;
src_rect.width = display_width << 16;
src_rect.height = display_height << 16;
dispman_display = vc_dispmanx_display_open(0 /* LCD */);
dispman_update = vc_dispmanx_update_start(0);
dispman_element = vc_dispmanx_element_add(dispman_update,
dispman_display, 0/*layer*/, &dst_rect, 0/*src*/,
&src_rect, DISPMANX_PROTECTION_NONE, nullptr /*alpha*/,
nullptr/*clamp*/, DISPMANX_NO_ROTATE);
LOGD("Dispelement %d", dispman_element);
nativewindow.element = dispman_element;
nativewindow.width = display_width;
nativewindow.height = display_height;
vc_dispmanx_update_submit_sync(dispman_update);
initEGL(eglConfig, eglContext, eglDisplay, eglSurface, &nativewindow);
//eglSurface = eglCreateWindowSurface(eglDisplay, eglConfig, &nativewindow, NULL);
/*
LOGI("Surface %p", eglSurface);
if (eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext) == EGL_FALSE) {
LOGI("Unable to eglMakeCurrent");
return;
}
*/
setup(display_width, display_height);
memset(pressed_keys, 0, sizeof(pressed_keys));
keyboardThread = thread([=]() {
uint8_t buf[8];
int k = ::open("/dev/hidraw0", O_RDONLY);
fprintf(stderr, "Reading kbd");
while(true) {
read(k, buf, 8);
for(int i=2; i<5; i++) {
auto k = buf[i];
if(k) {
if(!pressed_keys[k]) {
fprintf(stderr, utils::format("Got key %02x\n", k).c_str());
key_buffer.push_back(k);
}
pressed_keys[k] = 2;
}
}
for(int i=0; i<256; i++) {
if(pressed_keys[i])
pressed_keys[i]--;
}
}
});
keyboardThread.detach();
atexit([](){
if(!renderLoopFunction) {
while(screen.is_open()) {
screen.update_callbacks();
screen.flip();
}
}
});
};
void Window::render_loop(function<void(uint32_t)> f, int fps) {
renderLoopFunction = f;
//atexit([](){
auto lastMs = utils::getms();
while(screen.is_open()) {
screen.update_callbacks();
auto ms = utils::getms();
uint32_t rate = ms - lastMs;
lastMs = ms;
renderLoopFunction(rate);
//while(screen.locked()) {
// utils::sleepms(5);
//}
}
//});
}
void Window::flip() {
if(eglDisplay != EGL_NO_DISPLAY) {
eglSwapBuffers(eglDisplay, eglSurface);
//eglQuerySurface(eglDisplay, eglSurface, EGL_WIDTH, &screenWidth);
//eglQuerySurface(eglDisplay, eglSurface, EGL_HEIGHT, &screenHeight);
}
auto t = chrono::high_resolution_clock::now();
auto ms = chrono::duration_cast<chrono::microseconds>(t - startTime).count();
tween::Tween::updateTweens(ms / 1000000.0f);
}
bool Window::mouse_pressed() {
return false;
}
tuple<int, int> Window::mouse_position() {
return make_tuple(-1,-1);
}
bool Window::key_pressed(key k) {
auto rawkey = translate[k];
return (pressed_keys[rawkey] != 0);
}
bool Window::key_pressed(char k) {
int rawkey = k - 'A' + 0x4;
return (pressed_keys[rawkey] != 0);
}
Window::click Window::get_click(bool peek) {
/* if(click_buffer.size() > 0) {
auto k = click_buffer.front();
if(!peek)
click_buffer.pop_front();
return k;
}*/
return NO_CLICK;
}
unordered_map<int, int> Window::translate = {
{ ENTER, 0x28 },
{ SPACE, 0x2C },
{ RIGHT, 0x4f },
{ LEFT, 0x50 },
{ DOWN, 0x51 },
{ UP, 0x52 },
{ ESCAPE, 0x29 },
{ BACKSPACE, 0x2a },
};
Window::key Window::get_key(bool peek) {
if(key_buffer.size() > 0) {
auto k = key_buffer.front();
if(!peek)
key_buffer.pop_front();
if(k >= 0x3a && k <= 0x45)
k += (F1-0x3a);
else
if(k >= 0x04 && k <= 0x20)
k += ('A'-0x04);
else {
for(auto t : translate) {
LOGD("?? %02x", t.second);
if(t.second == k)
return (key)t.first;
}
}
LOGD(">> %02x", (key)k);
return (key)k;
}
return NO_KEY;
};
Window screen;
}<|endoftext|>
|
<commit_before>AliESDtrackCuts* CreateCuts(Bool_t fieldOn = kTRUE, Bool_t hists = kTRUE);
AliAnalysisTask* AddTaskFilteredTree(TString outputFile="")
{
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->Load("libTender");
gSystem->Load("libCORRFW");
gSystem->Load("libPWGUDbase");
gSystem->Load("libTPCcalib");
gSystem->Load("libPWGPP");
gSystem->Load("libPWGLFspectra");
::Info("AddTaskFilteredTree","BEGIN");
printf("AddTaskFilteredTree::BEGIN\n");
gRandom->SetSeed(0);
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskFilteredTree", "No analysis manager found.");
return 0;
}
// Switch off all AliInfo (too much output!!!)
AliLog::SetGlobalLogLevel(AliLog::kError);
mgr->SetDebugLevel(0);
//
// Create physics trigger selection class
//
//AliPhysicsSelection *physTrigSel = new AliPhysicsSelection();
//
// Create event cuts
//
Float_t zvWindow = 30. ;
AliFilteredTreeEventCuts *evtCuts = new AliFilteredTreeEventCuts("AliFilteredTreeEventCuts","Event cuts");
evtCuts->SetZvRange(-zvWindow,zvWindow);
evtCuts->SetMeanXYZv(0.0,0.0,0.0);
evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
evtCuts->SetTriggerRequired(kFALSE);
//evtCuts->SetTriggerRequired(kTRUE);
//
// Create geom. acceptance cuts
//
Float_t etaWindow = 1.0 ;
Float_t ptMin = 0.15 ;
AliFilteredTreeAcceptanceCuts *accCuts = new AliFilteredTreeAcceptanceCuts("AliFilteredTreeAcceptanceCuts","Geom. acceptance cuts");
accCuts->SetEtaRange(-etaWindow,etaWindow);
accCuts->SetPtRange(ptMin,1.e10);
accCuts->SetMaxDCAr(3.0);
accCuts->SetMaxDCAz(30.0);
//
// Create standard esd track cuts
//
AliESDtrackCuts* esdTrackCuts = CreateCuts();
if (!esdTrackCuts) {
printf("ERROR: esdTrackCuts could not be created\n");
return 0;
} else {
esdTrackCuts->SetHistogramsOn(kTRUE);
}
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
//
// Create task
//
AliAnalysisTaskFilteredTree *task = new AliAnalysisTaskFilteredTree("AliAnalysisTaskFilteredTree");
//task->SetUseMCInfo(hasMC);
//task->SetLowPtTrackDownscaligF(1.e4);
//task->SetLowPtV0DownscaligF(1.e2);
task->SetLowPtTrackDownscaligF(1.e5);
task->SetLowPtV0DownscaligF(2.e3);
task->SetProcessAll(kTRUE);
task->SetProcessCosmics(kTRUE);
if (gSystem->Getenv("AliAnalysisTaskFilteredTree_SetLowPtTrackDownscalingF")) {
Float_t downscale=TString(gSystem->Getenv("AliAnalysisTaskFilteredTree_SetLowPtTrackDownscalingF")).Atof();
task->SetLowPtTrackDownscaligF(downscale);
printf("AliAnalysisTaskFilteredTree_SetLowPtTrackDownscalingF: From env. variable\t%f\n", downscale);
}else {
::Info("AliAnalysisTaskFilteredTree__SetLowPtTrackDownscalingF", "Use default");
printf("AliAnalysisTaskFilteredTree_SetLowPtV0DownscalingF::Use DEFAULT\t\n");
}
if (gSystem->Getenv("AliAnalysisTaskFilteredTree_SetLowPtV0DownscalingF")) {
Float_t downscale=TString(gSystem->Getenv("AliAnalysisTaskFilteredTree_SetLowPtV0DownscalingF")).Atof();
task->SetLowPtV0DownscaligF(downscale);
printf("AliAnalysisTaskFilteredTree_SetLowPtV0DownscalingF:From enc. variable\t%f\n",downscale);
}else {
printf("AliAnalysisTaskFilteredTree_SetLowPtV0DownscalingF::Use DEFAULT\t\n");
}
//task->Dump();
//task->SetProcessAll(kFALSE);
//task->SetFillTrees(kFALSE); // only histograms are filled
// trigger
//task->SelectCollisionCandidates(AliVEvent::kMB);
//
// set analysis options from the Helper here !!!
//
// AlidNdPtHelper::OutputObject outputObject = AlidNdPtHelper::kCutAnalysisPbPb;
// AlidNdPtHelper::ParticleMode particleMode = AlidNdPtHelper::kAllPart ;
//AlidNdPtHelper::AnalysisMode analysisMode = AlidNdPtHelper::kTPCITS;
task->SetEventCuts(evtCuts);
task->SetAcceptanceCuts(accCuts);
task->SetTrackCuts(esdTrackCuts);
task->SetAnalysisMode(AliAnalysisTaskFilteredTree::kTPCITSAnalysisMode);
task->SetCentralityEstimator("V0M");
// Add task
mgr->AddTask(task);
// Create containers for input
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
mgr->ConnectInput(task, 0, cinput);
if (outputFile.IsNull())
outputFile=Form("%s", AliAnalysisManager::GetCommonFileName());
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("filtered1", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 1, coutput1);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("filtered2", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 2, coutput2);
AliAnalysisDataContainer *coutput3 = mgr->CreateContainer("filtered3", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 3, coutput3);
AliAnalysisDataContainer *coutput4 = mgr->CreateContainer("filtered4", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 4, coutput4);
AliAnalysisDataContainer *coutput5 = mgr->CreateContainer("filtered5", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 5, coutput5);
AliAnalysisDataContainer *coutput6 = mgr->CreateContainer("filtered6", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 6, coutput6);
// store histograms in the separate file
TString outputFileHisto = "PtResHistograms.root";
AliAnalysisDataContainer *coutput7 = mgr->CreateContainer("histo7", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileHisto.Data());
mgr->ConnectOutput(task, 7, coutput7);
::Info("AddTaskFilteredTree","END");
printf("AddTaskFilteredTree::END\n");
return task;
}
AliESDtrackCuts* CreateCuts(Bool_t fieldOn = kTRUE, Bool_t hists = kTRUE)
{
AliESDtrackCuts* esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts");
if(!esdTrackCuts) return 0;
if (hists)
esdTrackCuts->DefineHistograms(1);
Double_t cov1, cov2, cov3, cov4, cov5;
Double_t nSigma;
Double_t maxDCAtoVertex, maxDCAtoVertexXY, maxDCAtoVertexZ;
Double_t minNClustersTPC;
Double_t maxChi2PerClusterTPC;
Double_t minPt, maxPt;
//
// TPC
//
esdTrackCuts->SetRequireTPCRefit(kTRUE);
esdTrackCuts->SetAcceptKinkDaughters(kFALSE);
//
// ITS
//
//esdTrackCuts->SetRequireITSRefit(kTRUE);
//esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kAny);
//
TString tag = "TPC+ITS refit and KinkRejection required - for cut studies";
// cuts for data without field
if (!fieldOn)
{
cov5 = 1e10;
tag += " without field";
}
Printf("Created track cuts for: %s", tag.Data());
return esdTrackCuts;
}
<commit_msg>fix for redefinition of default argument (for ROOT6)<commit_after>AliESDtrackCuts* CreateCuts(Bool_t fieldOn = kTRUE, Bool_t hists = kTRUE);
AliAnalysisTask* AddTaskFilteredTree(TString outputFile="")
{
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->Load("libTender");
gSystem->Load("libCORRFW");
gSystem->Load("libPWGUDbase");
gSystem->Load("libTPCcalib");
gSystem->Load("libPWGPP");
gSystem->Load("libPWGLFspectra");
::Info("AddTaskFilteredTree","BEGIN");
printf("AddTaskFilteredTree::BEGIN\n");
gRandom->SetSeed(0);
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskFilteredTree", "No analysis manager found.");
return 0;
}
// Switch off all AliInfo (too much output!!!)
AliLog::SetGlobalLogLevel(AliLog::kError);
mgr->SetDebugLevel(0);
//
// Create physics trigger selection class
//
//AliPhysicsSelection *physTrigSel = new AliPhysicsSelection();
//
// Create event cuts
//
Float_t zvWindow = 30. ;
AliFilteredTreeEventCuts *evtCuts = new AliFilteredTreeEventCuts("AliFilteredTreeEventCuts","Event cuts");
evtCuts->SetZvRange(-zvWindow,zvWindow);
evtCuts->SetMeanXYZv(0.0,0.0,0.0);
evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
evtCuts->SetTriggerRequired(kFALSE);
//evtCuts->SetTriggerRequired(kTRUE);
//
// Create geom. acceptance cuts
//
Float_t etaWindow = 1.0 ;
Float_t ptMin = 0.15 ;
AliFilteredTreeAcceptanceCuts *accCuts = new AliFilteredTreeAcceptanceCuts("AliFilteredTreeAcceptanceCuts","Geom. acceptance cuts");
accCuts->SetEtaRange(-etaWindow,etaWindow);
accCuts->SetPtRange(ptMin,1.e10);
accCuts->SetMaxDCAr(3.0);
accCuts->SetMaxDCAz(30.0);
//
// Create standard esd track cuts
//
AliESDtrackCuts* esdTrackCuts = CreateCuts();
if (!esdTrackCuts) {
printf("ERROR: esdTrackCuts could not be created\n");
return 0;
} else {
esdTrackCuts->SetHistogramsOn(kTRUE);
}
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
//
// Create task
//
AliAnalysisTaskFilteredTree *task = new AliAnalysisTaskFilteredTree("AliAnalysisTaskFilteredTree");
//task->SetUseMCInfo(hasMC);
//task->SetLowPtTrackDownscaligF(1.e4);
//task->SetLowPtV0DownscaligF(1.e2);
task->SetLowPtTrackDownscaligF(1.e5);
task->SetLowPtV0DownscaligF(2.e3);
task->SetProcessAll(kTRUE);
task->SetProcessCosmics(kTRUE);
if (gSystem->Getenv("AliAnalysisTaskFilteredTree_SetLowPtTrackDownscalingF")) {
Float_t downscale=TString(gSystem->Getenv("AliAnalysisTaskFilteredTree_SetLowPtTrackDownscalingF")).Atof();
task->SetLowPtTrackDownscaligF(downscale);
printf("AliAnalysisTaskFilteredTree_SetLowPtTrackDownscalingF: From env. variable\t%f\n", downscale);
}else {
::Info("AliAnalysisTaskFilteredTree__SetLowPtTrackDownscalingF", "Use default");
printf("AliAnalysisTaskFilteredTree_SetLowPtV0DownscalingF::Use DEFAULT\t\n");
}
if (gSystem->Getenv("AliAnalysisTaskFilteredTree_SetLowPtV0DownscalingF")) {
Float_t downscale=TString(gSystem->Getenv("AliAnalysisTaskFilteredTree_SetLowPtV0DownscalingF")).Atof();
task->SetLowPtV0DownscaligF(downscale);
printf("AliAnalysisTaskFilteredTree_SetLowPtV0DownscalingF:From enc. variable\t%f\n",downscale);
}else {
printf("AliAnalysisTaskFilteredTree_SetLowPtV0DownscalingF::Use DEFAULT\t\n");
}
//task->Dump();
//task->SetProcessAll(kFALSE);
//task->SetFillTrees(kFALSE); // only histograms are filled
// trigger
//task->SelectCollisionCandidates(AliVEvent::kMB);
//
// set analysis options from the Helper here !!!
//
// AlidNdPtHelper::OutputObject outputObject = AlidNdPtHelper::kCutAnalysisPbPb;
// AlidNdPtHelper::ParticleMode particleMode = AlidNdPtHelper::kAllPart ;
//AlidNdPtHelper::AnalysisMode analysisMode = AlidNdPtHelper::kTPCITS;
task->SetEventCuts(evtCuts);
task->SetAcceptanceCuts(accCuts);
task->SetTrackCuts(esdTrackCuts);
task->SetAnalysisMode(AliAnalysisTaskFilteredTree::kTPCITSAnalysisMode);
task->SetCentralityEstimator("V0M");
// Add task
mgr->AddTask(task);
// Create containers for input
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
mgr->ConnectInput(task, 0, cinput);
if (outputFile.IsNull())
outputFile=Form("%s", AliAnalysisManager::GetCommonFileName());
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("filtered1", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 1, coutput1);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("filtered2", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 2, coutput2);
AliAnalysisDataContainer *coutput3 = mgr->CreateContainer("filtered3", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 3, coutput3);
AliAnalysisDataContainer *coutput4 = mgr->CreateContainer("filtered4", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 4, coutput4);
AliAnalysisDataContainer *coutput5 = mgr->CreateContainer("filtered5", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 5, coutput5);
AliAnalysisDataContainer *coutput6 = mgr->CreateContainer("filtered6", TTree::Class(), AliAnalysisManager::kOutputContainer, outputFile.Data());
mgr->ConnectOutput(task, 6, coutput6);
// store histograms in the separate file
TString outputFileHisto = "PtResHistograms.root";
AliAnalysisDataContainer *coutput7 = mgr->CreateContainer("histo7", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileHisto.Data());
mgr->ConnectOutput(task, 7, coutput7);
::Info("AddTaskFilteredTree","END");
printf("AddTaskFilteredTree::END\n");
return task;
}
AliESDtrackCuts* CreateCuts(Bool_t fieldOn, Bool_t hists)
{
AliESDtrackCuts* esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts");
if(!esdTrackCuts) return 0;
if (hists)
esdTrackCuts->DefineHistograms(1);
Double_t cov1, cov2, cov3, cov4, cov5;
Double_t nSigma;
Double_t maxDCAtoVertex, maxDCAtoVertexXY, maxDCAtoVertexZ;
Double_t minNClustersTPC;
Double_t maxChi2PerClusterTPC;
Double_t minPt, maxPt;
//
// TPC
//
esdTrackCuts->SetRequireTPCRefit(kTRUE);
esdTrackCuts->SetAcceptKinkDaughters(kFALSE);
//
// ITS
//
//esdTrackCuts->SetRequireITSRefit(kTRUE);
//esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kAny);
//
TString tag = "TPC+ITS refit and KinkRejection required - for cut studies";
// cuts for data without field
if (!fieldOn)
{
cov5 = 1e10;
tag += " without field";
}
Printf("Created track cuts for: %s", tag.Data());
return esdTrackCuts;
}
<|endoftext|>
|
<commit_before>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "vector.h"
TEST_CASE("Vector default ctor") {
Vector v;
for (unsigned i = 0; i < v.n; ++i) {
REQUIRE(v[i] == 0.0);
}
}<commit_msg>some unittests added<commit_after>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "vector.h"
typedef double Vec3[3];
void cmp_vec_arr(const Vector &lhs, const Vec3 &rhs) {
assert(Vector::n == sizeof(rhs)/sizeof(rhs[0]));
for (unsigned i = 0; i < Vector::n; ++i) {
REQUIRE(lhs[i] == rhs[i]);
}
}
TEST_CASE("Vector default ctor") {
Vector v;
Vec3 expected = {0.0, 0.0, 0.0};
cmp_vec_arr(v, expected);
}
TEST_CASE("Vector init value ctor") {
SECTION("Zeros") {
Vector v{0};
Vec3 expected = {0.0, 0.0, 0.0};
cmp_vec_arr(v, expected);
}
SECTION("Ones") {
Vector v{1.0};
Vec3 expected = {1.0, 1.0, 1.0};
cmp_vec_arr(v, expected);
}
SECTION("Minus ones") {
Vector v{-1.0};
Vec3 expected = {-1.0, -1.0, -1.0};
cmp_vec_arr(v, expected);
}
SECTION("42") {
Vector v{42};
Vec3 expected = {42.0, 42.0, 42.0};
cmp_vec_arr(v, expected);
}
}
TEST_CASE("Vector copy ctor") {
SECTION("Zeros") {
Vector v{0};
Vector copy{v};
Vec3 expected = {0.0, 0.0, 0.0};
cmp_vec_arr(copy, expected);
}
SECTION("Ones") {
Vector v{1.0};
Vector copy{v};
Vec3 expected = {1.0, 1.0, 1.0};
cmp_vec_arr(copy, expected);
}
SECTION("Minus ones") {
Vector v{-1.0};
Vector copy{v};
Vec3 expected = {-1.0, -1.0, -1.0};
cmp_vec_arr(copy, expected);
}
SECTION("42") {
Vector v{42};
Vector copy{v};
Vec3 expected = {42.0, 42.0, 42.0};
cmp_vec_arr(copy, expected);
}
}
TEST_CASE("Vector copy assignment") {
SECTION("Zeros") {
Vector v{0}, copy;
copy = v;
Vec3 expected = {0.0, 0.0, 0.0};
cmp_vec_arr(copy, expected);
}
SECTION("Ones") {
Vector v{1.0}, copy;
copy = v;
Vec3 expected = {1.0, 1.0, 1.0};
cmp_vec_arr(copy, expected);
}
SECTION("Minus ones") {
Vector v{-1.0}, copy;
copy = v;
Vec3 expected = {-1.0, -1.0, -1.0};
cmp_vec_arr(copy, expected);
}
SECTION("42") {
Vector v{42}, copy;
copy = v;
Vec3 expected = {42.0, 42.0, 42.0};
cmp_vec_arr(copy, expected);
}
}
TEST_CASE("Indexing operator") {
Vector v;
Vec3 expected = {1.0, 2.0, 3.0};
for (unsigned long i = 0; i < Vector::n; ++i) {
v[i] = expected[i];
}
cmp_vec_arr(v, expected);
}<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013, Hernan Saez
* 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 <organization> 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 <COPYRIGHT HOLDER> 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 "StreamingSystem.hpp"
#include "Simulation/Simulation.hpp"
#include "Simulation/FileSystem.hpp"
#include "Concurrency/Async.hpp"
using namespace crimild;
StreamingSystem::StreamingSystem( void )
: System( "Streaming System" )
{
CRIMILD_BIND_MEMBER_MESSAGE_HANDLER( messaging::LoadScene, StreamingSystem, onLoadScene );
CRIMILD_BIND_MEMBER_MESSAGE_HANDLER( messaging::ReloadScene, StreamingSystem, onReloadScene );
}
StreamingSystem::~StreamingSystem( void )
{
}
bool StreamingSystem::start( void )
{
return System::start();
}
void StreamingSystem::stop( void )
{
}
void StreamingSystem::onLoadScene( messaging::LoadScene const &message )
{
if ( message.sceneBuilder != nullptr ) {
setSceneBuilder( message.sceneBuilder );
}
loadScene( message.filename, getSceneBuilder() );
}
void StreamingSystem::onReloadScene( messaging::ReloadScene const &message )
{
auto sceneName = _lastSceneFileName;
auto builder = getSceneBuilder();
auto self = this;
crimild::async( crimild::AsyncDispatchPolicy::MAIN_QUEUE, [self, sceneName, builder] {
Simulation::getInstance()->setScene( nullptr );
self->loadScene( sceneName, builder );
});
}
void StreamingSystem::loadScene( std::string filename, SceneBuilder *builder )
{
if ( builder == nullptr ) {
Log::Error << "Undefined scene builder" << Log::End;
return;
}
_lastSceneFileName = filename;
crimild::async( crimild::AsyncDispatchPolicy::BACKGROUND_QUEUE, [builder, filename] {
builder->reset();
auto scene = builder->fromFile( FileSystem::getInstance().pathForResource( filename ) );
builder->reset();
crimild::async( crimild::AsyncDispatchPolicy::MAIN_QUEUE, [scene] {
Simulation::getInstance()->setScene( scene );
});
});
}
<commit_msg>Sync scene loading with frame rendering<commit_after>/*
* Copyright (c) 2013, Hernan Saez
* 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 <organization> 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 <COPYRIGHT HOLDER> 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 "StreamingSystem.hpp"
#include "Simulation/Simulation.hpp"
#include "Simulation/FileSystem.hpp"
#include "Concurrency/Async.hpp"
using namespace crimild;
StreamingSystem::StreamingSystem( void )
: System( "Streaming System" )
{
CRIMILD_BIND_MEMBER_MESSAGE_HANDLER( messaging::LoadScene, StreamingSystem, onLoadScene );
CRIMILD_BIND_MEMBER_MESSAGE_HANDLER( messaging::ReloadScene, StreamingSystem, onReloadScene );
}
StreamingSystem::~StreamingSystem( void )
{
}
bool StreamingSystem::start( void )
{
return System::start();
}
void StreamingSystem::stop( void )
{
}
void StreamingSystem::onLoadScene( messaging::LoadScene const &message )
{
if ( message.sceneBuilder != nullptr ) {
setSceneBuilder( message.sceneBuilder );
}
loadScene( message.filename, getSceneBuilder() );
}
void StreamingSystem::onReloadScene( messaging::ReloadScene const &message )
{
auto sceneName = _lastSceneFileName;
auto builder = getSceneBuilder();
auto self = this;
crimild::async( crimild::AsyncDispatchPolicy::MAIN_QUEUE, [self, sceneName, builder] {
Simulation::getInstance()->setScene( nullptr );
self->loadScene( sceneName, builder );
});
}
void StreamingSystem::loadScene( std::string filename, SceneBuilder *builder )
{
if ( builder == nullptr ) {
Log::Error << "Undefined scene builder" << Log::End;
return;
}
_lastSceneFileName = filename;
// Althougth the actual loading happens in background, we trigger it
// in the main thread to ensure all systems are properly runnning.
// Then, once the scene is completely loaded, we set it as the current
// scene again in main thread to avoid changing scenes when rendering or updating
crimild::async( crimild::AsyncDispatchPolicy::MAIN_QUEUE, [builder, filename] {
Log::Debug << "Loading scene: " << filename << Log::End;
crimild::async( crimild::AsyncDispatchPolicy::BACKGROUND_QUEUE, [builder, filename] {
builder->reset();
auto scene = builder->fromFile( FileSystem::getInstance().pathForResource( filename ) );
builder->reset();
Log::Debug << "Scene loaded: " << filename << Log::End;
crimild::async( crimild::AsyncDispatchPolicy::MAIN_QUEUE, [scene] {
Simulation::getInstance()->setScene( scene );
});
});
});
}
<|endoftext|>
|
<commit_before>#include <BuildManager.h>
#include <BuildingPlacer.h>
#include <ConstructionManager.h>
#include <ProductionManager.h>
#include <MorphManager.h>
BuildManager::BuildManager(Arbitrator::Arbitrator<BWAPI::Unit*,double>* arbitrator)
{
this->arbitrator=arbitrator;
this->buildingPlacer=new BuildingPlacer();
this->constructionManager=new ConstructionManager(this->arbitrator,this->buildingPlacer);
this->productionManager=new ProductionManager(this->arbitrator,this->buildingPlacer);
this->morphManager=new MorphManager(this->arbitrator);
}
BuildManager::~BuildManager()
{
delete this->buildingPlacer;
delete this->constructionManager;
delete this->productionManager;
delete this->morphManager;
}
void BuildManager::update()
{
this->constructionManager->update();
this->productionManager->update();
this->morphManager->update();
}
std::string BuildManager::getName() const
{
return "Build Manager";
}
BuildingPlacer* BuildManager::getBuildingPlacer() const
{
return this->buildingPlacer;
}
void BuildManager::onRemoveUnit(BWAPI::Unit* unit)
{
this->constructionManager->onRemoveUnit(unit);
this->productionManager->onRemoveUnit(unit);
this->morphManager->onRemoveUnit(unit);
}
bool BuildManager::build(BWAPI::UnitType type)
{
if (type==BWAPI::UnitTypes::None || type==BWAPI::UnitTypes::Unknown) return false;
if (type.getRace()==BWAPI::Races::Zerg && type.isBuilding()==type.whatBuilds().first->isBuilding())
return this->morphManager->morph(type);
else
{
if (type.isBuilding())
return this->constructionManager->build(type, BWAPI::Broodwar->self()->getStartLocation());
else
return this->productionManager->train(type);
}
return false;
}
bool BuildManager::build(BWAPI::UnitType type, BWAPI::TilePosition goalPosition)
{
if (type==BWAPI::UnitTypes::None || type==BWAPI::UnitTypes::Unknown) return false;
if (type.getRace()==BWAPI::Races::Zerg && type.isBuilding()==type.whatBuilds().first->isBuilding())
return this->morphManager->morph(type);
else
{
if (type.isBuilding())
return this->constructionManager->build(type, goalPosition);
else
return this->productionManager->train(type);
}
return false;
}
int BuildManager::getPlannedCount(BWAPI::UnitType type) const
{
if (type.getRace()==BWAPI::Races::Zerg && type.isBuilding()==type.whatBuilds().first->isBuilding())
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->morphManager->getPlannedCount(type);
else
{
if (type.isBuilding())
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->constructionManager->getPlannedCount(type);
else
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->productionManager->getPlannedCount(type);
}
}
int BuildManager::getStartedCount(BWAPI::UnitType type) const
{
if (type.getRace()==BWAPI::Races::Zerg && type.isBuilding()==type.whatBuilds().first->isBuilding())
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->morphManager->getStartedCount(type);
else
{
if (type.isBuilding())
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->constructionManager->getStartedCount(type);
else
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->productionManager->getStartedCount(type);
}
}
int BuildManager::getCompletedCount(BWAPI::UnitType type) const
{
return BWAPI::Broodwar->self()->completedUnitCount(type);
}
void BuildManager::setBuildDistance(int distance)
{
this->buildingPlacer->setBuildDistance(distance);
}<commit_msg>Eliminating duplicate code in BuildManager.<commit_after>#include <BuildManager.h>
#include <BuildingPlacer.h>
#include <ConstructionManager.h>
#include <ProductionManager.h>
#include <MorphManager.h>
BuildManager::BuildManager(Arbitrator::Arbitrator<BWAPI::Unit*,double>* arbitrator)
{
this->arbitrator=arbitrator;
this->buildingPlacer=new BuildingPlacer();
this->constructionManager=new ConstructionManager(this->arbitrator,this->buildingPlacer);
this->productionManager=new ProductionManager(this->arbitrator,this->buildingPlacer);
this->morphManager=new MorphManager(this->arbitrator);
}
BuildManager::~BuildManager()
{
delete this->buildingPlacer;
delete this->constructionManager;
delete this->productionManager;
delete this->morphManager;
}
void BuildManager::update()
{
this->constructionManager->update();
this->productionManager->update();
this->morphManager->update();
}
std::string BuildManager::getName() const
{
return "Build Manager";
}
BuildingPlacer* BuildManager::getBuildingPlacer() const
{
return this->buildingPlacer;
}
void BuildManager::onRemoveUnit(BWAPI::Unit* unit)
{
this->constructionManager->onRemoveUnit(unit);
this->productionManager->onRemoveUnit(unit);
this->morphManager->onRemoveUnit(unit);
}
bool BuildManager::build(BWAPI::UnitType type)
{
return build(type, BWAPI::Broodwar->self()->getStartLocation());
}
bool BuildManager::build(BWAPI::UnitType type, BWAPI::TilePosition goalPosition)
{
if (type==BWAPI::UnitTypes::None || type==BWAPI::UnitTypes::Unknown) return false;
if (type.getRace()==BWAPI::Races::Zerg && type.isBuilding()==type.whatBuilds().first->isBuilding())
return this->morphManager->morph(type);
else
{
if (type.isBuilding())
return this->constructionManager->build(type, goalPosition);
else
return this->productionManager->train(type);
}
return false;
}
int BuildManager::getPlannedCount(BWAPI::UnitType type) const
{
if (type.getRace()==BWAPI::Races::Zerg && type.isBuilding()==type.whatBuilds().first->isBuilding())
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->morphManager->getPlannedCount(type);
else
{
if (type.isBuilding())
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->constructionManager->getPlannedCount(type);
else
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->productionManager->getPlannedCount(type);
}
}
int BuildManager::getStartedCount(BWAPI::UnitType type) const
{
if (type.getRace()==BWAPI::Races::Zerg && type.isBuilding()==type.whatBuilds().first->isBuilding())
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->morphManager->getStartedCount(type);
else
{
if (type.isBuilding())
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->constructionManager->getStartedCount(type);
else
return BWAPI::Broodwar->self()->completedUnitCount(type)+this->productionManager->getStartedCount(type);
}
}
int BuildManager::getCompletedCount(BWAPI::UnitType type) const
{
return BWAPI::Broodwar->self()->completedUnitCount(type);
}
void BuildManager::setBuildDistance(int distance)
{
this->buildingPlacer->setBuildDistance(distance);
}<|endoftext|>
|
<commit_before>#include "pch.h"
#include "aiInternal.h"
#include "aiContext.h"
#include "aiObject.h"
#include <limits>
std::string ToString(const aiConfig &v)
{
std::ostringstream oss;
oss << "{swapHandedness: " << (v.swapHandedness ? "true" : "false");
oss << ", swapFaceWinding: " << (v.swapFaceWinding ? "true" : "false");
oss << ", normalsMode: " << (v.normalsMode == aiNormalsMode::ReadFromFile
? "read_from_file"
: (v.normalsMode == aiNormalsMode::ComputeIfMissing
? "compute_if_missing"
: (v.normalsMode == aiNormalsMode::AlwaysCompute
? "always_compute"
: "ignore")));
oss << ", tangentsMode: " << (v.tangentsMode == aiTangentsMode::None
? "none"
: (v.tangentsMode == aiTangentsMode::Smooth
? "smooth"
: "split"));
oss << ", cacheTangentsSplits: " << (v.cacheTangentsSplits ? "true" : "false");
oss << ", aspectRatio: " << v.aspectRatio;
oss << ", forceUpdate: " << (v.forceUpdate ? "true" : "false") << "}";
return oss.str();
}
aiContextManager aiContextManager::ms_instance;
aiContext* aiContextManager::getContext(int uid)
{
auto it = ms_instance.m_contexts.find(uid);
if (it != ms_instance.m_contexts.end())
{
aiLogger::Info("Using already created context for gameObject with ID %d", uid);
return it->second;
}
auto ctx = new aiContext(uid);
ms_instance.m_contexts[uid] = ctx;
aiLogger::Info("Register context for gameObject with ID %d", uid);
return ctx;
}
void aiContextManager::destroyContext(int uid)
{
auto it = ms_instance.m_contexts.find(uid);
if (it != ms_instance.m_contexts.end())
{
aiLogger::Info("Unregister context for gameObject with ID %d", uid);
ms_instance.m_contexts.erase(it);
delete it->second;
}
}
void aiContextManager::destroyContextsWithPath(const char* assetPath)
{
std::string path = aiContext::normalizePath(assetPath);
for (auto it = ms_instance.m_contexts.begin(); it != ms_instance.m_contexts.end(); ++it)
{
if (it->second->getPath() == path)
{
aiLogger::Info("Unregister context for gameObject with ID %s", it->second->getPath().c_str());
delete it->second;
ms_instance.m_contexts.erase(it);
}
}
}
aiContextManager::~aiContextManager()
{
if (m_contexts.size())
{
aiLogger::Warning("%lu remaining context(s) registered", m_contexts.size());
}
for (auto it=m_contexts.begin(); it!=m_contexts.end(); ++it)
{
delete it->second;
}
m_contexts.clear();
}
// ---
aiContext::aiContext(int uid)
: m_uid(uid)
{
}
aiContext::~aiContext()
{
m_tasks.wait();
m_top_node.reset();
m_archive.reset();
}
Abc::IArchive aiContext::getArchive() const
{
return m_archive;
}
const std::string& aiContext::getPath() const
{
return m_path;
}
int aiContext::getNumTimeSamplings()
{
return (int)m_archive.getNumTimeSamplings();
}
void aiContext::getTimeSampling(int i, aiTimeSamplingData& dst)
{
auto ts = m_archive.getTimeSampling(i);
auto tst = ts->getTimeSamplingType();
dst.numTimes = (int)ts->getNumStoredTimes();
if (tst.isUniform() || tst.isCyclic()) {
int numCycles = int(m_archive.getMaxNumSamplesForTimeSamplingIndex(i) / tst.getNumSamplesPerCycle());
dst.type = tst.isUniform() ? aiTimeSamplingType::Uniform : aiTimeSamplingType::Cyclic;
dst.interval = (float)tst.getTimePerCycle();
dst.startTime = (float)ts->getStoredTimes()[0];
dst.endTime = dst.startTime + dst.interval * (numCycles - 1);
dst.numTimes = (int)ts->getNumStoredTimes();
dst.times = const_cast<double*>(&ts->getStoredTimes()[0]);
}
else if (tst.isAcyclic()) {
dst.type = aiTimeSamplingType::Acyclic;
dst.startTime = (float)ts->getSampleTime(0);
dst.endTime = (float)ts->getSampleTime(ts->getNumStoredTimes() - 1);
dst.numTimes = (int)ts->getNumStoredTimes();
dst.times = const_cast<double*>(&ts->getStoredTimes()[0]);
}
}
void aiContext::copyTimeSampling(int i, aiTimeSamplingData& dst)
{
int dst_numSamples = dst.numTimes;
double *dst_samples = dst.times;
getTimeSampling(i, dst);
if (dst.type == aiTimeSamplingType::Acyclic) {
const auto& times = m_archive.getTimeSampling(i)->getStoredTimes();
if (dst_samples && dst_numSamples >= (int)times.size()) {
// memcpy() is way faster than std::copy() on VC...
memcpy(dst.times, ×[0], sizeof(times[0])*times.size());
}
}
}
int aiContext::getTimeSamplingIndex(Abc::TimeSamplingPtr ts)
{
int n = m_archive.getNumTimeSamplings();
for (int i = 0; i < n; ++i) {
if (m_archive.getTimeSampling(i) == ts) {
return i;
}
}
return 0;
}
int aiContext::getUid() const
{
return m_uid;
}
const aiConfig& aiContext::getConfig() const
{
return m_config;
}
void aiContext::setConfig(const aiConfig &config)
{
DebugLog("aiContext::setConfig: %s", ToString(config).c_str());
m_config = config;
}
void aiContext::gatherNodesRecursive(aiObject *n)
{
abcObject &abc = n->getAbcObject();
size_t numChildren = abc.getNumChildren();
for (size_t i = 0; i < numChildren; ++i)
{
aiObject *child = n->newChild(abc.getChild(i));
gatherNodesRecursive(child);
}
}
void aiContext::reset()
{
DebugLog("aiContext::reset()");
// just in case
m_tasks.wait();
m_top_node.reset();
m_path = "";
m_archive.reset();
m_timeRange[0] = 0.0f;
m_timeRange[1] = 0.0f;
}
std::string aiContext::normalizePath(const char *inPath)
{
std::string path;
if (inPath != nullptr)
{
path = inPath;
#ifdef _WIN32
size_t n = path.length();
for (size_t i=0; i<n; ++i)
{
char c = path[i];
if (c == '\\')
{
path[i] = '/';
}
else if (c >= 'A' && c <= 'Z')
{
path[i] = 'a' + (c - 'A');
}
}
#endif
}
return path;
}
bool aiContext::load(const char *inPath)
{
std::string path = normalizePath(inPath);
DebugLog("aiContext::load: '%s'", path.c_str());
if (path == m_path && m_archive)
{
aiLogger::Info("Context already loaded for gameObject with id %d", m_uid);
return true;
}
aiLogger::Info("Alembic file path changed from '%s' to '%s'. Reset context.", m_path.c_str(), path.c_str());
aiLogger::Indent(1);
reset();
if (path.length() == 0)
{
aiLogger::Unindent(1);
return false;
}
m_path = path;
if (!m_archive.valid())
{
aiLogger::Info("Archive '%s' not yet opened", inPath);
try
{
DebugLog("Trying to open AbcCoreOgawa::ReadArchive...");
m_archive = Abc::IArchive(AbcCoreOgawa::ReadArchive(std::thread::hardware_concurrency()), path);
}
catch (Alembic::Util::Exception e)
{
DebugLog("Failed (%s)", e.what());
try
{
DebugLog("Trying to open AbcCoreHDF5::ReadArchive...");
m_archive = Abc::IArchive(AbcCoreHDF5::ReadArchive(), path);
}
catch (Alembic::Util::Exception e2)
{
DebugLog("Failed (%s)", e2.what());
}
}
}
else
{
aiLogger::Info("Archive '%s' already opened", inPath);
}
if (m_archive.valid())
{
abcObject abcTop = m_archive.getTop();
m_top_node.reset(new aiObject(this, nullptr, abcTop));
gatherNodesRecursive(m_top_node.get());
m_timeRange[0] = std::numeric_limits<double>::max();
m_timeRange[1] = -std::numeric_limits<double>::max();
for (unsigned int i=0; i<m_archive.getNumTimeSamplings(); ++i)
{
AbcCoreAbstract::TimeSamplingPtr ts = m_archive.getTimeSampling(i);
AbcCoreAbstract::TimeSamplingType tst = ts->getTimeSamplingType();
// Note: alembic guaranties we have at least one stored time
if (tst.isCyclic() || tst.isUniform())
{
int numCycles = int(m_archive.getMaxNumSamplesForTimeSamplingIndex(i) / tst.getNumSamplesPerCycle());
m_timeRange[0] = ts->getStoredTimes()[0];
m_timeRange[1] = m_timeRange[0] + (numCycles - 1) * tst.getTimePerCycle();
if (numCycles > m_numFrames) m_numFrames = numCycles;
}
else if (tst.isAcyclic())
{
m_timeRange[0] = ts->getSampleTime(0);
m_timeRange[1] = ts->getSampleTime(ts->getNumStoredTimes() - 1);
}
}
if (m_timeRange[0] > m_timeRange[1])
{
m_timeRange[0] = 0.0;
m_timeRange[1] = 0.0;
}
DebugLog("Succeeded");
aiLogger::Unindent(1);
if (m_config.cacheSamples)
cacheAllSamples();
return true;
}
else
{
aiLogger::Error("Invalid archive '%s'", inPath);
aiLogger::Unindent(1);
reset();
return false;
}
}
float aiContext::getStartTime() const
{
return float(m_timeRange[0]);
}
float aiContext::getEndTime() const
{
return float(m_timeRange[1]);
}
int aiContext::getFrameCount() const
{
return (int)m_numFrames;
}
aiObject* aiContext::getTopObject() const
{
return m_top_node.get();
}
void aiContext::destroyObject(aiObject *obj)
{
if (obj == getTopObject()) {
m_top_node.reset();
}
else {
delete obj;
}
}
void aiContext::cacheAllSamples()
{
const int64_t numFramesPerBlock = 10;
const int64_t lastBlockSize = m_numFrames % numFramesPerBlock;
const int64_t numBlocks = m_numFrames / numFramesPerBlock + (lastBlockSize == 0 ? 0 : 1);
eachNodes([this, numBlocks, numFramesPerBlock, lastBlockSize](aiObject *o)
{
o->cacheSamples(0, 1);
});
for (int64_t i=0; i< numBlocks; i++)
{
const int64_t startIndex = (i == 0) ? 1 : i*numFramesPerBlock;
const int64_t endIndex = i*numFramesPerBlock + (i == numBlocks - 1 ? lastBlockSize : numFramesPerBlock);
m_tasks.run([this, startIndex, endIndex]()
{
eachNodes([this, startIndex, endIndex](aiObject *o)
{
o->cacheSamples(startIndex, endIndex);
});
});
}
m_tasks.wait();
}
void aiContext::updateSamples(float time)
{
DebugLog("aiContext::updateSamples()");
const abcSampleSelector ss = aiTimeToSampleSelector(time);
eachNodes([ss](aiObject *o) {
o->updateSample(ss);
});
}<commit_msg>fix: num frames was always 1 when time sampling mode is Acyclic<commit_after>#include "pch.h"
#include "aiInternal.h"
#include "aiContext.h"
#include "aiObject.h"
#include <limits>
std::string ToString(const aiConfig &v)
{
std::ostringstream oss;
oss << "{swapHandedness: " << (v.swapHandedness ? "true" : "false");
oss << ", swapFaceWinding: " << (v.swapFaceWinding ? "true" : "false");
oss << ", normalsMode: " << (v.normalsMode == aiNormalsMode::ReadFromFile
? "read_from_file"
: (v.normalsMode == aiNormalsMode::ComputeIfMissing
? "compute_if_missing"
: (v.normalsMode == aiNormalsMode::AlwaysCompute
? "always_compute"
: "ignore")));
oss << ", tangentsMode: " << (v.tangentsMode == aiTangentsMode::None
? "none"
: (v.tangentsMode == aiTangentsMode::Smooth
? "smooth"
: "split"));
oss << ", cacheTangentsSplits: " << (v.cacheTangentsSplits ? "true" : "false");
oss << ", aspectRatio: " << v.aspectRatio;
oss << ", forceUpdate: " << (v.forceUpdate ? "true" : "false") << "}";
return oss.str();
}
aiContextManager aiContextManager::ms_instance;
aiContext* aiContextManager::getContext(int uid)
{
auto it = ms_instance.m_contexts.find(uid);
if (it != ms_instance.m_contexts.end())
{
aiLogger::Info("Using already created context for gameObject with ID %d", uid);
return it->second;
}
auto ctx = new aiContext(uid);
ms_instance.m_contexts[uid] = ctx;
aiLogger::Info("Register context for gameObject with ID %d", uid);
return ctx;
}
void aiContextManager::destroyContext(int uid)
{
auto it = ms_instance.m_contexts.find(uid);
if (it != ms_instance.m_contexts.end())
{
aiLogger::Info("Unregister context for gameObject with ID %d", uid);
ms_instance.m_contexts.erase(it);
delete it->second;
}
}
void aiContextManager::destroyContextsWithPath(const char* assetPath)
{
std::string path = aiContext::normalizePath(assetPath);
for (auto it = ms_instance.m_contexts.begin(); it != ms_instance.m_contexts.end(); ++it)
{
if (it->second->getPath() == path)
{
aiLogger::Info("Unregister context for gameObject with ID %s", it->second->getPath().c_str());
delete it->second;
ms_instance.m_contexts.erase(it);
}
}
}
aiContextManager::~aiContextManager()
{
if (m_contexts.size())
{
aiLogger::Warning("%lu remaining context(s) registered", m_contexts.size());
}
for (auto it=m_contexts.begin(); it!=m_contexts.end(); ++it)
{
delete it->second;
}
m_contexts.clear();
}
// ---
aiContext::aiContext(int uid)
: m_uid(uid)
{
}
aiContext::~aiContext()
{
m_tasks.wait();
m_top_node.reset();
m_archive.reset();
}
Abc::IArchive aiContext::getArchive() const
{
return m_archive;
}
const std::string& aiContext::getPath() const
{
return m_path;
}
int aiContext::getNumTimeSamplings()
{
return (int)m_archive.getNumTimeSamplings();
}
void aiContext::getTimeSampling(int i, aiTimeSamplingData& dst)
{
auto ts = m_archive.getTimeSampling(i);
auto tst = ts->getTimeSamplingType();
dst.numTimes = (int)ts->getNumStoredTimes();
if (tst.isUniform() || tst.isCyclic()) {
int numCycles = int(m_archive.getMaxNumSamplesForTimeSamplingIndex(i) / tst.getNumSamplesPerCycle());
dst.type = tst.isUniform() ? aiTimeSamplingType::Uniform : aiTimeSamplingType::Cyclic;
dst.interval = (float)tst.getTimePerCycle();
dst.startTime = (float)ts->getStoredTimes()[0];
dst.endTime = dst.startTime + dst.interval * (numCycles - 1);
dst.numTimes = (int)ts->getNumStoredTimes();
dst.times = const_cast<double*>(&ts->getStoredTimes()[0]);
}
else if (tst.isAcyclic()) {
dst.type = aiTimeSamplingType::Acyclic;
dst.startTime = (float)ts->getSampleTime(0);
dst.endTime = (float)ts->getSampleTime(ts->getNumStoredTimes() - 1);
dst.numTimes = (int)ts->getNumStoredTimes();
dst.times = const_cast<double*>(&ts->getStoredTimes()[0]);
}
}
void aiContext::copyTimeSampling(int i, aiTimeSamplingData& dst)
{
int dst_numSamples = dst.numTimes;
double *dst_samples = dst.times;
getTimeSampling(i, dst);
if (dst.type == aiTimeSamplingType::Acyclic) {
const auto& times = m_archive.getTimeSampling(i)->getStoredTimes();
if (dst_samples && dst_numSamples >= (int)times.size()) {
// memcpy() is way faster than std::copy() on VC...
memcpy(dst.times, ×[0], sizeof(times[0])*times.size());
}
}
}
int aiContext::getTimeSamplingIndex(Abc::TimeSamplingPtr ts)
{
int n = m_archive.getNumTimeSamplings();
for (int i = 0; i < n; ++i) {
if (m_archive.getTimeSampling(i) == ts) {
return i;
}
}
return 0;
}
int aiContext::getUid() const
{
return m_uid;
}
const aiConfig& aiContext::getConfig() const
{
return m_config;
}
void aiContext::setConfig(const aiConfig &config)
{
DebugLog("aiContext::setConfig: %s", ToString(config).c_str());
m_config = config;
}
void aiContext::gatherNodesRecursive(aiObject *n)
{
abcObject &abc = n->getAbcObject();
size_t numChildren = abc.getNumChildren();
for (size_t i = 0; i < numChildren; ++i)
{
aiObject *child = n->newChild(abc.getChild(i));
gatherNodesRecursive(child);
}
}
void aiContext::reset()
{
DebugLog("aiContext::reset()");
// just in case
m_tasks.wait();
m_top_node.reset();
m_path = "";
m_archive.reset();
m_timeRange[0] = 0.0f;
m_timeRange[1] = 0.0f;
}
std::string aiContext::normalizePath(const char *inPath)
{
std::string path;
if (inPath != nullptr)
{
path = inPath;
#ifdef _WIN32
size_t n = path.length();
for (size_t i=0; i<n; ++i)
{
char c = path[i];
if (c == '\\')
{
path[i] = '/';
}
else if (c >= 'A' && c <= 'Z')
{
path[i] = 'a' + (c - 'A');
}
}
#endif
}
return path;
}
bool aiContext::load(const char *inPath)
{
std::string path = normalizePath(inPath);
DebugLog("aiContext::load: '%s'", path.c_str());
if (path == m_path && m_archive)
{
aiLogger::Info("Context already loaded for gameObject with id %d", m_uid);
return true;
}
aiLogger::Info("Alembic file path changed from '%s' to '%s'. Reset context.", m_path.c_str(), path.c_str());
aiLogger::Indent(1);
reset();
if (path.length() == 0)
{
aiLogger::Unindent(1);
return false;
}
m_path = path;
if (!m_archive.valid())
{
aiLogger::Info("Archive '%s' not yet opened", inPath);
try
{
DebugLog("Trying to open AbcCoreOgawa::ReadArchive...");
m_archive = Abc::IArchive(AbcCoreOgawa::ReadArchive(std::thread::hardware_concurrency()), path);
}
catch (Alembic::Util::Exception e)
{
DebugLog("Failed (%s)", e.what());
try
{
DebugLog("Trying to open AbcCoreHDF5::ReadArchive...");
m_archive = Abc::IArchive(AbcCoreHDF5::ReadArchive(), path);
}
catch (Alembic::Util::Exception e2)
{
DebugLog("Failed (%s)", e2.what());
}
}
}
else
{
aiLogger::Info("Archive '%s' already opened", inPath);
}
if (m_archive.valid())
{
abcObject abcTop = m_archive.getTop();
m_top_node.reset(new aiObject(this, nullptr, abcTop));
gatherNodesRecursive(m_top_node.get());
m_timeRange[0] = std::numeric_limits<double>::max();
m_timeRange[1] = -std::numeric_limits<double>::max();
for (unsigned int i=0; i<m_archive.getNumTimeSamplings(); ++i)
{
AbcCoreAbstract::TimeSamplingPtr ts = m_archive.getTimeSampling(i);
AbcCoreAbstract::TimeSamplingType tst = ts->getTimeSamplingType();
// Note: alembic guaranties we have at least one stored time
if (tst.isCyclic() || tst.isUniform())
{
int numCycles = int(m_archive.getMaxNumSamplesForTimeSamplingIndex(i) / tst.getNumSamplesPerCycle());
m_timeRange[0] = ts->getStoredTimes()[0];
m_timeRange[1] = m_timeRange[0] + (numCycles - 1) * tst.getTimePerCycle();
if (numCycles > m_numFrames) m_numFrames = numCycles;
}
else if (tst.isAcyclic())
{
m_timeRange[0] = ts->getSampleTime(0);
m_timeRange[1] = ts->getSampleTime(ts->getNumStoredTimes() - 1);
if (ts->getNumStoredTimes() > m_numFrames) m_numFrames = ts->getNumStoredTimes();
}
}
if (m_timeRange[0] > m_timeRange[1])
{
m_timeRange[0] = 0.0;
m_timeRange[1] = 0.0;
}
DebugLog("Succeeded");
aiLogger::Unindent(1);
if (m_config.cacheSamples)
cacheAllSamples();
return true;
}
else
{
aiLogger::Error("Invalid archive '%s'", inPath);
aiLogger::Unindent(1);
reset();
return false;
}
}
float aiContext::getStartTime() const
{
return float(m_timeRange[0]);
}
float aiContext::getEndTime() const
{
return float(m_timeRange[1]);
}
int aiContext::getFrameCount() const
{
return (int)m_numFrames;
}
aiObject* aiContext::getTopObject() const
{
return m_top_node.get();
}
void aiContext::destroyObject(aiObject *obj)
{
if (obj == getTopObject()) {
m_top_node.reset();
}
else {
delete obj;
}
}
void aiContext::cacheAllSamples()
{
const int64_t numFramesPerBlock = 10;
const int64_t lastBlockSize = m_numFrames % numFramesPerBlock;
const int64_t numBlocks = m_numFrames / numFramesPerBlock + (lastBlockSize == 0 ? 0 : 1);
eachNodes([this, numBlocks, numFramesPerBlock, lastBlockSize](aiObject *o)
{
o->cacheSamples(0, 1);
});
for (int64_t i=0; i< numBlocks; i++)
{
const int64_t startIndex = (i == 0) ? 1 : i*numFramesPerBlock;
const int64_t endIndex = i*numFramesPerBlock + (i == numBlocks - 1 ? lastBlockSize : numFramesPerBlock);
m_tasks.run([this, startIndex, endIndex]()
{
eachNodes([this, startIndex, endIndex](aiObject *o)
{
o->cacheSamples(startIndex, endIndex);
});
});
}
m_tasks.wait();
}
void aiContext::updateSamples(float time)
{
DebugLog("aiContext::updateSamples()");
const abcSampleSelector ss = aiTimeToSampleSelector(time);
eachNodes([ss](aiObject *o) {
o->updateSample(ss);
});
}<|endoftext|>
|
<commit_before>#include "Commands.h"
#include "Settings.h"
CommandLine commandLine(Serial, "> ");
bool setupMode;
/**
* Universal method for reading 1, 2 or 4 bytes.
*/
void parseCommand(void* property, size_t length, uint32_t min, uint32_t max)
{
char* parameter = strtok(NULL, " ");
if (parameter == NULL) {
if (length == 1) {
Serial.println(*(uint8_t *) property);
} else if (length == 2) {
Serial.println(*(uint16_t *) property);
} else if (length == 4) {
Serial.println(*(uint32_t *) property);
}
} else {
int value = atoi(parameter);
if (value < min || value > max) {
Serial.print(F("Value not in range: "));
Serial.print(min);
Serial.print(F(" - "));
Serial.print(max);
Serial.println(F(""));
} else {
if (length == 1) {
*(uint8_t*) property = (uint8_t) value;
} else if (length == 2) {
*(uint16_t*) property = (uint16_t) value;
} else if (length == 4) {
*(uint32_t*) property = (uint32_t) value;
}
}
}
}
void handleSampleReset(char* tokens)
{
parseCommand(&configuration.sampleReset, 1, 0, 1);
}
void handleSampleBucket(char* tokens)
{
parseCommand(&configuration.sampleBucket, 2, 1, 256);
}
void handleSampleMultiple(char* tokens)
{
parseCommand(&configuration.sampleMultiple, 2, 1, 65536U);
}
void handleDelayHold(char* tokens)
{
parseCommand(&configuration.delayHold, 4, 0, 4294967295U);
}
void handleDelaySkip(char* tokens)
{
parseCommand(&configuration.delaySkip, 4, 0, 4294967295U);
}
void handleDelayRound(char* tokens)
{
parseCommand(&configuration.delayRound, 4, 0, 4294967295U);
}
void handleSampleMask(char* tokens)
{
parseCommand(&configuration.sampleMask, 2, 0, 0xFF);
}
void handleSampleShift(char* tokens)
{
parseCommand(&configuration.sampleShift, 1, 0, 10);
}
void handleSampleTake(char* tokens)
{
parseCommand(&configuration.sampleTake, 1, 0, 10);
}
void handleMode(char* tokens)
{
parseCommand(&configuration.mode, 1, 1, 2);
}
void handleExtractor(char* tokens)
{
parseCommand(&configuration.extractor, 1, 1, 3);
}
void handleGenerator(char* tokens)
{
parseCommand(&configuration.generator, 1, 1, 2);
}
void handleOutput(char* tokens)
{
parseCommand(&configuration.output, 1, 1, 2);
}
void handleOutputMode(char* tokens)
{
parseCommand(&configuration.outputMode, 1, 1, 2);
}
void handleOutputBucket(char* tokens)
{
parseCommand(&configuration.outputBucket, 2, 1, 256);
}
void handleSave(char* tokens)
{
saveSettings();
Serial.println(F("Settings saved."));
}
void handleLoad(char* tokens)
{
loadSettings();
Serial.println(F("Settings loaded."));
}
void handleDefaults(char* tokens)
{
defaultSettings();
Serial.println(F("Default settings (not saved)."));
}
void handleHelp(char* tokens)
{
Serial.println(F("Available commands: sampleReset, sampleBucket, sampleMultiple, delayHold, delaySkip, delayRound, sampleMask, sampleShift, sampleTake, mode, extractor, generator, output, outputMode, outputBucket, save, load, defaults, help, run"));
}
void handleRun(char* tokens)
{
setupMode = false;
}
void addCommands()
{
commandLine.add("sampleReset", &handleSampleReset);
commandLine.add("sampleBucket", &handleSampleBucket);
commandLine.add("sampleMultiple", &handleSampleMultiple);
commandLine.add("delayHold", &handleDelayHold);
commandLine.add("delaySkip", &handleDelaySkip);
commandLine.add("delayRound", &handleDelayRound);
commandLine.add("sampleMask", &handleSampleMask);
commandLine.add("sampleShift", &handleSampleShift);
commandLine.add("sampleTake", &handleSampleTake);
commandLine.add("mode", &handleMode);
commandLine.add("extractor", &handleExtractor);
commandLine.add("generator", &handleGenerator);
commandLine.add("output", &handleOutput);
commandLine.add("outputMode", &handleOutputMode);
commandLine.add("outputBucket", &handleOutputBucket);
commandLine.add("save", &handleSave);
commandLine.add("load", &handleLoad);
commandLine.add("defaults", &handleDefaults);
commandLine.add("help", &handleHelp);
commandLine.add("run", &handleRun);
}
<commit_msg>Bugfix in limits.<commit_after>#include "Commands.h"
#include "Settings.h"
CommandLine commandLine(Serial, "> ");
bool setupMode;
/**
* Universal method for reading 1, 2 or 4 bytes.
*/
void parseCommand(void* property, size_t length, uint32_t min, uint32_t max)
{
char* parameter = strtok(NULL, " ");
if (parameter == NULL) {
if (length == 1) {
Serial.println(*(uint8_t *) property);
} else if (length == 2) {
Serial.println(*(uint16_t *) property);
} else if (length == 4) {
Serial.println(*(uint32_t *) property);
}
} else {
uint32_t value = atol(parameter);
if (value < min || value > max) {
Serial.print(F("Value not in range: "));
Serial.print(min);
Serial.print(F(" - "));
Serial.print(max);
Serial.println(F(""));
} else {
if (length == 1) {
*(uint8_t*) property = (uint8_t) value;
} else if (length == 2) {
*(uint16_t*) property = (uint16_t) value;
} else if (length == 4) {
*(uint32_t*) property = (uint32_t) value;
}
}
}
}
void handleSampleReset(char* tokens)
{
parseCommand(&configuration.sampleReset, 1, 0, 1);
}
void handleSampleBucket(char* tokens)
{
parseCommand(&configuration.sampleBucket, 2, 1, 256);
}
void handleSampleMultiple(char* tokens)
{
parseCommand(&configuration.sampleMultiple, 2, 1, 65535U);
}
void handleDelayHold(char* tokens)
{
parseCommand(&configuration.delayHold, 4, 0, 4294967295U);
}
void handleDelaySkip(char* tokens)
{
parseCommand(&configuration.delaySkip, 4, 0, 4294967295U);
}
void handleDelayRound(char* tokens)
{
parseCommand(&configuration.delayRound, 4, 0, 4294967295U);
}
void handleSampleMask(char* tokens)
{
parseCommand(&configuration.sampleMask, 2, 0, 0xFFFF);
}
void handleSampleShift(char* tokens)
{
parseCommand(&configuration.sampleShift, 1, 0, 10);
}
void handleSampleTake(char* tokens)
{
parseCommand(&configuration.sampleTake, 1, 0, 10);
}
void handleMode(char* tokens)
{
parseCommand(&configuration.mode, 1, 1, 2);
}
void handleExtractor(char* tokens)
{
parseCommand(&configuration.extractor, 1, 1, 3);
}
void handleGenerator(char* tokens)
{
parseCommand(&configuration.generator, 1, 1, 2);
}
void handleOutput(char* tokens)
{
parseCommand(&configuration.output, 1, 1, 2);
}
void handleOutputMode(char* tokens)
{
parseCommand(&configuration.outputMode, 1, 1, 2);
}
void handleOutputBucket(char* tokens)
{
parseCommand(&configuration.outputBucket, 2, 1, 256);
}
void handleSave(char* tokens)
{
saveSettings();
Serial.println(F("Settings saved."));
}
void handleLoad(char* tokens)
{
loadSettings();
Serial.println(F("Settings loaded."));
}
void handleDefaults(char* tokens)
{
defaultSettings();
Serial.println(F("Default settings (not saved)."));
}
void handleHelp(char* tokens)
{
Serial.println(F("Available commands: sampleReset, sampleBucket, sampleMultiple, delayHold, delaySkip, delayRound, sampleMask, sampleShift, sampleTake, mode, extractor, generator, output, outputMode, outputBucket, save, load, defaults, help, run"));
}
void handleRun(char* tokens)
{
setupMode = false;
}
void addCommands()
{
commandLine.add("sampleReset", &handleSampleReset);
commandLine.add("sampleBucket", &handleSampleBucket);
commandLine.add("sampleMultiple", &handleSampleMultiple);
commandLine.add("delayHold", &handleDelayHold);
commandLine.add("delaySkip", &handleDelaySkip);
commandLine.add("delayRound", &handleDelayRound);
commandLine.add("sampleMask", &handleSampleMask);
commandLine.add("sampleShift", &handleSampleShift);
commandLine.add("sampleTake", &handleSampleTake);
commandLine.add("mode", &handleMode);
commandLine.add("extractor", &handleExtractor);
commandLine.add("generator", &handleGenerator);
commandLine.add("output", &handleOutput);
commandLine.add("outputMode", &handleOutputMode);
commandLine.add("outputBucket", &handleOutputBucket);
commandLine.add("save", &handleSave);
commandLine.add("load", &handleLoad);
commandLine.add("defaults", &handleDefaults);
commandLine.add("help", &handleHelp);
commandLine.add("run", &handleRun);
}
<|endoftext|>
|
<commit_before>// Copyright 2013 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 "content/browser/dom_storage/dom_storage_host.h"
#include "content/browser/dom_storage/dom_storage_area.h"
#include "content/browser/dom_storage/dom_storage_context_impl.h"
#include "content/browser/dom_storage/dom_storage_namespace.h"
#include "content/common/dom_storage/dom_storage_types.h"
#include "url/gurl.h"
namespace content {
DOMStorageHost::DOMStorageHost(DOMStorageContextImpl* context,
int render_process_id)
: context_(context),
render_process_id_(render_process_id) {
}
DOMStorageHost::~DOMStorageHost() {
AreaMap::const_iterator it = connections_.begin();
for (; it != connections_.end(); ++it)
it->second.namespace_->CloseStorageArea(it->second.area_.get());
connections_.clear(); // Clear prior to releasing the context_
}
bool DOMStorageHost::OpenStorageArea(int connection_id, int namespace_id,
const GURL& origin) {
DCHECK(!GetOpenArea(connection_id));
if (GetOpenArea(connection_id))
return false; // Indicates the renderer gave us very bad data.
NamespaceAndArea references;
references.namespace_ = context_->GetStorageNamespace(namespace_id);
if (!references.namespace_.get())
return false;
references.area_ = references.namespace_->OpenStorageArea(origin);
DCHECK(references.area_.get());
connections_[connection_id] = references;
return true;
}
void DOMStorageHost::CloseStorageArea(int connection_id) {
AreaMap::iterator found = connections_.find(connection_id);
if (found == connections_.end())
return;
found->second.namespace_->CloseStorageArea(found->second.area_.get());
connections_.erase(found);
}
bool DOMStorageHost::ExtractAreaValues(
int connection_id, DOMStorageValuesMap* map, bool* send_log_get_messages) {
map->clear();
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return false;
if (!area->IsLoadedInMemory()) {
DOMStorageNamespace* ns = GetNamespace(connection_id);
DCHECK(ns);
if (ns->CountInMemoryAreas() > kMaxInMemoryStorageAreas) {
ns->PurgeMemory(DOMStorageNamespace::PURGE_UNOPENED);
if (ns->CountInMemoryAreas() > kMaxInMemoryStorageAreas)
ns->PurgeMemory(DOMStorageNamespace::PURGE_AGGRESSIVE);
}
}
area->ExtractValues(map);
*send_log_get_messages = false;
DOMStorageNamespace* ns = GetNamespace(connection_id);
DCHECK(ns);
*send_log_get_messages = ns->IsLoggingRenderer(render_process_id_);
return true;
}
unsigned DOMStorageHost::GetAreaLength(int connection_id) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return 0;
return area->Length();
}
base::NullableString16 DOMStorageHost::GetAreaKey(int connection_id,
unsigned index) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return base::NullableString16();
return area->Key(index);
}
base::NullableString16 DOMStorageHost::GetAreaItem(int connection_id,
const base::string16& key) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return base::NullableString16();
return area->GetItem(key);
}
bool DOMStorageHost::SetAreaItem(
int connection_id, const base::string16& key,
const base::string16& value, const GURL& page_url,
base::NullableString16* old_value) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return false;
if (!area->SetItem(key, value, old_value))
return false;
if (old_value->is_null() || old_value->string() != value)
context_->NotifyItemSet(area, key, value, *old_value, page_url);
MaybeLogTransaction(connection_id,
DOMStorageNamespace::TRANSACTION_WRITE,
area->origin(), page_url, key,
base::NullableString16(value, false));
return true;
}
void DOMStorageHost::LogGetAreaItem(
int connection_id, const base::string16& key,
const base::NullableString16& value) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return;
MaybeLogTransaction(connection_id,
DOMStorageNamespace::TRANSACTION_READ,
area->origin(), GURL(), key, value);
}
bool DOMStorageHost::RemoveAreaItem(
int connection_id, const base::string16& key, const GURL& page_url,
base::string16* old_value) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return false;
if (!area->RemoveItem(key, old_value))
return false;
context_->NotifyItemRemoved(area, key, *old_value, page_url);
MaybeLogTransaction(connection_id,
DOMStorageNamespace::TRANSACTION_REMOVE,
area->origin(), page_url, key, base::NullableString16());
return true;
}
bool DOMStorageHost::ClearArea(int connection_id, const GURL& page_url) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return false;
if (!area->Clear())
return false;
context_->NotifyAreaCleared(area, page_url);
MaybeLogTransaction(connection_id,
DOMStorageNamespace::TRANSACTION_CLEAR,
area->origin(), page_url, base::string16(),
base::NullableString16());
return true;
}
bool DOMStorageHost::HasAreaOpen(
int64 namespace_id, const GURL& origin, int64* alias_namespace_id) const {
AreaMap::const_iterator it = connections_.begin();
for (; it != connections_.end(); ++it) {
if (namespace_id == it->second.area_->namespace_id() &&
origin == it->second.area_->origin()) {
*alias_namespace_id = it->second.namespace_->namespace_id();
return true;
}
}
return false;
}
bool DOMStorageHost::ResetOpenAreasForNamespace(int64 namespace_id) {
bool result = false;
AreaMap::iterator it = connections_.begin();
for (; it != connections_.end(); ++it) {
if (namespace_id == it->second.namespace_->namespace_id()) {
GURL origin = it->second.area_->origin();
it->second.namespace_->CloseStorageArea(it->second.area_.get());
it->second.area_ = it->second.namespace_->OpenStorageArea(origin);
result = true;
}
}
return result;
}
DOMStorageArea* DOMStorageHost::GetOpenArea(int connection_id) {
AreaMap::iterator found = connections_.find(connection_id);
if (found == connections_.end())
return NULL;
return found->second.area_.get();
}
DOMStorageNamespace* DOMStorageHost::GetNamespace(int connection_id) {
AreaMap::iterator found = connections_.find(connection_id);
if (found == connections_.end())
return NULL;
return found->second.namespace_.get();
}
void DOMStorageHost::MaybeLogTransaction(
int connection_id,
DOMStorageNamespace::LogType transaction_type,
const GURL& origin,
const GURL& page_url,
const base::string16& key,
const base::NullableString16& value) {
DOMStorageNamespace* ns = GetNamespace(connection_id);
DCHECK(ns);
if (!ns->IsLoggingRenderer(render_process_id_))
return;
DOMStorageNamespace::TransactionRecord transaction;
transaction.transaction_type = transaction_type;
transaction.origin = origin;
transaction.page_url = page_url;
transaction.key = key;
transaction.value = value;
ns->AddTransaction(render_process_id_, transaction);
}
// NamespaceAndArea
DOMStorageHost::NamespaceAndArea::NamespaceAndArea() {}
DOMStorageHost::NamespaceAndArea::~NamespaceAndArea() {}
} // namespace content
<commit_msg>Revert 217570 "Undo band-aid which was ignoring wrong SessionSto..."<commit_after>// Copyright 2013 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 "content/browser/dom_storage/dom_storage_host.h"
#include "content/browser/dom_storage/dom_storage_area.h"
#include "content/browser/dom_storage/dom_storage_context_impl.h"
#include "content/browser/dom_storage/dom_storage_namespace.h"
#include "content/common/dom_storage/dom_storage_types.h"
#include "url/gurl.h"
namespace content {
DOMStorageHost::DOMStorageHost(DOMStorageContextImpl* context,
int render_process_id)
: context_(context),
render_process_id_(render_process_id) {
}
DOMStorageHost::~DOMStorageHost() {
AreaMap::const_iterator it = connections_.begin();
for (; it != connections_.end(); ++it)
it->second.namespace_->CloseStorageArea(it->second.area_.get());
connections_.clear(); // Clear prior to releasing the context_
}
bool DOMStorageHost::OpenStorageArea(int connection_id, int namespace_id,
const GURL& origin) {
DCHECK(!GetOpenArea(connection_id));
if (GetOpenArea(connection_id))
return false; // Indicates the renderer gave us very bad data.
NamespaceAndArea references;
references.namespace_ = context_->GetStorageNamespace(namespace_id);
if (!references.namespace_.get()) {
// TODO(michaeln): Fix crbug/134003 and return false here.
// Until then return true to avoid crashing the renderer for
// sending a bad message.
return true;
}
references.area_ = references.namespace_->OpenStorageArea(origin);
DCHECK(references.area_.get());
connections_[connection_id] = references;
return true;
}
void DOMStorageHost::CloseStorageArea(int connection_id) {
AreaMap::iterator found = connections_.find(connection_id);
if (found == connections_.end())
return;
found->second.namespace_->CloseStorageArea(found->second.area_.get());
connections_.erase(found);
}
bool DOMStorageHost::ExtractAreaValues(
int connection_id, DOMStorageValuesMap* map, bool* send_log_get_messages) {
map->clear();
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area) {
// TODO(michaeln): Fix crbug/134003 and return false here.
// Until then return true to avoid crashing the renderer
// for sending a bad message.
return true;
}
if (!area->IsLoadedInMemory()) {
DOMStorageNamespace* ns = GetNamespace(connection_id);
DCHECK(ns);
if (ns->CountInMemoryAreas() > kMaxInMemoryStorageAreas) {
ns->PurgeMemory(DOMStorageNamespace::PURGE_UNOPENED);
if (ns->CountInMemoryAreas() > kMaxInMemoryStorageAreas)
ns->PurgeMemory(DOMStorageNamespace::PURGE_AGGRESSIVE);
}
}
area->ExtractValues(map);
*send_log_get_messages = false;
DOMStorageNamespace* ns = GetNamespace(connection_id);
DCHECK(ns);
*send_log_get_messages = ns->IsLoggingRenderer(render_process_id_);
return true;
}
unsigned DOMStorageHost::GetAreaLength(int connection_id) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return 0;
return area->Length();
}
base::NullableString16 DOMStorageHost::GetAreaKey(int connection_id,
unsigned index) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return base::NullableString16();
return area->Key(index);
}
base::NullableString16 DOMStorageHost::GetAreaItem(int connection_id,
const base::string16& key) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return base::NullableString16();
return area->GetItem(key);
}
bool DOMStorageHost::SetAreaItem(
int connection_id, const base::string16& key,
const base::string16& value, const GURL& page_url,
base::NullableString16* old_value) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area) {
// TODO(michaeln): Fix crbug/134003 and return false here.
// Until then return true to allow the renderer to operate
// to a limited degree out of its cache.
return true;
}
if (!area->SetItem(key, value, old_value))
return false;
if (old_value->is_null() || old_value->string() != value)
context_->NotifyItemSet(area, key, value, *old_value, page_url);
MaybeLogTransaction(connection_id,
DOMStorageNamespace::TRANSACTION_WRITE,
area->origin(), page_url, key,
base::NullableString16(value, false));
return true;
}
void DOMStorageHost::LogGetAreaItem(
int connection_id, const base::string16& key,
const base::NullableString16& value) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return;
MaybeLogTransaction(connection_id,
DOMStorageNamespace::TRANSACTION_READ,
area->origin(), GURL(), key, value);
}
bool DOMStorageHost::RemoveAreaItem(
int connection_id, const base::string16& key, const GURL& page_url,
base::string16* old_value) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return false;
if (!area->RemoveItem(key, old_value))
return false;
context_->NotifyItemRemoved(area, key, *old_value, page_url);
MaybeLogTransaction(connection_id,
DOMStorageNamespace::TRANSACTION_REMOVE,
area->origin(), page_url, key, base::NullableString16());
return true;
}
bool DOMStorageHost::ClearArea(int connection_id, const GURL& page_url) {
DOMStorageArea* area = GetOpenArea(connection_id);
if (!area)
return false;
if (!area->Clear())
return false;
context_->NotifyAreaCleared(area, page_url);
MaybeLogTransaction(connection_id,
DOMStorageNamespace::TRANSACTION_CLEAR,
area->origin(), page_url, base::string16(),
base::NullableString16());
return true;
}
bool DOMStorageHost::HasAreaOpen(
int64 namespace_id, const GURL& origin, int64* alias_namespace_id) const {
AreaMap::const_iterator it = connections_.begin();
for (; it != connections_.end(); ++it) {
if (namespace_id == it->second.area_->namespace_id() &&
origin == it->second.area_->origin()) {
*alias_namespace_id = it->second.namespace_->namespace_id();
return true;
}
}
return false;
}
bool DOMStorageHost::ResetOpenAreasForNamespace(int64 namespace_id) {
bool result = false;
AreaMap::iterator it = connections_.begin();
for (; it != connections_.end(); ++it) {
if (namespace_id == it->second.namespace_->namespace_id()) {
GURL origin = it->second.area_->origin();
it->second.namespace_->CloseStorageArea(it->second.area_.get());
it->second.area_ = it->second.namespace_->OpenStorageArea(origin);
result = true;
}
}
return result;
}
DOMStorageArea* DOMStorageHost::GetOpenArea(int connection_id) {
AreaMap::iterator found = connections_.find(connection_id);
if (found == connections_.end())
return NULL;
return found->second.area_.get();
}
DOMStorageNamespace* DOMStorageHost::GetNamespace(int connection_id) {
AreaMap::iterator found = connections_.find(connection_id);
if (found == connections_.end())
return NULL;
return found->second.namespace_.get();
}
void DOMStorageHost::MaybeLogTransaction(
int connection_id,
DOMStorageNamespace::LogType transaction_type,
const GURL& origin,
const GURL& page_url,
const base::string16& key,
const base::NullableString16& value) {
DOMStorageNamespace* ns = GetNamespace(connection_id);
DCHECK(ns);
if (!ns->IsLoggingRenderer(render_process_id_))
return;
DOMStorageNamespace::TransactionRecord transaction;
transaction.transaction_type = transaction_type;
transaction.origin = origin;
transaction.page_url = page_url;
transaction.key = key;
transaction.value = value;
ns->AddTransaction(render_process_id_, transaction);
}
// NamespaceAndArea
DOMStorageHost::NamespaceAndArea::NamespaceAndArea() {}
DOMStorageHost::NamespaceAndArea::~NamespaceAndArea() {}
} // namespace content
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/gpu/client/content_gl_context.h"
#include "base/bind.h"
#include "base/debug/trace_event.h"
#include "base/lazy_instance.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/memory/weak_ptr.h"
#include "base/shared_memory.h"
#include "content/common/gpu/client/command_buffer_proxy.h"
#include "content/common/gpu/client/gpu_channel_host.h"
#include "googleurl/src/gurl.h"
#include "ipc/ipc_channel_handle.h"
#if defined(ENABLE_GPU)
#include "gpu/command_buffer/client/gles2_cmd_helper.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_lib.h"
#include "gpu/command_buffer/client/transfer_buffer.h"
#include "gpu/command_buffer/common/constants.h"
#endif // ENABLE_GPU
namespace {
const int32 kCommandBufferSize = 1024 * 1024;
// TODO(kbr): make the transfer buffer size configurable via context
// creation attributes.
const size_t kStartTransferBufferSize = 1 * 1024 * 1024;
const size_t kMinTransferBufferSize = 1 * 256 * 1024;
const size_t kMaxTransferBufferSize = 16 * 1024 * 1024;
// Singleton used to initialize and terminate the gles2 library.
class GLES2Initializer {
public:
GLES2Initializer() {
gles2::Initialize();
}
~GLES2Initializer() {
gles2::Terminate();
}
private:
DISALLOW_COPY_AND_ASSIGN(GLES2Initializer);
};
////////////////////////////////////////////////////////////////////////////////
base::LazyInstance<GLES2Initializer> g_gles2_initializer =
LAZY_INSTANCE_INITIALIZER;
////////////////////////////////////////////////////////////////////////////////
#if defined(ENABLE_GPU)
ContentGLContext::ContextLostReason ConvertReason(
gpu::error::ContextLostReason reason) {
switch (reason) {
case gpu::error::kGuilty:
return ContentGLContext::kGuilty;
case gpu::error::kInnocent:
return ContentGLContext::kInnocent;
case gpu::error::kUnknown:
return ContentGLContext::kUnknown;
}
NOTREACHED();
return ContentGLContext::kUnknown;
}
#endif
} // namespace
ContentGLContext::~ContentGLContext() {
Destroy();
}
ContentGLContext* ContentGLContext::CreateViewContext(
GpuChannelHost* channel,
int32 surface_id,
ContentGLContext* share_group,
const char* allowed_extensions,
const int32* attrib_list,
const GURL& active_url,
gfx::GpuPreference gpu_preference) {
#if defined(ENABLE_GPU)
scoped_ptr<ContentGLContext> context(new ContentGLContext(channel));
if (!context->Initialize(
true,
surface_id,
gfx::Size(),
share_group,
allowed_extensions,
attrib_list,
active_url,
gpu_preference))
return NULL;
return context.release();
#else
return NULL;
#endif
}
ContentGLContext* ContentGLContext::CreateOffscreenContext(
GpuChannelHost* channel,
const gfx::Size& size,
ContentGLContext* share_group,
const char* allowed_extensions,
const int32* attrib_list,
const GURL& active_url,
gfx::GpuPreference gpu_preference) {
#if defined(ENABLE_GPU)
scoped_ptr<ContentGLContext> context(new ContentGLContext(channel));
if (!context->Initialize(
false,
0,
size,
share_group,
allowed_extensions,
attrib_list,
active_url,
gpu_preference))
return NULL;
return context.release();
#else
return NULL;
#endif
}
bool ContentGLContext::SetParent(ContentGLContext* new_parent) {
if (parent_.get() == new_parent)
return true;
// Allocate a texture ID with respect to the parent and change the parent.
uint32 new_parent_texture_id = 0;
if (command_buffer_) {
if (new_parent) {
TRACE_EVENT0("gpu", "ContentGLContext::SetParent::flushParent");
// Flush any remaining commands in the parent context to make sure the
// texture id accounting stays consistent.
int32 token = new_parent->gles2_helper_->InsertToken();
new_parent->gles2_helper_->WaitForToken(token);
new_parent_texture_id =
new_parent->gles2_implementation_->MakeTextureId();
if (!command_buffer_->SetParent(new_parent->command_buffer_,
new_parent_texture_id)) {
new_parent->gles2_implementation_->FreeTextureId(parent_texture_id_);
return false;
}
} else {
if (!command_buffer_->SetParent(NULL, 0))
return false;
}
}
// Free the previous parent's texture ID.
if (parent_.get() && parent_texture_id_ != 0) {
// Flush any remaining commands in the parent context to make sure the
// texture id accounting stays consistent.
gpu::gles2::GLES2Implementation* parent_gles2 =
parent_->GetImplementation();
parent_gles2->helper()->CommandBufferHelper::Finish();
parent_gles2->FreeTextureId(parent_texture_id_);
}
if (new_parent) {
parent_ = new_parent->AsWeakPtr();
parent_texture_id_ = new_parent_texture_id;
} else {
parent_.reset();
parent_texture_id_ = 0;
}
return true;
}
uint32 ContentGLContext::GetParentTextureId() {
return parent_texture_id_;
}
uint32 ContentGLContext::CreateParentTexture(const gfx::Size& size) {
uint32 texture_id = 0;
gles2_implementation_->GenTextures(1, &texture_id);
gles2_implementation_->Flush();
return texture_id;
}
void ContentGLContext::DeleteParentTexture(uint32 texture) {
gles2_implementation_->DeleteTextures(1, &texture);
}
void ContentGLContext::SetContextLostCallback(
const base::Callback<void (ContextLostReason)>& callback) {
context_lost_callback_ = callback;
}
bool ContentGLContext::MakeCurrent(ContentGLContext* context) {
if (context) {
DCHECK(context->CalledOnValidThread());
gles2::SetGLContext(context->gles2_implementation_);
// Don't request latest error status from service. Just use the locally
// cached information from the last flush.
// TODO(apatrick): I'm not sure if this should actually change the
// current context if it fails. For now it gets changed even if it fails
// because making GL calls with a NULL context crashes.
if (context->command_buffer_->GetLastState().error != gpu::error::kNoError)
return false;
} else {
gles2::SetGLContext(NULL);
}
return true;
}
bool ContentGLContext::SwapBuffers() {
TRACE_EVENT1("gpu", "ContentGLContext::SwapBuffers", "frame", frame_number_);
frame_number_++;
// Don't request latest error status from service. Just use the locally cached
// information from the last flush.
if (command_buffer_->GetLastState().error != gpu::error::kNoError)
return false;
gles2_implementation_->SwapBuffers();
return true;
}
bool ContentGLContext::Echo(const base::Closure& task) {
return command_buffer_->Echo(task);
}
ContentGLContext::Error ContentGLContext::GetError() {
gpu::CommandBuffer::State state = command_buffer_->GetState();
if (state.error == gpu::error::kNoError) {
Error old_error = last_error_;
last_error_ = SUCCESS;
return old_error;
} else {
// All command buffer errors are unrecoverable. The error is treated as a
// lost context: destroy the context and create another one.
return CONTEXT_LOST;
}
}
bool ContentGLContext::IsCommandBufferContextLost() {
// If the channel shut down unexpectedly, let that supersede the
// command buffer's state.
if (channel_->state() == GpuChannelHost::kLost)
return true;
gpu::CommandBuffer::State state = command_buffer_->GetLastState();
return state.error == gpu::error::kLostContext;
}
CommandBufferProxy* ContentGLContext::GetCommandBufferProxy() {
return command_buffer_;
}
bool ContentGLContext::SetSurfaceVisible(bool visible) {
return GetCommandBufferProxy()->SetSurfaceVisible(visible);
}
// TODO(gman): Remove This
void ContentGLContext::DisableShaderTranslation() {
NOTREACHED();
}
gpu::gles2::GLES2Implementation* ContentGLContext::GetImplementation() {
return gles2_implementation_;
}
ContentGLContext::ContentGLContext(GpuChannelHost* channel)
: channel_(channel),
parent_(base::WeakPtr<ContentGLContext>()),
parent_texture_id_(0),
command_buffer_(NULL),
gles2_helper_(NULL),
transfer_buffer_(NULL),
gles2_implementation_(NULL),
last_error_(SUCCESS),
frame_number_(0) {
DCHECK(channel);
}
bool ContentGLContext::Initialize(bool onscreen,
int32 surface_id,
const gfx::Size& size,
ContentGLContext* share_group,
const char* allowed_extensions,
const int32* attrib_list,
const GURL& active_url,
gfx::GpuPreference gpu_preference) {
DCHECK(CalledOnValidThread());
DCHECK(size.width() >= 0 && size.height() >= 0);
TRACE_EVENT2("gpu", "ContentGLContext::Initialize",
"on_screen", onscreen, "num_pixels", size.GetArea());
if (channel_->state() != GpuChannelHost::kConnected)
return false;
// Ensure the gles2 library is initialized first in a thread safe way.
g_gles2_initializer.Get();
bool share_resources = true;
bool bind_generates_resources = true;
std::vector<int32> attribs;
while (attrib_list) {
int32 attrib = *attrib_list++;
switch (attrib) {
// Known attributes
case ALPHA_SIZE:
case BLUE_SIZE:
case GREEN_SIZE:
case RED_SIZE:
case DEPTH_SIZE:
case STENCIL_SIZE:
case SAMPLES:
case SAMPLE_BUFFERS:
attribs.push_back(attrib);
attribs.push_back(*attrib_list++);
break;
case SHARE_RESOURCES:
share_resources = !!(*attrib_list++);
break;
case BIND_GENERATES_RESOURCES:
bind_generates_resources = !!(*attrib_list++);
break;
case NONE:
attribs.push_back(attrib);
attrib_list = NULL;
break;
default:
last_error_ = BAD_ATTRIBUTE;
attribs.push_back(NONE);
attrib_list = NULL;
break;
}
}
// Create a proxy to a command buffer in the GPU process.
if (onscreen) {
TRACE_EVENT0("gpu",
"ContentGLContext::Initialize::CreateViewCommandBuffer");
command_buffer_ = channel_->CreateViewCommandBuffer(
surface_id,
share_group ? share_group->command_buffer_ : NULL,
allowed_extensions,
attribs,
active_url,
gpu_preference);
} else {
command_buffer_ = channel_->CreateOffscreenCommandBuffer(
size,
share_group ? share_group->command_buffer_ : NULL,
allowed_extensions,
attribs,
active_url,
gpu_preference);
}
if (!command_buffer_) {
Destroy();
return false;
}
{
TRACE_EVENT0("gpu",
"ContentGLContext::Initialize::InitializeCommandBuffer");
// Initiaize the command buffer.
if (!command_buffer_->Initialize()) {
Destroy();
return false;
}
}
command_buffer_->SetChannelErrorCallback(
base::Bind(&ContentGLContext::OnContextLost, base::Unretained(this)));
// Create the GLES2 helper, which writes the command buffer protocol.
gles2_helper_ = new gpu::gles2::GLES2CmdHelper(command_buffer_);
if (!gles2_helper_->Initialize(kCommandBufferSize)) {
Destroy();
return false;
}
{
TRACE_EVENT0("gpu", "ContentGLContext::Initialize::CreateTransferBuffer");
// Create a transfer buffer used to copy resources between the renderer
// process and the GPU process.
transfer_buffer_ = new gpu::TransferBuffer(gles2_helper_);
}
// Create the object exposing the OpenGL API.
gles2_implementation_ = new gpu::gles2::GLES2Implementation(
gles2_helper_,
transfer_buffer_,
share_resources,
bind_generates_resources);
if (!gles2_implementation_->Initialize(
kStartTransferBufferSize,
kMinTransferBufferSize,
kMaxTransferBufferSize)) {
Destroy();
return false;
}
return true;
}
void ContentGLContext::Destroy() {
TRACE_EVENT0("gpu", "ContentGLContext::Destroy");
DCHECK(CalledOnValidThread());
SetParent(NULL);
if (gles2_implementation_) {
// First flush the context to ensure that any pending frees of resources
// are completed. Otherwise, if this context is part of a share group,
// those resources might leak. Also, any remaining side effects of commands
// issued on this context might not be visible to other contexts in the
// share group.
gles2_implementation_->Flush();
delete gles2_implementation_;
gles2_implementation_ = NULL;
}
if (transfer_buffer_) {
delete transfer_buffer_;
transfer_buffer_ = NULL;
}
delete gles2_helper_;
gles2_helper_ = NULL;
if (channel_ && command_buffer_) {
channel_->DestroyCommandBuffer(command_buffer_);
command_buffer_ = NULL;
}
channel_ = NULL;
}
void ContentGLContext::OnContextLost() {
if (!context_lost_callback_.is_null()) {
ContentGLContext::ContextLostReason reason = kUnknown;
if (command_buffer_) {
reason = ConvertReason(
command_buffer_->GetLastState().context_lost_reason);
}
context_lost_callback_.Run(reason);
}
}
<commit_msg>RendererGLContext calls CommandBuffer::GetLastError instead of GetLastState.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/gpu/client/content_gl_context.h"
#include "base/bind.h"
#include "base/debug/trace_event.h"
#include "base/lazy_instance.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/memory/weak_ptr.h"
#include "base/shared_memory.h"
#include "content/common/gpu/client/command_buffer_proxy.h"
#include "content/common/gpu/client/gpu_channel_host.h"
#include "googleurl/src/gurl.h"
#include "ipc/ipc_channel_handle.h"
#if defined(ENABLE_GPU)
#include "gpu/command_buffer/client/gles2_cmd_helper.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_lib.h"
#include "gpu/command_buffer/client/transfer_buffer.h"
#include "gpu/command_buffer/common/constants.h"
#endif // ENABLE_GPU
namespace {
const int32 kCommandBufferSize = 1024 * 1024;
// TODO(kbr): make the transfer buffer size configurable via context
// creation attributes.
const size_t kStartTransferBufferSize = 1 * 1024 * 1024;
const size_t kMinTransferBufferSize = 1 * 256 * 1024;
const size_t kMaxTransferBufferSize = 16 * 1024 * 1024;
// Singleton used to initialize and terminate the gles2 library.
class GLES2Initializer {
public:
GLES2Initializer() {
gles2::Initialize();
}
~GLES2Initializer() {
gles2::Terminate();
}
private:
DISALLOW_COPY_AND_ASSIGN(GLES2Initializer);
};
////////////////////////////////////////////////////////////////////////////////
base::LazyInstance<GLES2Initializer> g_gles2_initializer =
LAZY_INSTANCE_INITIALIZER;
////////////////////////////////////////////////////////////////////////////////
#if defined(ENABLE_GPU)
ContentGLContext::ContextLostReason ConvertReason(
gpu::error::ContextLostReason reason) {
switch (reason) {
case gpu::error::kGuilty:
return ContentGLContext::kGuilty;
case gpu::error::kInnocent:
return ContentGLContext::kInnocent;
case gpu::error::kUnknown:
return ContentGLContext::kUnknown;
}
NOTREACHED();
return ContentGLContext::kUnknown;
}
#endif
} // namespace
ContentGLContext::~ContentGLContext() {
Destroy();
}
ContentGLContext* ContentGLContext::CreateViewContext(
GpuChannelHost* channel,
int32 surface_id,
ContentGLContext* share_group,
const char* allowed_extensions,
const int32* attrib_list,
const GURL& active_url,
gfx::GpuPreference gpu_preference) {
#if defined(ENABLE_GPU)
scoped_ptr<ContentGLContext> context(new ContentGLContext(channel));
if (!context->Initialize(
true,
surface_id,
gfx::Size(),
share_group,
allowed_extensions,
attrib_list,
active_url,
gpu_preference))
return NULL;
return context.release();
#else
return NULL;
#endif
}
ContentGLContext* ContentGLContext::CreateOffscreenContext(
GpuChannelHost* channel,
const gfx::Size& size,
ContentGLContext* share_group,
const char* allowed_extensions,
const int32* attrib_list,
const GURL& active_url,
gfx::GpuPreference gpu_preference) {
#if defined(ENABLE_GPU)
scoped_ptr<ContentGLContext> context(new ContentGLContext(channel));
if (!context->Initialize(
false,
0,
size,
share_group,
allowed_extensions,
attrib_list,
active_url,
gpu_preference))
return NULL;
return context.release();
#else
return NULL;
#endif
}
bool ContentGLContext::SetParent(ContentGLContext* new_parent) {
if (parent_.get() == new_parent)
return true;
// Allocate a texture ID with respect to the parent and change the parent.
uint32 new_parent_texture_id = 0;
if (command_buffer_) {
if (new_parent) {
TRACE_EVENT0("gpu", "ContentGLContext::SetParent::flushParent");
// Flush any remaining commands in the parent context to make sure the
// texture id accounting stays consistent.
int32 token = new_parent->gles2_helper_->InsertToken();
new_parent->gles2_helper_->WaitForToken(token);
new_parent_texture_id =
new_parent->gles2_implementation_->MakeTextureId();
if (!command_buffer_->SetParent(new_parent->command_buffer_,
new_parent_texture_id)) {
new_parent->gles2_implementation_->FreeTextureId(parent_texture_id_);
return false;
}
} else {
if (!command_buffer_->SetParent(NULL, 0))
return false;
}
}
// Free the previous parent's texture ID.
if (parent_.get() && parent_texture_id_ != 0) {
// Flush any remaining commands in the parent context to make sure the
// texture id accounting stays consistent.
gpu::gles2::GLES2Implementation* parent_gles2 =
parent_->GetImplementation();
parent_gles2->helper()->CommandBufferHelper::Finish();
parent_gles2->FreeTextureId(parent_texture_id_);
}
if (new_parent) {
parent_ = new_parent->AsWeakPtr();
parent_texture_id_ = new_parent_texture_id;
} else {
parent_.reset();
parent_texture_id_ = 0;
}
return true;
}
uint32 ContentGLContext::GetParentTextureId() {
return parent_texture_id_;
}
uint32 ContentGLContext::CreateParentTexture(const gfx::Size& size) {
uint32 texture_id = 0;
gles2_implementation_->GenTextures(1, &texture_id);
gles2_implementation_->Flush();
return texture_id;
}
void ContentGLContext::DeleteParentTexture(uint32 texture) {
gles2_implementation_->DeleteTextures(1, &texture);
}
void ContentGLContext::SetContextLostCallback(
const base::Callback<void (ContextLostReason)>& callback) {
context_lost_callback_ = callback;
}
bool ContentGLContext::MakeCurrent(ContentGLContext* context) {
if (context) {
DCHECK(context->CalledOnValidThread());
gles2::SetGLContext(context->gles2_implementation_);
// Don't request latest error status from service. Just use the locally
// cached information from the last flush.
// TODO(apatrick): I'm not sure if this should actually change the
// current context if it fails. For now it gets changed even if it fails
// because making GL calls with a NULL context crashes.
if (context->command_buffer_->GetLastError() != gpu::error::kNoError)
return false;
} else {
gles2::SetGLContext(NULL);
}
return true;
}
bool ContentGLContext::SwapBuffers() {
TRACE_EVENT1("gpu", "ContentGLContext::SwapBuffers", "frame", frame_number_);
frame_number_++;
// Don't request latest error status from service. Just use the locally cached
// information from the last flush.
if (command_buffer_->GetLastState().error != gpu::error::kNoError)
return false;
gles2_implementation_->SwapBuffers();
return true;
}
bool ContentGLContext::Echo(const base::Closure& task) {
return command_buffer_->Echo(task);
}
ContentGLContext::Error ContentGLContext::GetError() {
gpu::CommandBuffer::State state = command_buffer_->GetState();
if (state.error == gpu::error::kNoError) {
Error old_error = last_error_;
last_error_ = SUCCESS;
return old_error;
} else {
// All command buffer errors are unrecoverable. The error is treated as a
// lost context: destroy the context and create another one.
return CONTEXT_LOST;
}
}
bool ContentGLContext::IsCommandBufferContextLost() {
// If the channel shut down unexpectedly, let that supersede the
// command buffer's state.
if (channel_->state() == GpuChannelHost::kLost)
return true;
gpu::CommandBuffer::State state = command_buffer_->GetLastState();
return state.error == gpu::error::kLostContext;
}
CommandBufferProxy* ContentGLContext::GetCommandBufferProxy() {
return command_buffer_;
}
bool ContentGLContext::SetSurfaceVisible(bool visible) {
return GetCommandBufferProxy()->SetSurfaceVisible(visible);
}
// TODO(gman): Remove This
void ContentGLContext::DisableShaderTranslation() {
NOTREACHED();
}
gpu::gles2::GLES2Implementation* ContentGLContext::GetImplementation() {
return gles2_implementation_;
}
ContentGLContext::ContentGLContext(GpuChannelHost* channel)
: channel_(channel),
parent_(base::WeakPtr<ContentGLContext>()),
parent_texture_id_(0),
command_buffer_(NULL),
gles2_helper_(NULL),
transfer_buffer_(NULL),
gles2_implementation_(NULL),
last_error_(SUCCESS),
frame_number_(0) {
DCHECK(channel);
}
bool ContentGLContext::Initialize(bool onscreen,
int32 surface_id,
const gfx::Size& size,
ContentGLContext* share_group,
const char* allowed_extensions,
const int32* attrib_list,
const GURL& active_url,
gfx::GpuPreference gpu_preference) {
DCHECK(CalledOnValidThread());
DCHECK(size.width() >= 0 && size.height() >= 0);
TRACE_EVENT2("gpu", "ContentGLContext::Initialize",
"on_screen", onscreen, "num_pixels", size.GetArea());
if (channel_->state() != GpuChannelHost::kConnected)
return false;
// Ensure the gles2 library is initialized first in a thread safe way.
g_gles2_initializer.Get();
bool share_resources = true;
bool bind_generates_resources = true;
std::vector<int32> attribs;
while (attrib_list) {
int32 attrib = *attrib_list++;
switch (attrib) {
// Known attributes
case ALPHA_SIZE:
case BLUE_SIZE:
case GREEN_SIZE:
case RED_SIZE:
case DEPTH_SIZE:
case STENCIL_SIZE:
case SAMPLES:
case SAMPLE_BUFFERS:
attribs.push_back(attrib);
attribs.push_back(*attrib_list++);
break;
case SHARE_RESOURCES:
share_resources = !!(*attrib_list++);
break;
case BIND_GENERATES_RESOURCES:
bind_generates_resources = !!(*attrib_list++);
break;
case NONE:
attribs.push_back(attrib);
attrib_list = NULL;
break;
default:
last_error_ = BAD_ATTRIBUTE;
attribs.push_back(NONE);
attrib_list = NULL;
break;
}
}
// Create a proxy to a command buffer in the GPU process.
if (onscreen) {
TRACE_EVENT0("gpu",
"ContentGLContext::Initialize::CreateViewCommandBuffer");
command_buffer_ = channel_->CreateViewCommandBuffer(
surface_id,
share_group ? share_group->command_buffer_ : NULL,
allowed_extensions,
attribs,
active_url,
gpu_preference);
} else {
command_buffer_ = channel_->CreateOffscreenCommandBuffer(
size,
share_group ? share_group->command_buffer_ : NULL,
allowed_extensions,
attribs,
active_url,
gpu_preference);
}
if (!command_buffer_) {
Destroy();
return false;
}
{
TRACE_EVENT0("gpu",
"ContentGLContext::Initialize::InitializeCommandBuffer");
// Initiaize the command buffer.
if (!command_buffer_->Initialize()) {
Destroy();
return false;
}
}
command_buffer_->SetChannelErrorCallback(
base::Bind(&ContentGLContext::OnContextLost, base::Unretained(this)));
// Create the GLES2 helper, which writes the command buffer protocol.
gles2_helper_ = new gpu::gles2::GLES2CmdHelper(command_buffer_);
if (!gles2_helper_->Initialize(kCommandBufferSize)) {
Destroy();
return false;
}
{
TRACE_EVENT0("gpu", "ContentGLContext::Initialize::CreateTransferBuffer");
// Create a transfer buffer used to copy resources between the renderer
// process and the GPU process.
transfer_buffer_ = new gpu::TransferBuffer(gles2_helper_);
}
// Create the object exposing the OpenGL API.
gles2_implementation_ = new gpu::gles2::GLES2Implementation(
gles2_helper_,
transfer_buffer_,
share_resources,
bind_generates_resources);
if (!gles2_implementation_->Initialize(
kStartTransferBufferSize,
kMinTransferBufferSize,
kMaxTransferBufferSize)) {
Destroy();
return false;
}
return true;
}
void ContentGLContext::Destroy() {
TRACE_EVENT0("gpu", "ContentGLContext::Destroy");
DCHECK(CalledOnValidThread());
SetParent(NULL);
if (gles2_implementation_) {
// First flush the context to ensure that any pending frees of resources
// are completed. Otherwise, if this context is part of a share group,
// those resources might leak. Also, any remaining side effects of commands
// issued on this context might not be visible to other contexts in the
// share group.
gles2_implementation_->Flush();
delete gles2_implementation_;
gles2_implementation_ = NULL;
}
if (transfer_buffer_) {
delete transfer_buffer_;
transfer_buffer_ = NULL;
}
delete gles2_helper_;
gles2_helper_ = NULL;
if (channel_ && command_buffer_) {
channel_->DestroyCommandBuffer(command_buffer_);
command_buffer_ = NULL;
}
channel_ = NULL;
}
void ContentGLContext::OnContextLost() {
if (!context_lost_callback_.is_null()) {
ContentGLContext::ContextLostReason reason = kUnknown;
if (command_buffer_) {
reason = ConvertReason(
command_buffer_->GetLastState().context_lost_reason);
}
context_lost_callback_.Run(reason);
}
}
<|endoftext|>
|
<commit_before>//===--- ParentVirtualCallCheck.cpp - clang-tidy---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ParentVirtualCallCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/FixIt.h"
#include "llvm/ADT/SmallVector.h"
#include <algorithm>
#include <cctype>
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace bugprone {
using BasesVector = llvm::SmallVector<const CXXRecordDecl *, 5>;
static bool isParentOf(const CXXRecordDecl &Parent,
const CXXRecordDecl &ThisClass) {
if (Parent.getCanonicalDecl() == ThisClass.getCanonicalDecl())
return true;
for (const CXXBaseSpecifier &Base : ThisClass.bases()) {
auto *BaseDecl = Base.getType()->getAsCXXRecordDecl();
assert(BaseDecl);
if (Parent.getCanonicalDecl() == BaseDecl->getCanonicalDecl())
return true;
}
return false;
}
static BasesVector getParentsByGrandParent(const CXXRecordDecl &GrandParent,
const CXXRecordDecl &ThisClass,
const CXXMethodDecl &MemberDecl) {
BasesVector Result;
for (const auto &Base : ThisClass.bases()) {
const auto *BaseDecl = Base.getType()->getAsCXXRecordDecl();
const CXXMethodDecl *ActualMemberDecl =
MemberDecl.getCorrespondingMethodInClass(BaseDecl);
if (!ActualMemberDecl)
continue;
// TypePtr is the nearest base class to ThisClass between ThisClass and
// GrandParent, where MemberDecl is overridden. TypePtr is the class the
// check proposes to fix to.
const Type *TypePtr =
ActualMemberDecl->getThisType(ActualMemberDecl->getASTContext())
.getTypePtr();
const CXXRecordDecl *RecordDeclType = TypePtr->getPointeeCXXRecordDecl();
assert(RecordDeclType && "TypePtr is not a pointer to CXXRecordDecl!");
if (RecordDeclType->getCanonicalDecl()->isDerivedFrom(&GrandParent))
Result.emplace_back(RecordDeclType);
}
return Result;
}
static std::string getNameAsString(const NamedDecl *Decl) {
std::string QualName;
llvm::raw_string_ostream OS(QualName);
PrintingPolicy PP(Decl->getASTContext().getPrintingPolicy());
PP.SuppressUnwrittenScope = true;
Decl->printQualifiedName(OS, PP);
return OS.str();
}
// Returns E as written in the source code. Used to handle 'using' and
// 'typedef'ed names of grand-parent classes.
static std::string getExprAsString(const clang::Expr &E,
clang::ASTContext &AC) {
std::string Text = tooling::fixit::getText(E, AC).str();
Text.erase(
std::remove_if(
Text.begin(), Text.end(),
[](char c) { return std::isspace(static_cast<unsigned char>(c)); }),
Text.end());
return Text;
}
void ParentVirtualCallCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(
cxxMemberCallExpr(
callee(memberExpr(hasDescendant(implicitCastExpr(
hasImplicitDestinationType(pointsTo(
type(anything()).bind("castToType"))),
hasSourceExpression(cxxThisExpr(hasType(
type(anything()).bind("thisType")))))))
.bind("member")),
callee(cxxMethodDecl(isVirtual())))
.bind("call"),
this);
}
void ParentVirtualCallCheck::check(const MatchFinder::MatchResult &Result) {
const auto *MatchedDecl = Result.Nodes.getNodeAs<CXXMemberCallExpr>("call");
assert(MatchedDecl);
const auto *Member = Result.Nodes.getNodeAs<MemberExpr>("member");
assert(Member);
if (!Member->getQualifier())
return;
const auto *MemberDecl = cast<CXXMethodDecl>(Member->getMemberDecl());
const auto *ThisTypePtr = Result.Nodes.getNodeAs<PointerType>("thisType");
assert(ThisTypePtr);
const auto *ThisType = ThisTypePtr->getPointeeCXXRecordDecl();
assert(ThisType);
const auto *CastToTypePtr = Result.Nodes.getNodeAs<Type>("castToType");
assert(CastToTypePtr);
const auto *CastToType = CastToTypePtr->getAsCXXRecordDecl();
assert(CastToType);
if (isParentOf(*CastToType, *ThisType))
return;
const BasesVector Parents =
getParentsByGrandParent(*CastToType, *ThisType, *MemberDecl);
if (Parents.empty())
return;
std::string ParentsStr;
ParentsStr.reserve(30 * Parents.size());
for (const CXXRecordDecl *Parent : Parents) {
if (!ParentsStr.empty())
ParentsStr.append(" or ");
ParentsStr.append("'").append(getNameAsString(Parent)).append("'");
}
assert(Member->getQualifierLoc().getSourceRange().getBegin().isValid());
auto Diag = diag(Member->getQualifierLoc().getSourceRange().getBegin(),
"qualified name '%0' refers to a member overridden "
"in subclass%1; did you mean %2?")
<< getExprAsString(*Member, *Result.Context)
<< (Parents.size() > 1 ? "es" : "") << ParentsStr;
// Propose a fix if there's only one parent class...
if (Parents.size() == 1 &&
// ...unless parent class is templated
!isa<ClassTemplateSpecializationDecl>(Parents.front()))
Diag << FixItHint::CreateReplacement(
Member->getQualifierLoc().getSourceRange(),
getNameAsString(Parents.front()) + "::");
}
} // namespace bugprone
} // namespace tidy
} // namespace clang
<commit_msg>Fix unused variable warning.<commit_after>//===--- ParentVirtualCallCheck.cpp - clang-tidy---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ParentVirtualCallCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/FixIt.h"
#include "llvm/ADT/SmallVector.h"
#include <algorithm>
#include <cctype>
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace bugprone {
using BasesVector = llvm::SmallVector<const CXXRecordDecl *, 5>;
static bool isParentOf(const CXXRecordDecl &Parent,
const CXXRecordDecl &ThisClass) {
if (Parent.getCanonicalDecl() == ThisClass.getCanonicalDecl())
return true;
for (const CXXBaseSpecifier &Base : ThisClass.bases()) {
auto *BaseDecl = Base.getType()->getAsCXXRecordDecl();
assert(BaseDecl);
if (Parent.getCanonicalDecl() == BaseDecl->getCanonicalDecl())
return true;
}
return false;
}
static BasesVector getParentsByGrandParent(const CXXRecordDecl &GrandParent,
const CXXRecordDecl &ThisClass,
const CXXMethodDecl &MemberDecl) {
BasesVector Result;
for (const auto &Base : ThisClass.bases()) {
const auto *BaseDecl = Base.getType()->getAsCXXRecordDecl();
const CXXMethodDecl *ActualMemberDecl =
MemberDecl.getCorrespondingMethodInClass(BaseDecl);
if (!ActualMemberDecl)
continue;
// TypePtr is the nearest base class to ThisClass between ThisClass and
// GrandParent, where MemberDecl is overridden. TypePtr is the class the
// check proposes to fix to.
const Type *TypePtr =
ActualMemberDecl->getThisType(ActualMemberDecl->getASTContext())
.getTypePtr();
const CXXRecordDecl *RecordDeclType = TypePtr->getPointeeCXXRecordDecl();
assert(RecordDeclType && "TypePtr is not a pointer to CXXRecordDecl!");
if (RecordDeclType->getCanonicalDecl()->isDerivedFrom(&GrandParent))
Result.emplace_back(RecordDeclType);
}
return Result;
}
static std::string getNameAsString(const NamedDecl *Decl) {
std::string QualName;
llvm::raw_string_ostream OS(QualName);
PrintingPolicy PP(Decl->getASTContext().getPrintingPolicy());
PP.SuppressUnwrittenScope = true;
Decl->printQualifiedName(OS, PP);
return OS.str();
}
// Returns E as written in the source code. Used to handle 'using' and
// 'typedef'ed names of grand-parent classes.
static std::string getExprAsString(const clang::Expr &E,
clang::ASTContext &AC) {
std::string Text = tooling::fixit::getText(E, AC).str();
Text.erase(
std::remove_if(
Text.begin(), Text.end(),
[](char c) { return std::isspace(static_cast<unsigned char>(c)); }),
Text.end());
return Text;
}
void ParentVirtualCallCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(
cxxMemberCallExpr(
callee(memberExpr(hasDescendant(implicitCastExpr(
hasImplicitDestinationType(pointsTo(
type(anything()).bind("castToType"))),
hasSourceExpression(cxxThisExpr(hasType(
type(anything()).bind("thisType")))))))
.bind("member")),
callee(cxxMethodDecl(isVirtual())))
.bind("call"),
this);
}
void ParentVirtualCallCheck::check(const MatchFinder::MatchResult &Result) {
const auto *MatchedDecl = Result.Nodes.getNodeAs<CXXMemberCallExpr>("call");
(void)MatchedDecl;
assert(MatchedDecl);
const auto *Member = Result.Nodes.getNodeAs<MemberExpr>("member");
assert(Member);
if (!Member->getQualifier())
return;
const auto *MemberDecl = cast<CXXMethodDecl>(Member->getMemberDecl());
const auto *ThisTypePtr = Result.Nodes.getNodeAs<PointerType>("thisType");
assert(ThisTypePtr);
const auto *ThisType = ThisTypePtr->getPointeeCXXRecordDecl();
assert(ThisType);
const auto *CastToTypePtr = Result.Nodes.getNodeAs<Type>("castToType");
assert(CastToTypePtr);
const auto *CastToType = CastToTypePtr->getAsCXXRecordDecl();
assert(CastToType);
if (isParentOf(*CastToType, *ThisType))
return;
const BasesVector Parents =
getParentsByGrandParent(*CastToType, *ThisType, *MemberDecl);
if (Parents.empty())
return;
std::string ParentsStr;
ParentsStr.reserve(30 * Parents.size());
for (const CXXRecordDecl *Parent : Parents) {
if (!ParentsStr.empty())
ParentsStr.append(" or ");
ParentsStr.append("'").append(getNameAsString(Parent)).append("'");
}
assert(Member->getQualifierLoc().getSourceRange().getBegin().isValid());
auto Diag = diag(Member->getQualifierLoc().getSourceRange().getBegin(),
"qualified name '%0' refers to a member overridden "
"in subclass%1; did you mean %2?")
<< getExprAsString(*Member, *Result.Context)
<< (Parents.size() > 1 ? "es" : "") << ParentsStr;
// Propose a fix if there's only one parent class...
if (Parents.size() == 1 &&
// ...unless parent class is templated
!isa<ClassTemplateSpecializationDecl>(Parents.front()))
Diag << FixItHint::CreateReplacement(
Member->getQualifierLoc().getSourceRange(),
getNameAsString(Parents.front()) + "::");
}
} // namespace bugprone
} // namespace tidy
} // namespace clang
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2017 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file baro.cpp
* Implementation of the Baro Temperature Calibration for onboard sensors.
*
* @author Siddharth Bharat Purohit
* @author Paul Riseborough
* @author Beat Küng <beat-kueng@gmx.net>
*/
#include "baro.h"
#include <uORB/topics/sensor_baro.h>
#include <mathlib/mathlib.h>
TemperatureCalibrationBaro::TemperatureCalibrationBaro(float min_temperature_rise, float min_start_temperature)
: TemperatureCalibrationCommon(min_temperature_rise, min_start_temperature)
{
//init subscriptions
_num_sensor_instances = orb_group_count(ORB_ID(sensor_baro));
if (_num_sensor_instances > SENSOR_COUNT_MAX) {
_num_sensor_instances = SENSOR_COUNT_MAX;
}
for (unsigned i = 0; i < _num_sensor_instances; i++) {
_sensor_subs[i] = orb_subscribe_multi(ORB_ID(sensor_baro), i);
}
}
TemperatureCalibrationBaro::~TemperatureCalibrationBaro()
{
for (unsigned i = 0; i < _num_sensor_instances; i++) {
orb_unsubscribe(_sensor_subs[i]);
}
}
void TemperatureCalibrationBaro::reset_calibration()
{
//nothing to do
}
int TemperatureCalibrationBaro::update_sensor_instance(PerSensorData &data, int sensor_sub)
{
bool finished = data.hot_soaked;
bool updated;
orb_check(sensor_sub, &updated);
if (!updated) {
return finished ? 0 : 1;
}
sensor_baro_s baro_data;
orb_copy(ORB_ID(sensor_baro), sensor_sub, &baro_data);
if (finished) {
// if we're done, return, but we need to return after orb_copy because of poll()
return 0;
}
data.device_id = baro_data.device_id;
data.sensor_sample_filt[0] = 100.0f * baro_data.pressure; // convert from hPA to Pa
data.sensor_sample_filt[1] = baro_data.temperature;
if (!data.cold_soaked) {
data.cold_soaked = true;
data.low_temp = data.sensor_sample_filt[1]; //Record the low temperature
data.ref_temp = data.sensor_sample_filt[1] + 0.5f * _min_temperature_rise;
}
// check if temperature increased
if (data.sensor_sample_filt[1] > data.high_temp) {
data.high_temp = data.sensor_sample_filt[1];
data.hot_soak_sat = 0;
} else {
return 1;
}
//TODO: Detect when temperature has stopped rising for more than TBD seconds
if (data.hot_soak_sat == 10 || (data.high_temp - data.low_temp) > _min_temperature_rise) {
data.hot_soaked = true;
}
if (sensor_sub == _sensor_subs[0]) { // debug output, but only for the first sensor
TC_DEBUG("\nBaro: %.20f,%.20f,%.20f,%.20f, %.6f, %.6f, %.6f\n\n", (double)data.sensor_sample_filt[0],
(double)data.sensor_sample_filt[1], (double)data.low_temp, (double)data.high_temp,
(double)(data.high_temp - data.low_temp));
}
//update linear fit matrices
data.sensor_sample_filt[1] -= data.ref_temp;
data.P[0].update((double)data.sensor_sample_filt[1], (double)data.sensor_sample_filt[0]);
return 1;
}
int TemperatureCalibrationBaro::finish()
{
for (unsigned uorb_index = 0; uorb_index < _num_sensor_instances; uorb_index++) {
finish_sensor_instance(_data[uorb_index], uorb_index);
}
int32_t enabled = 1;
int result = param_set_no_notification(param_find("TC_B_ENABLE"), &enabled);
if (result != PX4_OK) {
PX4_ERR("unable to reset TC_B_ENABLE (%i)", result);
}
return result;
}
int TemperatureCalibrationBaro::finish_sensor_instance(PerSensorData &data, int sensor_index)
{
if (!data.hot_soaked || data.tempcal_complete) {
return 0;
}
double res[POLYFIT_ORDER + 1] = {};
data.P[0].fit(res);
res[POLYFIT_ORDER] =
0.0; // normalise the correction to be zero at the reference temperature by setting the X^0 coefficient to zero
PX4_INFO("Result baro %u %.20f %.20f %.20f %.20f %.20f %.20f", sensor_index, (double)res[0],
(double)res[1], (double)res[2], (double)res[3], (double)res[4], (double)res[5]);
data.tempcal_complete = true;
char str[30];
float param = 0.0f;
int result = PX4_OK;
set_parameter("TC_B%d_ID", sensor_index, &data.device_id);
for (unsigned coef_index = 0; coef_index <= POLYFIT_ORDER; coef_index++) {
sprintf(str, "TC_B%d_X%d", sensor_index, (POLYFIT_ORDER - coef_index));
param = (float)res[coef_index];
result = param_set_no_notification(param_find(str), ¶m);
if (result != PX4_OK) {
PX4_ERR("unable to reset %s", str);
}
}
set_parameter("TC_B%d_TMAX", sensor_index, &data.high_temp);
set_parameter("TC_B%d_TMIN", sensor_index, &data.low_temp);
set_parameter("TC_B%d_TREF", sensor_index, &data.ref_temp);
return 0;
}
<commit_msg>events: don't start baro calibration until specified temperature achieved<commit_after>/****************************************************************************
*
* Copyright (c) 2017 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file baro.cpp
* Implementation of the Baro Temperature Calibration for onboard sensors.
*
* @author Siddharth Bharat Purohit
* @author Paul Riseborough
* @author Beat Küng <beat-kueng@gmx.net>
*/
#include "baro.h"
#include <uORB/topics/sensor_baro.h>
#include <mathlib/mathlib.h>
TemperatureCalibrationBaro::TemperatureCalibrationBaro(float min_temperature_rise, float min_start_temperature)
: TemperatureCalibrationCommon(min_temperature_rise, min_start_temperature)
{
//init subscriptions
_num_sensor_instances = orb_group_count(ORB_ID(sensor_baro));
if (_num_sensor_instances > SENSOR_COUNT_MAX) {
_num_sensor_instances = SENSOR_COUNT_MAX;
}
for (unsigned i = 0; i < _num_sensor_instances; i++) {
_sensor_subs[i] = orb_subscribe_multi(ORB_ID(sensor_baro), i);
}
}
TemperatureCalibrationBaro::~TemperatureCalibrationBaro()
{
for (unsigned i = 0; i < _num_sensor_instances; i++) {
orb_unsubscribe(_sensor_subs[i]);
}
}
void TemperatureCalibrationBaro::reset_calibration()
{
//nothing to do
}
int TemperatureCalibrationBaro::update_sensor_instance(PerSensorData &data, int sensor_sub)
{
bool finished = data.hot_soaked;
bool updated;
orb_check(sensor_sub, &updated);
if (!updated) {
return finished ? 0 : 1;
}
sensor_baro_s baro_data;
orb_copy(ORB_ID(sensor_baro), sensor_sub, &baro_data);
if (finished) {
// if we're done, return, but we need to return after orb_copy because of poll()
return 0;
}
data.device_id = baro_data.device_id;
data.sensor_sample_filt[0] = 100.0f * baro_data.pressure; // convert from hPA to Pa
data.sensor_sample_filt[1] = baro_data.temperature;
// wait for min start temp to be reached before starting calibration
if (data.sensor_sample_filt[1] < _min_start_temperature) {
return 1;
}
if (!data.cold_soaked) {
data.cold_soaked = true;
data.low_temp = data.sensor_sample_filt[1]; //Record the low temperature
data.ref_temp = data.sensor_sample_filt[1] + 0.5f * _min_temperature_rise;
}
// check if temperature increased
if (data.sensor_sample_filt[1] > data.high_temp) {
data.high_temp = data.sensor_sample_filt[1];
data.hot_soak_sat = 0;
} else {
return 1;
}
//TODO: Detect when temperature has stopped rising for more than TBD seconds
if (data.hot_soak_sat == 10 || (data.high_temp - data.low_temp) > _min_temperature_rise) {
data.hot_soaked = true;
}
if (sensor_sub == _sensor_subs[0]) { // debug output, but only for the first sensor
TC_DEBUG("\nBaro: %.20f,%.20f,%.20f,%.20f, %.6f, %.6f, %.6f\n\n", (double)data.sensor_sample_filt[0],
(double)data.sensor_sample_filt[1], (double)data.low_temp, (double)data.high_temp,
(double)(data.high_temp - data.low_temp));
}
//update linear fit matrices
data.sensor_sample_filt[1] -= data.ref_temp;
data.P[0].update((double)data.sensor_sample_filt[1], (double)data.sensor_sample_filt[0]);
return 1;
}
int TemperatureCalibrationBaro::finish()
{
for (unsigned uorb_index = 0; uorb_index < _num_sensor_instances; uorb_index++) {
finish_sensor_instance(_data[uorb_index], uorb_index);
}
int32_t enabled = 1;
int result = param_set_no_notification(param_find("TC_B_ENABLE"), &enabled);
if (result != PX4_OK) {
PX4_ERR("unable to reset TC_B_ENABLE (%i)", result);
}
return result;
}
int TemperatureCalibrationBaro::finish_sensor_instance(PerSensorData &data, int sensor_index)
{
if (!data.hot_soaked || data.tempcal_complete) {
return 0;
}
double res[POLYFIT_ORDER + 1] = {};
data.P[0].fit(res);
res[POLYFIT_ORDER] =
0.0; // normalise the correction to be zero at the reference temperature by setting the X^0 coefficient to zero
PX4_INFO("Result baro %u %.20f %.20f %.20f %.20f %.20f %.20f", sensor_index, (double)res[0],
(double)res[1], (double)res[2], (double)res[3], (double)res[4], (double)res[5]);
data.tempcal_complete = true;
char str[30];
float param = 0.0f;
int result = PX4_OK;
set_parameter("TC_B%d_ID", sensor_index, &data.device_id);
for (unsigned coef_index = 0; coef_index <= POLYFIT_ORDER; coef_index++) {
sprintf(str, "TC_B%d_X%d", sensor_index, (POLYFIT_ORDER - coef_index));
param = (float)res[coef_index];
result = param_set_no_notification(param_find(str), ¶m);
if (result != PX4_OK) {
PX4_ERR("unable to reset %s", str);
}
}
set_parameter("TC_B%d_TMAX", sensor_index, &data.high_temp);
set_parameter("TC_B%d_TMIN", sensor_index, &data.low_temp);
set_parameter("TC_B%d_TREF", sensor_index, &data.ref_temp);
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: datasourceconnector.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2003-03-19 17:52:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DBAUI_DATASOURCECONNECTOR_HXX_
#include "datasourceconnector.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XCOMPLETEDCONNECTION_HPP_
#include <com/sun/star/sdb/XCompletedConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_
#include <com/sun/star/sdb/SQLContext.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::dbtools;
//=====================================================================
//= ODatasourceConnector
//=====================================================================
//---------------------------------------------------------------------
ODatasourceConnector::ODatasourceConnector(const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent)
:m_xORB(_rxORB)
,m_pErrorMessageParent(_pMessageParent)
{
implConstruct();
}
//---------------------------------------------------------------------
ODatasourceConnector::ODatasourceConnector( const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent,
const ::rtl::OUString& _rContextInformation, const ::rtl::OUString& _rContextDetails )
:m_xORB(_rxORB)
,m_pErrorMessageParent(_pMessageParent)
,m_sContextInformation( _rContextInformation )
,m_sContextDetails( _rContextDetails )
{
implConstruct();
}
//---------------------------------------------------------------------
void ODatasourceConnector::implConstruct()
{
OSL_ENSURE(m_xORB.is(), "ODatasourceConnector::implConstruct: invalid ORB!");
if (m_xORB.is())
{
try
{
Reference< XInterface > xContext = m_xORB->createInstance(SERVICE_SDB_DATABASECONTEXT);
OSL_ENSURE(xContext.is(), "ODatasourceConnector::implConstruct: got no data source context!");
m_xDatabaseContext = Reference< XNameAccess >(xContext, UNO_QUERY);
OSL_ENSURE(m_xDatabaseContext.is() || !xContext.is(), "ODatasourceConnector::ODatasourceConnector: missing the XNameAccess interface on the data source context!");
}
catch(const Exception&)
{
OSL_ENSURE(sal_False, "ODatasourceConnector::implConstruct: caught an exception while creating the data source context!");
}
}
}
//---------------------------------------------------------------------
Reference< XConnection > ODatasourceConnector::connect(const ::rtl::OUString& _rDataSourceName, sal_Bool _bShowError) const
{
Reference< XConnection > xConnection;
OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!");
if (!isValid())
return xConnection;
// get the data source
Reference< XPropertySet > xDatasource;
try
{
m_xDatabaseContext->getByName(_rDataSourceName) >>= xDatasource;
}
catch(Exception&)
{
}
if (!xDatasource.is())
{
OSL_ENSURE(sal_False,( ::rtl::OString("ODatasourceConnector::connect: could not retrieve the data source named ")
+= ::rtl::OString(_rDataSourceName.getStr(), _rDataSourceName.getLength(), osl_getThreadTextEncoding())
+= ::rtl::OString(" !")).getStr());
return xConnection;
}
// get user/password
::rtl::OUString sPassword, sUser;
sal_Bool bPwdRequired = sal_False;
try
{
xDatasource->getPropertyValue(PROPERTY_PASSWORD) >>= sPassword;
bPwdRequired = ::cppu::any2bool(xDatasource->getPropertyValue(PROPERTY_ISPASSWORDREQUIRED));
xDatasource->getPropertyValue(PROPERTY_USER) >>= sUser;
}
catch(Exception&)
{
OSL_ENSURE(sal_False, "ODatasourceConnector::connect: error while retrieving data source properties!");
}
// try to connect
SQLExceptionInfo aInfo;
try
{
if (bPwdRequired && !sPassword.getLength())
{ // password required, but empty -> connect using an interaction handler
Reference< XCompletedConnection > xConnectionCompletion(xDatasource, UNO_QUERY);
if (!xConnectionCompletion.is())
{
OSL_ENSURE(sal_False, "ODatasourceConnector::connect: missing an interface ... need an error message here!");
}
else
{ // instantiate the default SDB interaction handler
Reference< XInteractionHandler > xHandler(m_xORB->createInstance(SERVICE_SDB_INTERACTION_HANDLER), UNO_QUERY);
if (!xHandler.is())
{
ShowServiceNotAvailableError(m_pErrorMessageParent, String(SERVICE_SDB_INTERACTION_HANDLER), sal_True);
}
else
{
xConnection = xConnectionCompletion->connectWithCompletion(xHandler);
}
}
}
else
{
Reference< XDataSource > xDataSource(xDatasource,UNO_QUERY);
xConnection = xDataSource->getConnection(sUser, sPassword);
}
}
catch(SQLContext& e) { aInfo = SQLExceptionInfo(e); }
catch(SQLWarning& e) { aInfo = SQLExceptionInfo(e); }
catch(SQLException& e) { aInfo = SQLExceptionInfo(e); }
catch(Exception&) { OSL_ENSURE(sal_False, "SbaTableQueryBrowser::OnExpandEntry: could not connect - unknown exception!"); }
// display the error (if any)
if ( _bShowError && aInfo.isValid() )
{
if ( m_sContextInformation.getLength() )
{
SQLContext aContext;
aContext.Message = m_sContextInformation;
aContext.Details = m_sContextDetails;
aContext.NextException = aInfo.get();
aInfo = aContext;
}
showError(aInfo, m_pErrorMessageParent, m_xORB);
}
return xConnection;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS insight01 (1.4.64); FILE MERGED 2004/03/11 09:04:00 oj 1.4.64.2: #111075# changes for closing 2003/10/24 06:36:48 oj 1.4.64.1: #i21643# import filter changes<commit_after>/*************************************************************************
*
* $RCSfile: datasourceconnector.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2004-08-02 16:08:51 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DBAUI_DATASOURCECONNECTOR_HXX_
#include "datasourceconnector.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XCOMPLETEDCONNECTION_HPP_
#include <com/sun/star/sdb/XCompletedConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_
#include <com/sun/star/sdb/SQLContext.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::dbtools;
//=====================================================================
//= ODatasourceConnector
//=====================================================================
//---------------------------------------------------------------------
ODatasourceConnector::ODatasourceConnector(const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent)
:m_xORB(_rxORB)
,m_pErrorMessageParent(_pMessageParent)
{
implConstruct();
}
//---------------------------------------------------------------------
ODatasourceConnector::ODatasourceConnector( const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent,
const ::rtl::OUString& _rContextInformation, const ::rtl::OUString& _rContextDetails )
:m_xORB(_rxORB)
,m_pErrorMessageParent(_pMessageParent)
,m_sContextInformation( _rContextInformation )
,m_sContextDetails( _rContextDetails )
{
implConstruct();
}
//---------------------------------------------------------------------
void ODatasourceConnector::implConstruct()
{
OSL_ENSURE(m_xORB.is(), "ODatasourceConnector::implConstruct: invalid ORB!");
if (m_xORB.is())
{
try
{
Reference< XInterface > xContext = m_xORB->createInstance(SERVICE_SDB_DATABASECONTEXT);
OSL_ENSURE(xContext.is(), "ODatasourceConnector::implConstruct: got no data source context!");
m_xDatabaseContext.set(xContext,UNO_QUERY);
OSL_ENSURE(m_xDatabaseContext.is() || !xContext.is(), "ODatasourceConnector::ODatasourceConnector: missing the XNameAccess interface on the data source context!");
}
catch(const Exception&)
{
OSL_ENSURE(sal_False, "ODatasourceConnector::implConstruct: caught an exception while creating the data source context!");
}
}
}
//---------------------------------------------------------------------
Reference< XConnection > ODatasourceConnector::connect(const ::rtl::OUString& _rDataSourceName, sal_Bool _bShowError) const
{
Reference< XConnection > xConnection;
OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!");
if (!isValid())
return xConnection;
// get the data source
Reference< XDataSource > xDatasource;
try
{
m_xDatabaseContext->getByName(_rDataSourceName) >>= xDatasource;
}
catch(Exception&)
{
}
return connect(xDatasource,_bShowError);
}
//---------------------------------------------------------------------
Reference< XConnection > ODatasourceConnector::connect(const Reference< XDataSource>& _xDataSource, sal_Bool _bShowError) const
{
Reference< XConnection > xConnection;
OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!");
if (!isValid())
return xConnection;
if (!_xDataSource.is())
{
OSL_ENSURE(sal_False, "ODatasourceConnector::connect: could not retrieve the data source!");
return xConnection;
}
// get user/password
::rtl::OUString sPassword, sUser;
sal_Bool bPwdRequired = sal_False;
Reference<XPropertySet> xProp(_xDataSource,UNO_QUERY);
try
{
xProp->getPropertyValue(PROPERTY_PASSWORD) >>= sPassword;
xProp->getPropertyValue(PROPERTY_ISPASSWORDREQUIRED) >>= bPwdRequired;
xProp->getPropertyValue(PROPERTY_USER) >>= sUser;
}
catch(Exception&)
{
OSL_ENSURE(sal_False, "ODatasourceConnector::connect: error while retrieving data source properties!");
}
// try to connect
SQLExceptionInfo aInfo;
try
{
if (bPwdRequired && !sPassword.getLength())
{ // password required, but empty -> connect using an interaction handler
Reference< XCompletedConnection > xConnectionCompletion(_xDataSource, UNO_QUERY);
if (!xConnectionCompletion.is())
{
OSL_ENSURE(sal_False, "ODatasourceConnector::connect: missing an interface ... need an error message here!");
}
else
{ // instantiate the default SDB interaction handler
Reference< XInteractionHandler > xHandler(m_xORB->createInstance(SERVICE_SDB_INTERACTION_HANDLER), UNO_QUERY);
if (!xHandler.is())
{
ShowServiceNotAvailableError(m_pErrorMessageParent, String(SERVICE_SDB_INTERACTION_HANDLER), sal_True);
}
else
{
xConnection = xConnectionCompletion->connectWithCompletion(xHandler);
}
}
}
else
{
xConnection = _xDataSource->getConnection(sUser, sPassword);
}
}
catch(SQLContext& e) { aInfo = SQLExceptionInfo(e); }
catch(SQLWarning& e) { aInfo = SQLExceptionInfo(e); }
catch(SQLException& e) { aInfo = SQLExceptionInfo(e); }
catch(Exception&) { OSL_ENSURE(sal_False, "SbaTableQueryBrowser::OnExpandEntry: could not connect - unknown exception!"); }
// display the error (if any)
if ( _bShowError && aInfo.isValid() )
{
if ( m_sContextInformation.getLength() )
{
SQLContext aContext;
aContext.Message = m_sContextInformation;
aContext.Details = m_sContextDetails;
aContext.NextException = aInfo.get();
aInfo = aContext;
}
showError(aInfo, m_pErrorMessageParent, m_xORB);
}
return xConnection;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<|endoftext|>
|
<commit_before>/**
* @file hybrid_height.cpp
*
* @date Apr 5, 2013
* @author peramaki
*/
#include "hybrid_height.h"
#include "plugin_factory.h"
#include "logger_factory.h"
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <math.h>
#define HIMAN_AUXILIARY_INCLUDE
#include "fetcher.h"
#include "neons.h"
#undef HIMAN_AUXILIARY_INCLUDE
using namespace std;
using namespace himan::plugin;
const string itsName("hybrid_height");
hybrid_height::hybrid_height() : itsFastMode(false)
{
itsClearTextFormula = "HEIGHT = prevH + (287/9.81) * (T+prevT)/2 * log(prevP / P)";
itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog(itsName));
}
void hybrid_height::Process(std::shared_ptr<const plugin_configuration> conf)
{
Init(conf);
/*
* Set target parameter to HL-M
* - name HL-M
* - univ_id 3
*
*
* We need to specify grib and querydata parameter information
* since we don't know which one will be the output format.
*
*/
vector<param> theParams;
param theRequestedParam("HL-M", 3);
// GRIB 2
theRequestedParam.GribDiscipline(0);
theRequestedParam.GribCategory(3);
theRequestedParam.GribParameter(6);
// GRIB 1
theParams.push_back(theRequestedParam);
SetParams(theParams);
/*
* For hybrid height we must go through the levels backwards.
*/
itsInfo->LevelOrder(kBottomToTop);
shared_ptr<neons> theNeons = dynamic_pointer_cast <neons> (plugin_factory::Instance()->Plugin("neons"));
itsBottomLevel = boost::lexical_cast<int> (theNeons->ProducerMetaData(230, "last hybrid level number"));
if (!itsConfiguration->Exists("fast_mode") && itsConfiguration->GetValue("fast_mode") == "true")
{
itsFastMode = true;
}
else
{
// When doing exact calculation we must do them sequentially starting from
// surface closest to ground because every surface's value is depended
// on the surface below it. Therefore we cannot parallelize the calculation.
itsThreadCount = 1;
}
Start();
}
/*
* Calculate()
*
* This function does the actual calculation.
*/
void hybrid_height::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)
{
shared_ptr<fetcher> theFetcher = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher"));
param GPParam("P-PA");
param PParam("P-HPA");
param TParam("T-K");
level H2(himan::kHeight, 2, "HEIGHT");
level H0(himan::kHeight, 0, "HEIGHT");
unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog(itsName + "Thread #" + boost::lexical_cast<string> (threadIndex)));
ResetNonLeadingDimension(myTargetInfo);
myTargetInfo->FirstParam();
/*
pitääkö tunnistaa tuottaja?
*/
level prevLevel;
while (AdjustNonLeadingDimension(myTargetInfo))
{
myThreadedLogger->Debug("Calculating time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H") +
" level " + boost::lexical_cast<string> (myTargetInfo->Level().Value()));
bool firstLevel(false);
if (itsFastMode)
{
firstLevel = true;
}
//only works with hirlam for now
//itsLogger->Debug("level: "
if ( myTargetInfo->Level().Value() == itsBottomLevel )
{
firstLevel = true;
}
else
{
prevLevel = level(myTargetInfo->Level());
prevLevel.Value(myTargetInfo->Level().Value() + 1);
prevLevel.Index(prevLevel.Index() + 1);
}
shared_ptr<info> PInfo;
shared_ptr<info> TInfo;
shared_ptr<info> prevPInfo;
shared_ptr<info> prevTInfo;
shared_ptr<info> prevHInfo;
try
{
forecast_time& fTime = myTargetInfo->Time();
if (!firstLevel)
{
prevTInfo = FetchPrevious(fTime, prevLevel, param("T-K"));
prevPInfo = FetchPrevious(fTime, prevLevel, param("P-HPA"));
prevHInfo = FetchPrevious(fTime, prevLevel, param("HL-M"));
}
else
{
prevPInfo = FetchPrevious(fTime, H0, param("P-PA"));
prevTInfo = FetchPrevious(fTime, H2, param("T-K"));
}
//prevLevel = myTargetInfo->Level();
PInfo = theFetcher->Fetch(itsConfiguration,
myTargetInfo->Time(),
myTargetInfo->Level(),
PParam);
TInfo = theFetcher->Fetch(itsConfiguration,
myTargetInfo->Time(),
myTargetInfo->Level(),
TParam);
}
catch (HPExceptionType e)
{
switch (e)
{
case kFileDataNotFound:
itsLogger->Warning("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value()));
myTargetInfo->Data()->Fill(kFloatMissing);
if (itsConfiguration->StatisticsEnabled())
{
itsConfiguration->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size());
itsConfiguration->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size());
}
continue;
break;
default:
throw runtime_error(ClassName() + ": Unable to proceed");
break;
}
}
unique_ptr<timer> processTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer());
if (itsConfiguration->StatisticsEnabled())
{
processTimer->Start();
}
assert(PInfo->Grid()->AB() == TInfo->Grid()->AB());
SetAB(myTargetInfo, TInfo);
size_t missingCount = 0;
size_t count = 0;
shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> PGrid(PInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> prevPGrid(prevPInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> TGrid(TInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> prevTGrid(prevTInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> prevHGrid;
if (!firstLevel )
prevHGrid = shared_ptr<NFmiGrid>(prevHInfo->Grid()->ToNewbaseGrid());
bool equalGrids = ( *myTargetInfo->Grid() == *prevTInfo->Grid() && *myTargetInfo->Grid() == *prevPInfo->Grid() && *myTargetInfo->Grid() == *PInfo->Grid() && *myTargetInfo->Grid() == *TInfo->Grid() ); //&& *myTargetInfo->Grid() == *T2mInfo->Grid() && *myTargetInfo->Grid() == *P0mInfo->Grid() );
if (!firstLevel)
equalGrids = ( equalGrids && *myTargetInfo->Grid() == *prevHInfo->Grid() );
string deviceType = "CPU";
assert(targetGrid->Size() == myTargetInfo->Data()->Size());
myTargetInfo->ResetLocation();
targetGrid->Reset();
prevPGrid->Reset();
prevTGrid->Reset();
if (!firstLevel)
prevHGrid->Reset();
while ( myTargetInfo->NextLocation() &&
targetGrid->Next() &&
prevTGrid->Next() &&
prevPGrid->Next() )
{
count++;
double T = kFloatMissing;
double P = kFloatMissing;
double prevP = kFloatMissing;
double prevT = kFloatMissing;
double prevH = kFloatMissing;
InterpolateToPoint(targetGrid, TGrid, equalGrids, T);
InterpolateToPoint(targetGrid, PGrid, equalGrids, P);
InterpolateToPoint(targetGrid, prevPGrid, equalGrids, prevP);
InterpolateToPoint(targetGrid, prevTGrid, equalGrids, prevT);
if (!firstLevel)
{
prevHGrid->Next();
InterpolateToPoint(targetGrid, prevHGrid, equalGrids, prevH);
if (prevH == kFloatMissing )
{
missingCount++;
myTargetInfo->Value(kFloatMissing);
continue;
}
}
if (prevT == kFloatMissing || prevP == kFloatMissing || T == kFloatMissing || P == kFloatMissing )
{
missingCount++;
myTargetInfo->Value(kFloatMissing);
continue;
}
if (firstLevel)
{
prevP /= 100.f;
}
double Tave = ( T + prevT ) / 2;
double deltaZ = (287 / 9.81) * Tave * log(prevP / P);
double totalHeight(0);
if (firstLevel)
{
totalHeight = deltaZ;
}
else
{
totalHeight = prevH + deltaZ;
}
if (!myTargetInfo->Value(totalHeight))
{
throw runtime_error(ClassName() + ": Failed to set value to matrix");
}
}
if (!itsFastMode)
{
firstLevel = false;
}
/*
* Newbase normalizes scanning mode to bottom left -- if that's not what
* the target scanning mode is, we have to swap the data back.
*/
SwapTo(myTargetInfo, kBottomLeft);
if (itsConfiguration->StatisticsEnabled())
{
processTimer->Stop();
itsConfiguration->Statistics()->AddToProcessingTime(processTimer->GetTime());
#ifdef DEBUG
itsLogger->Debug("Calculation took " + boost::lexical_cast<string> (processTimer->GetTime()) + " microseconds on " + deviceType);
#endif
itsConfiguration->Statistics()->AddToMissingCount(missingCount);
itsConfiguration->Statistics()->AddToValueCount(count);
}
/*
* Now we are done for this level
*
* Clone info-instance to writer since it might change our descriptor places
* */
myThreadedLogger->Info("Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count));
if (itsConfiguration->FileWriteOption() != kSingleFile)
{
WriteToFile(myTargetInfo);
}
}
}
shared_ptr<himan::info> hybrid_height::FetchPrevious(const forecast_time& wantedTime, const level& wantedLevel, const param& wantedParam)
{
shared_ptr<fetcher> f = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher"));
try
{
return f->Fetch(itsConfiguration,
wantedTime,
wantedLevel,
wantedParam);
}
catch (HPExceptionType e)
{
throw e;
}
}
<commit_msg>set thread count correctly to statistics<commit_after>/**
* @file hybrid_height.cpp
*
* @date Apr 5, 2013
* @author peramaki
*/
#include "hybrid_height.h"
#include "plugin_factory.h"
#include "logger_factory.h"
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <math.h>
#define HIMAN_AUXILIARY_INCLUDE
#include "fetcher.h"
#include "neons.h"
#undef HIMAN_AUXILIARY_INCLUDE
using namespace std;
using namespace himan::plugin;
const string itsName("hybrid_height");
hybrid_height::hybrid_height() : itsFastMode(false)
{
itsClearTextFormula = "HEIGHT = prevH + (287/9.81) * (T+prevT)/2 * log(prevP / P)";
itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog(itsName));
}
void hybrid_height::Process(std::shared_ptr<const plugin_configuration> conf)
{
Init(conf);
/*
* Set target parameter to HL-M
* - name HL-M
* - univ_id 3
*
*
* We need to specify grib and querydata parameter information
* since we don't know which one will be the output format.
*
*/
vector<param> theParams;
param theRequestedParam("HL-M", 3);
// GRIB 2
theRequestedParam.GribDiscipline(0);
theRequestedParam.GribCategory(3);
theRequestedParam.GribParameter(6);
// GRIB 1
theParams.push_back(theRequestedParam);
SetParams(theParams);
/*
* For hybrid height we must go through the levels backwards.
*/
itsInfo->LevelOrder(kBottomToTop);
shared_ptr<neons> theNeons = dynamic_pointer_cast <neons> (plugin_factory::Instance()->Plugin("neons"));
itsBottomLevel = boost::lexical_cast<int> (theNeons->ProducerMetaData(230, "last hybrid level number"));
if (!itsConfiguration->Exists("fast_mode") && itsConfiguration->GetValue("fast_mode") == "true")
{
itsFastMode = true;
}
else
{
// When doing exact calculation we must do them sequentially starting from
// surface closest to ground because every surface's value is depended
// on the surface below it. Therefore we cannot parallelize the calculation.
itsThreadCount = 1;
if (itsConfiguration->StatisticsEnabled())
{
itsConfiguration->Statistics()->UsedThreadCount(itsThreadCount);
}
}
Start();
}
/*
* Calculate()
*
* This function does the actual calculation.
*/
void hybrid_height::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)
{
shared_ptr<fetcher> theFetcher = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher"));
param GPParam("P-PA");
param PParam("P-HPA");
param TParam("T-K");
level H2(himan::kHeight, 2, "HEIGHT");
level H0(himan::kHeight, 0, "HEIGHT");
unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog(itsName + "Thread #" + boost::lexical_cast<string> (threadIndex)));
ResetNonLeadingDimension(myTargetInfo);
myTargetInfo->FirstParam();
/*
pitääkö tunnistaa tuottaja?
*/
level prevLevel;
while (AdjustNonLeadingDimension(myTargetInfo))
{
myThreadedLogger->Debug("Calculating time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H") +
" level " + boost::lexical_cast<string> (myTargetInfo->Level().Value()));
bool firstLevel(false);
if (itsFastMode)
{
firstLevel = true;
}
//only works with hirlam for now
//itsLogger->Debug("level: "
if ( myTargetInfo->Level().Value() == itsBottomLevel )
{
firstLevel = true;
}
else
{
prevLevel = level(myTargetInfo->Level());
prevLevel.Value(myTargetInfo->Level().Value() + 1);
prevLevel.Index(prevLevel.Index() + 1);
}
shared_ptr<info> PInfo;
shared_ptr<info> TInfo;
shared_ptr<info> prevPInfo;
shared_ptr<info> prevTInfo;
shared_ptr<info> prevHInfo;
try
{
forecast_time& fTime = myTargetInfo->Time();
if (!firstLevel)
{
prevTInfo = FetchPrevious(fTime, prevLevel, param("T-K"));
prevPInfo = FetchPrevious(fTime, prevLevel, param("P-HPA"));
prevHInfo = FetchPrevious(fTime, prevLevel, param("HL-M"));
}
else
{
prevPInfo = FetchPrevious(fTime, H0, param("P-PA"));
prevTInfo = FetchPrevious(fTime, H2, param("T-K"));
}
//prevLevel = myTargetInfo->Level();
PInfo = theFetcher->Fetch(itsConfiguration,
myTargetInfo->Time(),
myTargetInfo->Level(),
PParam);
TInfo = theFetcher->Fetch(itsConfiguration,
myTargetInfo->Time(),
myTargetInfo->Level(),
TParam);
}
catch (HPExceptionType e)
{
switch (e)
{
case kFileDataNotFound:
itsLogger->Warning("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value()));
myTargetInfo->Data()->Fill(kFloatMissing);
if (itsConfiguration->StatisticsEnabled())
{
itsConfiguration->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size());
itsConfiguration->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size());
}
continue;
break;
default:
throw runtime_error(ClassName() + ": Unable to proceed");
break;
}
}
unique_ptr<timer> processTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer());
if (itsConfiguration->StatisticsEnabled())
{
processTimer->Start();
}
assert(PInfo->Grid()->AB() == TInfo->Grid()->AB());
SetAB(myTargetInfo, TInfo);
size_t missingCount = 0;
size_t count = 0;
shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> PGrid(PInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> prevPGrid(prevPInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> TGrid(TInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> prevTGrid(prevTInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> prevHGrid;
if (!firstLevel )
prevHGrid = shared_ptr<NFmiGrid>(prevHInfo->Grid()->ToNewbaseGrid());
bool equalGrids = ( *myTargetInfo->Grid() == *prevTInfo->Grid() && *myTargetInfo->Grid() == *prevPInfo->Grid() && *myTargetInfo->Grid() == *PInfo->Grid() && *myTargetInfo->Grid() == *TInfo->Grid() ); //&& *myTargetInfo->Grid() == *T2mInfo->Grid() && *myTargetInfo->Grid() == *P0mInfo->Grid() );
if (!firstLevel)
equalGrids = ( equalGrids && *myTargetInfo->Grid() == *prevHInfo->Grid() );
string deviceType = "CPU";
assert(targetGrid->Size() == myTargetInfo->Data()->Size());
myTargetInfo->ResetLocation();
targetGrid->Reset();
prevPGrid->Reset();
prevTGrid->Reset();
if (!firstLevel)
prevHGrid->Reset();
while ( myTargetInfo->NextLocation() &&
targetGrid->Next() &&
prevTGrid->Next() &&
prevPGrid->Next() )
{
count++;
double T = kFloatMissing;
double P = kFloatMissing;
double prevP = kFloatMissing;
double prevT = kFloatMissing;
double prevH = kFloatMissing;
InterpolateToPoint(targetGrid, TGrid, equalGrids, T);
InterpolateToPoint(targetGrid, PGrid, equalGrids, P);
InterpolateToPoint(targetGrid, prevPGrid, equalGrids, prevP);
InterpolateToPoint(targetGrid, prevTGrid, equalGrids, prevT);
if (!firstLevel)
{
prevHGrid->Next();
InterpolateToPoint(targetGrid, prevHGrid, equalGrids, prevH);
if (prevH == kFloatMissing )
{
missingCount++;
myTargetInfo->Value(kFloatMissing);
continue;
}
}
if (prevT == kFloatMissing || prevP == kFloatMissing || T == kFloatMissing || P == kFloatMissing )
{
missingCount++;
myTargetInfo->Value(kFloatMissing);
continue;
}
if (firstLevel)
{
prevP /= 100.f;
}
double Tave = ( T + prevT ) / 2;
double deltaZ = (287 / 9.81) * Tave * log(prevP / P);
double totalHeight(0);
if (firstLevel)
{
totalHeight = deltaZ;
}
else
{
totalHeight = prevH + deltaZ;
}
if (!myTargetInfo->Value(totalHeight))
{
throw runtime_error(ClassName() + ": Failed to set value to matrix");
}
}
if (!itsFastMode)
{
firstLevel = false;
}
/*
* Newbase normalizes scanning mode to bottom left -- if that's not what
* the target scanning mode is, we have to swap the data back.
*/
SwapTo(myTargetInfo, kBottomLeft);
if (itsConfiguration->StatisticsEnabled())
{
processTimer->Stop();
itsConfiguration->Statistics()->AddToProcessingTime(processTimer->GetTime());
#ifdef DEBUG
itsLogger->Debug("Calculation took " + boost::lexical_cast<string> (processTimer->GetTime()) + " microseconds on " + deviceType);
#endif
itsConfiguration->Statistics()->AddToMissingCount(missingCount);
itsConfiguration->Statistics()->AddToValueCount(count);
}
/*
* Now we are done for this level
*
* Clone info-instance to writer since it might change our descriptor places
* */
myThreadedLogger->Info("Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count));
if (itsConfiguration->FileWriteOption() != kSingleFile)
{
WriteToFile(myTargetInfo);
}
}
}
shared_ptr<himan::info> hybrid_height::FetchPrevious(const forecast_time& wantedTime, const level& wantedLevel, const param& wantedParam)
{
shared_ptr<fetcher> f = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher"));
try
{
return f->Fetch(itsConfiguration,
wantedTime,
wantedLevel,
wantedParam);
}
catch (HPExceptionType e)
{
throw e;
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "createandroidmanifestwizard.h"
#include <projectexplorer/target.h>
#include <qmakeprojectmanager/qmakeproject.h>
#include <qmakeprojectmanager/qmakenodes.h>
#include <proparser/prowriter.h>
#include <QComboBox>
#include <QFormLayout>
#include <QLabel>
#include <QMessageBox>
#include <QVBoxLayout>
#include <qtsupport/qtkitinformation.h>
#include <coreplugin/editormanager/editormanager.h>
using namespace Android;
using namespace Android::Internal;
using QmakeProjectManager::QmakeProject;
using QmakeProjectManager::QmakeProFileNode;
//
// NoApplicationProFilePage
//
NoApplicationProFilePage::NoApplicationProFilePage(CreateAndroidManifestWizard *wizard)
: m_wizard(wizard)
{
QVBoxLayout *layout = new QVBoxLayout(this);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(tr("No application .pro file found in this project."));
layout->addWidget(label);
setTitle(tr("No Application .pro File"));
}
//
// ChooseProFilePage
//
ChooseProFilePage::ChooseProFilePage(CreateAndroidManifestWizard *wizard, const QList<QmakeProFileNode *> &nodes)
: m_wizard(wizard)
{
QFormLayout *fl = new QFormLayout(this);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(tr("Select the .pro file for which you want to create an AndroidManifest.xml file."));
fl->addRow(label);
m_comboBox = new QComboBox(this);
foreach (QmakeProFileNode *node, nodes)
m_comboBox->addItem(node->displayName(), QVariant::fromValue(static_cast<void *>(node))); // TODO something more?
connect(m_comboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(nodeSelected(int)));
fl->addRow(tr(".pro file:"), m_comboBox);
setTitle(tr("Select a .pro File"));
}
void ChooseProFilePage::nodeSelected(int index)
{
Q_UNUSED(index)
m_wizard->setNode(static_cast<QmakeProFileNode *>(m_comboBox->itemData(m_comboBox->currentIndex()).value<void *>()));
}
//
// ChooseDirectoryPage
//
ChooseDirectoryPage::ChooseDirectoryPage(CreateAndroidManifestWizard *wizard)
: m_wizard(wizard), m_androidPackageSourceDir(0)
{
QString androidPackageDir = m_wizard->node()->singleVariableValue(QmakeProjectManager::AndroidPackageSourceDir);
QFormLayout *fl = new QFormLayout(this);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
fl->addRow(label);
m_androidPackageSourceDir = new Utils::PathChooser(this);
m_androidPackageSourceDir->setExpectedKind(Utils::PathChooser::Directory);
fl->addRow(tr("Android package source directory:"), m_androidPackageSourceDir);
if (androidPackageDir.isEmpty()) {
label->setText(tr("Select the Android package source directory. "
"The files in the Android package source directory are copied to the build directory's "
"Android directory and the default files are overwritten."));
m_androidPackageSourceDir->setPath(QFileInfo(m_wizard->node()->path()).absolutePath().append(QLatin1String("/android")));
} else {
label->setText(tr("The Android manifest file will be created in the ANDROID_PACKAGE_SOURCE_DIR set in the .pro file."));
m_androidPackageSourceDir->setPath(androidPackageDir);
m_androidPackageSourceDir->setReadOnly(true);
}
m_wizard->setDirectory(m_androidPackageSourceDir->path());
connect(m_androidPackageSourceDir, SIGNAL(pathChanged(QString)),
m_wizard, SLOT(setDirectory(QString)));
}
//
// CreateAndroidManifestWizard
//
CreateAndroidManifestWizard::CreateAndroidManifestWizard(ProjectExplorer::Target *target)
: m_target(target), m_node(0)
{
setWindowTitle(tr("Create Android Manifest Wizard"));
QmakeProject *project = static_cast<QmakeProject *>(target->project());
QList<QmakeProFileNode *> nodes = project->applicationProFiles();
if (nodes.isEmpty()) {
// oh uhm can't create anything
addPage(new NoApplicationProFilePage(this));
} else if (nodes.size() == 1) {
setNode(nodes.first());
addPage(new ChooseDirectoryPage(this));
} else {
addPage(new ChooseProFilePage(this, nodes));
addPage(new ChooseDirectoryPage(this));
}
}
QmakeProjectManager::QmakeProFileNode *CreateAndroidManifestWizard::node() const
{
return m_node;
}
void CreateAndroidManifestWizard::setNode(QmakeProjectManager::QmakeProFileNode *node)
{
m_node = node;
}
void CreateAndroidManifestWizard::setDirectory(const QString &directory)
{
m_directory = directory;
}
QString CreateAndroidManifestWizard::sourceFileName() const
{
QString result;
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(m_target->kit());
if (!version)
return result;
Utils::FileName srcPath
= Utils::FileName::fromString(version->qmakeProperty("QT_INSTALL_PREFIX"))
.appendPath(QLatin1String("src/android/java"));
srcPath.appendPath(QLatin1String("AndroidManifest.xml"));
return srcPath.toString();
}
void CreateAndroidManifestWizard::createAndroidManifestFile()
{
if (m_directory.isEmpty())
return;
QDir dir;
if (!QFileInfo(m_directory).exists())
dir.mkpath(m_directory);
QString fileName = m_directory + QLatin1String("/AndroidManifest.xml");
if (QFileInfo(fileName).exists()) {
if (QMessageBox::question(this, tr("Overwrite AndroidManifest.xml"),
tr("Overwrite existing AndroidManifest.xml?"),
QMessageBox::Yes, QMessageBox::No)
== QMessageBox::Yes) {
if (!QFile(m_directory + QLatin1String("/AndroidManifest.xml")).remove()) {
QMessageBox::warning(this, tr("File Removal Error"),
tr("Could not remove file %1.").arg(fileName));
return;
}
} else {
return;
}
}
if (!QFile::copy(sourceFileName(), fileName)) {
QMessageBox::warning(this, tr("File Creation Error"),
tr("Could not create file %1.").arg(fileName));
return;
}
if (m_node->singleVariableValue(QmakeProjectManager::AndroidPackageSourceDir).isEmpty()) {
// and now time for some magic
QString dir = QFileInfo(fileName).absolutePath();
QString value = QLatin1String("$$PWD/")
+ QDir(m_target->project()->projectDirectory()).relativeFilePath(dir);
bool result =
m_node->setProVariable(QLatin1String("ANDROID_PACKAGE_SOURCE_DIR"), value);
QStringList unChanged;
m_node->addFiles(QStringList(fileName), &unChanged);
if (result == false
|| !unChanged.isEmpty()) {
QMessageBox::warning(this, tr("Project File not Updated"),
tr("Could not update the .pro file %1.").arg(m_node->path()));
}
}
Core::EditorManager::openEditor(fileName);
}
void CreateAndroidManifestWizard::accept()
{
createAndroidManifestFile();
Utils::Wizard::accept();
}
<commit_msg>Android: Fix crash in CreateAndroidManifestWizard<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "createandroidmanifestwizard.h"
#include <projectexplorer/target.h>
#include <qmakeprojectmanager/qmakeproject.h>
#include <qmakeprojectmanager/qmakenodes.h>
#include <proparser/prowriter.h>
#include <QComboBox>
#include <QFormLayout>
#include <QLabel>
#include <QMessageBox>
#include <QVBoxLayout>
#include <qtsupport/qtkitinformation.h>
#include <coreplugin/editormanager/editormanager.h>
using namespace Android;
using namespace Android::Internal;
using QmakeProjectManager::QmakeProject;
using QmakeProjectManager::QmakeProFileNode;
//
// NoApplicationProFilePage
//
NoApplicationProFilePage::NoApplicationProFilePage(CreateAndroidManifestWizard *wizard)
: m_wizard(wizard)
{
QVBoxLayout *layout = new QVBoxLayout(this);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(tr("No application .pro file found in this project."));
layout->addWidget(label);
setTitle(tr("No Application .pro File"));
}
//
// ChooseProFilePage
//
ChooseProFilePage::ChooseProFilePage(CreateAndroidManifestWizard *wizard, const QList<QmakeProFileNode *> &nodes)
: m_wizard(wizard)
{
QFormLayout *fl = new QFormLayout(this);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(tr("Select the .pro file for which you want to create an AndroidManifest.xml file."));
fl->addRow(label);
m_comboBox = new QComboBox(this);
foreach (QmakeProFileNode *node, nodes)
m_comboBox->addItem(node->displayName(), QVariant::fromValue(static_cast<void *>(node))); // TODO something more?
nodeSelected(0);
connect(m_comboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(nodeSelected(int)));
fl->addRow(tr(".pro file:"), m_comboBox);
setTitle(tr("Select a .pro File"));
}
void ChooseProFilePage::nodeSelected(int index)
{
Q_UNUSED(index)
m_wizard->setNode(static_cast<QmakeProFileNode *>(m_comboBox->itemData(m_comboBox->currentIndex()).value<void *>()));
}
//
// ChooseDirectoryPage
//
ChooseDirectoryPage::ChooseDirectoryPage(CreateAndroidManifestWizard *wizard)
: m_wizard(wizard), m_androidPackageSourceDir(0)
{
QString androidPackageDir = m_wizard->node()->singleVariableValue(QmakeProjectManager::AndroidPackageSourceDir);
QFormLayout *fl = new QFormLayout(this);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
fl->addRow(label);
m_androidPackageSourceDir = new Utils::PathChooser(this);
m_androidPackageSourceDir->setExpectedKind(Utils::PathChooser::Directory);
fl->addRow(tr("Android package source directory:"), m_androidPackageSourceDir);
if (androidPackageDir.isEmpty()) {
label->setText(tr("Select the Android package source directory. "
"The files in the Android package source directory are copied to the build directory's "
"Android directory and the default files are overwritten."));
m_androidPackageSourceDir->setPath(QFileInfo(m_wizard->node()->path()).absolutePath().append(QLatin1String("/android")));
} else {
label->setText(tr("The Android manifest file will be created in the ANDROID_PACKAGE_SOURCE_DIR set in the .pro file."));
m_androidPackageSourceDir->setPath(androidPackageDir);
m_androidPackageSourceDir->setReadOnly(true);
}
m_wizard->setDirectory(m_androidPackageSourceDir->path());
connect(m_androidPackageSourceDir, SIGNAL(pathChanged(QString)),
m_wizard, SLOT(setDirectory(QString)));
}
//
// CreateAndroidManifestWizard
//
CreateAndroidManifestWizard::CreateAndroidManifestWizard(ProjectExplorer::Target *target)
: m_target(target), m_node(0)
{
setWindowTitle(tr("Create Android Manifest Wizard"));
QmakeProject *project = static_cast<QmakeProject *>(target->project());
QList<QmakeProFileNode *> nodes = project->applicationProFiles();
if (nodes.isEmpty()) {
// oh uhm can't create anything
addPage(new NoApplicationProFilePage(this));
} else if (nodes.size() == 1) {
setNode(nodes.first());
addPage(new ChooseDirectoryPage(this));
} else {
addPage(new ChooseProFilePage(this, nodes));
addPage(new ChooseDirectoryPage(this));
}
}
QmakeProjectManager::QmakeProFileNode *CreateAndroidManifestWizard::node() const
{
return m_node;
}
void CreateAndroidManifestWizard::setNode(QmakeProjectManager::QmakeProFileNode *node)
{
m_node = node;
}
void CreateAndroidManifestWizard::setDirectory(const QString &directory)
{
m_directory = directory;
}
QString CreateAndroidManifestWizard::sourceFileName() const
{
QString result;
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(m_target->kit());
if (!version)
return result;
Utils::FileName srcPath
= Utils::FileName::fromString(version->qmakeProperty("QT_INSTALL_PREFIX"))
.appendPath(QLatin1String("src/android/java"));
srcPath.appendPath(QLatin1String("AndroidManifest.xml"));
return srcPath.toString();
}
void CreateAndroidManifestWizard::createAndroidManifestFile()
{
if (m_directory.isEmpty())
return;
QDir dir;
if (!QFileInfo(m_directory).exists())
dir.mkpath(m_directory);
QString fileName = m_directory + QLatin1String("/AndroidManifest.xml");
if (QFileInfo(fileName).exists()) {
if (QMessageBox::question(this, tr("Overwrite AndroidManifest.xml"),
tr("Overwrite existing AndroidManifest.xml?"),
QMessageBox::Yes, QMessageBox::No)
== QMessageBox::Yes) {
if (!QFile(m_directory + QLatin1String("/AndroidManifest.xml")).remove()) {
QMessageBox::warning(this, tr("File Removal Error"),
tr("Could not remove file %1.").arg(fileName));
return;
}
} else {
return;
}
}
if (!QFile::copy(sourceFileName(), fileName)) {
QMessageBox::warning(this, tr("File Creation Error"),
tr("Could not create file %1.").arg(fileName));
return;
}
if (m_node->singleVariableValue(QmakeProjectManager::AndroidPackageSourceDir).isEmpty()) {
// and now time for some magic
QString dir = QFileInfo(fileName).absolutePath();
QString value = QLatin1String("$$PWD/")
+ QDir(m_target->project()->projectDirectory()).relativeFilePath(dir);
bool result =
m_node->setProVariable(QLatin1String("ANDROID_PACKAGE_SOURCE_DIR"), value);
QStringList unChanged;
m_node->addFiles(QStringList(fileName), &unChanged);
if (result == false
|| !unChanged.isEmpty()) {
QMessageBox::warning(this, tr("Project File not Updated"),
tr("Could not update the .pro file %1.").arg(m_node->path()));
}
}
Core::EditorManager::openEditor(fileName);
}
void CreateAndroidManifestWizard::accept()
{
createAndroidManifestFile();
Utils::Wizard::accept();
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qt4projectmanager.h"
#include "qt4projectmanagerconstants.h"
#include "qt4projectmanagerplugin.h"
#include "qt4nodes.h"
#include "qt4project.h"
#include "qt4target.h"
#include "profilereader.h"
#include "qmakestep.h"
#include "qt4buildconfiguration.h"
#include <coreplugin/icore.h>
#include <coreplugin/basefilewizard.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/session.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/qtcassert.h>
#include <designer/formwindoweditor.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QVariant>
#include <QtGui/QFileDialog>
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
using ProjectExplorer::BuildStep;
using ProjectExplorer::FileType;
using ProjectExplorer::HeaderType;
using ProjectExplorer::SourceType;
using ProjectExplorer::FormType;
using ProjectExplorer::ResourceType;
using ProjectExplorer::UnknownFileType;
// Known file types of a Qt 4 project
static const char* qt4FileTypes[] = {
"CppHeaderFiles",
"CppSourceFiles",
"Qt4FormFiles",
"Qt4ResourceFiles"
};
Qt4Manager::Qt4Manager(Qt4ProjectManagerPlugin *plugin)
: m_plugin(plugin),
m_contextProject(0),
m_lastEditor(0),
m_dirty(false)
{
}
Qt4Manager::~Qt4Manager()
{
}
void Qt4Manager::registerProject(Qt4Project *project)
{
m_projects.append(project);
}
void Qt4Manager::unregisterProject(Qt4Project *project)
{
m_projects.removeOne(project);
}
void Qt4Manager::notifyChanged(const QString &name)
{
foreach (Qt4Project *pro, m_projects)
pro->notifyChanged(name);
}
void Qt4Manager::init()
{
connect(Core::EditorManager::instance(), SIGNAL(editorAboutToClose(Core::IEditor*)),
this, SLOT(editorAboutToClose(Core::IEditor*)));
connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(editorChanged(Core::IEditor*)));
}
void Qt4Manager::editorChanged(Core::IEditor *editor)
{
// Handle old editor
Designer::FormWindowEditor *lastFormEditor = qobject_cast<Designer::FormWindowEditor *>(m_lastEditor);
if (lastFormEditor) {
disconnect(lastFormEditor, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
if (m_dirty) {
const QString contents = lastFormEditor->contents();
foreach(Qt4Project *project, m_projects)
project->rootProjectNode()->updateCodeModelSupportFromEditor(lastFormEditor->file()->fileName(), contents);
m_dirty = false;
}
}
m_lastEditor = editor;
// Handle new editor
if (Designer::FormWindowEditor *fw = qobject_cast<Designer::FormWindowEditor *>(editor))
connect(fw, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
}
void Qt4Manager::editorAboutToClose(Core::IEditor *editor)
{
if (m_lastEditor == editor) {
// Oh no our editor is going to be closed
// get the content first
Designer::FormWindowEditor *lastEditor = qobject_cast<Designer::FormWindowEditor *>(m_lastEditor);
if (lastEditor) {
disconnect(lastEditor, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
if (m_dirty) {
const QString contents = lastEditor->contents();
foreach(Qt4Project *project, m_projects)
project->rootProjectNode()->updateCodeModelSupportFromEditor(lastEditor->file()->fileName(), contents);
m_dirty = false;
}
}
m_lastEditor = 0;
}
}
void Qt4Manager::uiEditorContentsChanged()
{
// cast sender, get filename
if (m_dirty)
return;
Designer::FormWindowEditor *fw = qobject_cast<Designer::FormWindowEditor *>(sender());
if (!fw)
return;
m_dirty = true;
}
Core::Context Qt4Manager::projectContext() const
{
return m_plugin->projectContext();
}
Core::Context Qt4Manager::projectLanguage() const
{
return Core::Context(ProjectExplorer::Constants::LANG_CXX);
}
QString Qt4Manager::mimeType() const
{
return QLatin1String(Qt4ProjectManager::Constants::PROFILE_MIMETYPE);
}
ProjectExplorer::Project *Qt4Manager::openProject(const QString &fileName)
{
Core::MessageManager *messageManager = Core::ICore::instance()->messageManager();
// TODO Make all file paths relative & remove this hack
// We convert the path to an absolute one here because qt4project.cpp
// && profileevaluator use absolute/canonical file paths all over the place
// Correct fix would be to remove these calls ...
QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();
if (canonicalFilePath.isEmpty()) {
messageManager->printToOutputPane(tr("Failed opening project '%1': Project file does not exist").arg(QDir::toNativeSeparators(canonicalFilePath)));
return 0;
}
foreach (ProjectExplorer::Project *pi, projectExplorer()->session()->projects()) {
if (canonicalFilePath == pi->file()->fileName()) {
messageManager->printToOutputPane(tr("Failed opening project '%1': Project already open").arg(QDir::toNativeSeparators(canonicalFilePath)));
return 0;
}
}
Qt4Project *pro = new Qt4Project(this, canonicalFilePath);
return pro;
}
ProjectExplorer::ProjectExplorerPlugin *Qt4Manager::projectExplorer() const
{
return ProjectExplorer::ProjectExplorerPlugin::instance();
}
ProjectExplorer::Node *Qt4Manager::contextNode() const
{
return m_contextNode;
}
void Qt4Manager::setContextNode(ProjectExplorer::Node *node)
{
m_contextNode = node;
}
void Qt4Manager::setContextProject(ProjectExplorer::Project *project)
{
m_contextProject = project;
}
ProjectExplorer::Project *Qt4Manager::contextProject() const
{
return m_contextProject;
}
void Qt4Manager::runQMake()
{
runQMake(projectExplorer()->currentProject(), 0);
}
void Qt4Manager::runQMakeContextMenu()
{
runQMake(m_contextProject, m_contextNode);
}
void Qt4Manager::runQMake(ProjectExplorer::Project *p, ProjectExplorer::Node *node)
{
Qt4Project *qt4pro = qobject_cast<Qt4Project *>(p);
QTC_ASSERT(qt4pro, return);
if (!qt4pro->activeTarget() ||
!qt4pro->activeTarget()->activeBuildConfiguration())
return;
Qt4BuildConfiguration *bc = qt4pro->activeTarget()->activeBuildConfiguration();
QMakeStep *qs = bc->qmakeStep();
if (!qs)
return;
//found qmakeStep, now use it
qs->setForced(true);
if (node != 0 && node != qt4pro->rootProjectNode())
if (Qt4ProFileNode *profile = qobject_cast<Qt4ProFileNode *>(node))
bc->setSubNodeBuild(profile);
projectExplorer()->buildManager()->appendStep(qs);
bc->setSubNodeBuild(0);
}
void Qt4Manager::buildSubDirContextMenu()
{
handleSubDirContexMenu(BUILD);
}
void Qt4Manager::cleanSubDirContextMenu()
{
handleSubDirContexMenu(CLEAN);
}
void Qt4Manager::rebuildSubDirContextMenu()
{
handleSubDirContexMenu(REBUILD);
}
void Qt4Manager::handleSubDirContexMenu(Qt4Manager::Action action)
{
Qt4Project *qt4pro = qobject_cast<Qt4Project *>(m_contextProject);
QTC_ASSERT(qt4pro, return);
if (!qt4pro->activeTarget() ||
!qt4pro->activeTarget()->activeBuildConfiguration())
return;
Qt4BuildConfiguration *bc = qt4pro->activeTarget()->activeBuildConfiguration();
if (m_contextNode != 0 && m_contextNode != qt4pro->rootProjectNode())
if (Qt4ProFileNode *profile = qobject_cast<Qt4ProFileNode *>(m_contextNode))
bc->setSubNodeBuild(profile);
if (projectExplorer()->saveModifiedFiles()) {
if (action == BUILD)
projectExplorer()->buildManager()->buildProject(bc);
else if (action == CLEAN)
projectExplorer()->buildManager()->cleanProject(bc);
else if (action == REBUILD) {
projectExplorer()->buildManager()->cleanProject(bc);
projectExplorer()->buildManager()->buildProject(bc);
}
}
bc->setSubNodeBuild(0);
}
QString Qt4Manager::fileTypeId(ProjectExplorer::FileType type)
{
switch (type) {
case HeaderType:
return QLatin1String(qt4FileTypes[0]);
case SourceType:
return QLatin1String(qt4FileTypes[1]);
case FormType:
return QLatin1String(qt4FileTypes[2]);
case ResourceType:
return QLatin1String(qt4FileTypes[3]);
case UnknownFileType:
default:
break;
}
return QString();
}
<commit_msg>Ask to save all editors before running qmake<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qt4projectmanager.h"
#include "qt4projectmanagerconstants.h"
#include "qt4projectmanagerplugin.h"
#include "qt4nodes.h"
#include "qt4project.h"
#include "qt4target.h"
#include "profilereader.h"
#include "qmakestep.h"
#include "qt4buildconfiguration.h"
#include <coreplugin/icore.h>
#include <coreplugin/basefilewizard.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/session.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/qtcassert.h>
#include <designer/formwindoweditor.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QVariant>
#include <QtGui/QFileDialog>
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
using ProjectExplorer::BuildStep;
using ProjectExplorer::FileType;
using ProjectExplorer::HeaderType;
using ProjectExplorer::SourceType;
using ProjectExplorer::FormType;
using ProjectExplorer::ResourceType;
using ProjectExplorer::UnknownFileType;
// Known file types of a Qt 4 project
static const char* qt4FileTypes[] = {
"CppHeaderFiles",
"CppSourceFiles",
"Qt4FormFiles",
"Qt4ResourceFiles"
};
Qt4Manager::Qt4Manager(Qt4ProjectManagerPlugin *plugin)
: m_plugin(plugin),
m_contextProject(0),
m_lastEditor(0),
m_dirty(false)
{
}
Qt4Manager::~Qt4Manager()
{
}
void Qt4Manager::registerProject(Qt4Project *project)
{
m_projects.append(project);
}
void Qt4Manager::unregisterProject(Qt4Project *project)
{
m_projects.removeOne(project);
}
void Qt4Manager::notifyChanged(const QString &name)
{
foreach (Qt4Project *pro, m_projects)
pro->notifyChanged(name);
}
void Qt4Manager::init()
{
connect(Core::EditorManager::instance(), SIGNAL(editorAboutToClose(Core::IEditor*)),
this, SLOT(editorAboutToClose(Core::IEditor*)));
connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(editorChanged(Core::IEditor*)));
}
void Qt4Manager::editorChanged(Core::IEditor *editor)
{
// Handle old editor
Designer::FormWindowEditor *lastFormEditor = qobject_cast<Designer::FormWindowEditor *>(m_lastEditor);
if (lastFormEditor) {
disconnect(lastFormEditor, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
if (m_dirty) {
const QString contents = lastFormEditor->contents();
foreach(Qt4Project *project, m_projects)
project->rootProjectNode()->updateCodeModelSupportFromEditor(lastFormEditor->file()->fileName(), contents);
m_dirty = false;
}
}
m_lastEditor = editor;
// Handle new editor
if (Designer::FormWindowEditor *fw = qobject_cast<Designer::FormWindowEditor *>(editor))
connect(fw, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
}
void Qt4Manager::editorAboutToClose(Core::IEditor *editor)
{
if (m_lastEditor == editor) {
// Oh no our editor is going to be closed
// get the content first
Designer::FormWindowEditor *lastEditor = qobject_cast<Designer::FormWindowEditor *>(m_lastEditor);
if (lastEditor) {
disconnect(lastEditor, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
if (m_dirty) {
const QString contents = lastEditor->contents();
foreach(Qt4Project *project, m_projects)
project->rootProjectNode()->updateCodeModelSupportFromEditor(lastEditor->file()->fileName(), contents);
m_dirty = false;
}
}
m_lastEditor = 0;
}
}
void Qt4Manager::uiEditorContentsChanged()
{
// cast sender, get filename
if (m_dirty)
return;
Designer::FormWindowEditor *fw = qobject_cast<Designer::FormWindowEditor *>(sender());
if (!fw)
return;
m_dirty = true;
}
Core::Context Qt4Manager::projectContext() const
{
return m_plugin->projectContext();
}
Core::Context Qt4Manager::projectLanguage() const
{
return Core::Context(ProjectExplorer::Constants::LANG_CXX);
}
QString Qt4Manager::mimeType() const
{
return QLatin1String(Qt4ProjectManager::Constants::PROFILE_MIMETYPE);
}
ProjectExplorer::Project *Qt4Manager::openProject(const QString &fileName)
{
Core::MessageManager *messageManager = Core::ICore::instance()->messageManager();
// TODO Make all file paths relative & remove this hack
// We convert the path to an absolute one here because qt4project.cpp
// && profileevaluator use absolute/canonical file paths all over the place
// Correct fix would be to remove these calls ...
QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();
if (canonicalFilePath.isEmpty()) {
messageManager->printToOutputPane(tr("Failed opening project '%1': Project file does not exist").arg(QDir::toNativeSeparators(canonicalFilePath)));
return 0;
}
foreach (ProjectExplorer::Project *pi, projectExplorer()->session()->projects()) {
if (canonicalFilePath == pi->file()->fileName()) {
messageManager->printToOutputPane(tr("Failed opening project '%1': Project already open").arg(QDir::toNativeSeparators(canonicalFilePath)));
return 0;
}
}
Qt4Project *pro = new Qt4Project(this, canonicalFilePath);
return pro;
}
ProjectExplorer::ProjectExplorerPlugin *Qt4Manager::projectExplorer() const
{
return ProjectExplorer::ProjectExplorerPlugin::instance();
}
ProjectExplorer::Node *Qt4Manager::contextNode() const
{
return m_contextNode;
}
void Qt4Manager::setContextNode(ProjectExplorer::Node *node)
{
m_contextNode = node;
}
void Qt4Manager::setContextProject(ProjectExplorer::Project *project)
{
m_contextProject = project;
}
ProjectExplorer::Project *Qt4Manager::contextProject() const
{
return m_contextProject;
}
void Qt4Manager::runQMake()
{
runQMake(projectExplorer()->currentProject(), 0);
}
void Qt4Manager::runQMakeContextMenu()
{
runQMake(m_contextProject, m_contextNode);
}
void Qt4Manager::runQMake(ProjectExplorer::Project *p, ProjectExplorer::Node *node)
{
if (!ProjectExplorer::ProjectExplorerPlugin::instance()->saveModifiedFiles())
return;
Qt4Project *qt4pro = qobject_cast<Qt4Project *>(p);
QTC_ASSERT(qt4pro, return);
if (!qt4pro->activeTarget() ||
!qt4pro->activeTarget()->activeBuildConfiguration())
return;
Qt4BuildConfiguration *bc = qt4pro->activeTarget()->activeBuildConfiguration();
QMakeStep *qs = bc->qmakeStep();
if (!qs)
return;
//found qmakeStep, now use it
qs->setForced(true);
if (node != 0 && node != qt4pro->rootProjectNode())
if (Qt4ProFileNode *profile = qobject_cast<Qt4ProFileNode *>(node))
bc->setSubNodeBuild(profile);
projectExplorer()->buildManager()->appendStep(qs);
bc->setSubNodeBuild(0);
}
void Qt4Manager::buildSubDirContextMenu()
{
handleSubDirContexMenu(BUILD);
}
void Qt4Manager::cleanSubDirContextMenu()
{
handleSubDirContexMenu(CLEAN);
}
void Qt4Manager::rebuildSubDirContextMenu()
{
handleSubDirContexMenu(REBUILD);
}
void Qt4Manager::handleSubDirContexMenu(Qt4Manager::Action action)
{
Qt4Project *qt4pro = qobject_cast<Qt4Project *>(m_contextProject);
QTC_ASSERT(qt4pro, return);
if (!qt4pro->activeTarget() ||
!qt4pro->activeTarget()->activeBuildConfiguration())
return;
Qt4BuildConfiguration *bc = qt4pro->activeTarget()->activeBuildConfiguration();
if (m_contextNode != 0 && m_contextNode != qt4pro->rootProjectNode())
if (Qt4ProFileNode *profile = qobject_cast<Qt4ProFileNode *>(m_contextNode))
bc->setSubNodeBuild(profile);
if (projectExplorer()->saveModifiedFiles()) {
if (action == BUILD)
projectExplorer()->buildManager()->buildProject(bc);
else if (action == CLEAN)
projectExplorer()->buildManager()->cleanProject(bc);
else if (action == REBUILD) {
projectExplorer()->buildManager()->cleanProject(bc);
projectExplorer()->buildManager()->buildProject(bc);
}
}
bc->setSubNodeBuild(0);
}
QString Qt4Manager::fileTypeId(ProjectExplorer::FileType type)
{
switch (type) {
case HeaderType:
return QLatin1String(qt4FileTypes[0]);
case SourceType:
return QLatin1String(qt4FileTypes[1]);
case FormType:
return QLatin1String(qt4FileTypes[2]);
case ResourceType:
return QLatin1String(qt4FileTypes[3]);
case UnknownFileType:
default:
break;
}
return QString();
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/
#include "qt4projectmanager.h"
#include "qt4projectmanagerconstants.h"
#include "qt4projectmanagerplugin.h"
#include "qt4nodes.h"
#include "qt4project.h"
#include "profilereader.h"
#include "qtversionmanager.h"
#include "qmakestep.h"
#include <coreplugin/icore.h>
#include <coreplugin/basefilewizard.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/vcsmanager.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/listutils.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QLinkedList>
#include <QtCore/QVariant>
#include <QtGui/QFileDialog>
#include <QtGui/QMenu>
#include <QtGui/QMessageBox>
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
using ProjectExplorer::BuildStep;
using ProjectExplorer::FileType;
using ProjectExplorer::HeaderType;
using ProjectExplorer::SourceType;
using ProjectExplorer::FormType;
using ProjectExplorer::ResourceType;
using ProjectExplorer::UnknownFileType;
// Known file types of a Qt 4 project
static const char* qt4FileTypes[] = {
"CppHeaderFiles",
"CppSourceFiles",
"Qt4FormFiles",
"Qt4ResourceFiles"
};
Qt4Manager::Qt4Manager(Qt4ProjectManagerPlugin *plugin)
: m_mimeType(QLatin1String(Qt4ProjectManager::Constants::PROFILE_MIMETYPE)),
m_plugin(plugin),
m_projectExplorer(0),
m_contextProject(0),
m_languageID(0)
{
m_languageID = Core::UniqueIDManager::instance()->
uniqueIdentifier(ProjectExplorer::Constants::LANG_CXX);
}
Qt4Manager::~Qt4Manager()
{
}
void Qt4Manager::registerProject(Qt4Project *project)
{
m_projects.append(project);
}
void Qt4Manager::unregisterProject(Qt4Project *project)
{
m_projects.removeOne(project);
}
void Qt4Manager::notifyChanged(const QString &name)
{
foreach (Qt4Project *pro, m_projects)
pro->notifyChanged(name);
}
void Qt4Manager::init()
{
m_projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
}
int Qt4Manager::projectContext() const
{
return m_plugin->projectContext();
}
int Qt4Manager::projectLanguage() const
{
return m_languageID;
}
QString Qt4Manager::mimeType() const
{
return m_mimeType;
}
ProjectExplorer::Project* Qt4Manager::openProject(const QString &fileName)
{
Core::MessageManager *messageManager = Core::ICore::instance()->messageManager();
messageManager->displayStatusBarMessage(tr("Loading project %1 ...").arg(fileName), 50000);
// TODO Make all file paths relative & remove this hack
// We convert the path to an absolute one here because qt4project.cpp
// && profileevaluator use absolute/canonical file paths all over the place
// Correct fix would be to remove these calls ...
QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();
if (canonicalFilePath.isEmpty()) {
messageManager->printToOutputPane(tr("Failed opening project '%1': Project file does not exist").arg(canonicalFilePath));
messageManager->displayStatusBarMessage(tr("Failed opening project"), 5000);
return 0;
}
foreach (ProjectExplorer::Project *pi, projectExplorer()->session()->projects()) {
if (canonicalFilePath == pi->file()->fileName()) {
messageManager->printToOutputPane(tr("Failed opening project '%1': Project already open").arg(canonicalFilePath));
messageManager->displayStatusBarMessage(tr("Failed opening project"), 5000);
return 0;
}
}
messageManager->displayStatusBarMessage(tr("Opening %1 ...").arg(fileName));
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
Qt4Project *pro = new Qt4Project(this, canonicalFilePath);
messageManager->displayStatusBarMessage(tr("Done opening project"), 5000);
return pro;
}
ProjectExplorer::ProjectExplorerPlugin *Qt4Manager::projectExplorer() const
{
return m_projectExplorer;
}
ProjectExplorer::Node *Qt4Manager::contextNode() const
{
return m_contextNode;
}
void Qt4Manager::setContextNode(ProjectExplorer::Node *node)
{
m_contextNode = node;
}
void Qt4Manager::setContextProject(ProjectExplorer::Project *project)
{
m_contextProject = project;
}
ProjectExplorer::Project *Qt4Manager::contextProject() const
{
return m_contextProject;
}
QtVersionManager *Qt4Manager::versionManager() const
{
return m_plugin->versionManager();
}
void Qt4Manager::runQMake()
{
runQMake(m_projectExplorer->currentProject());
}
void Qt4Manager::runQMakeContextMenu()
{
runQMake(m_contextProject);
}
void Qt4Manager::runQMake(ProjectExplorer::Project *p)
{
QMakeStep *qmakeStep = qobject_cast<Qt4Project *>(p)->qmakeStep();
//found qmakeStep, now use it
qmakeStep->setForced(true);
const QString &config = p->activeBuildConfiguration();
m_projectExplorer->buildManager()->appendStep(qmakeStep, config);
}
QString Qt4Manager::fileTypeId(ProjectExplorer::FileType type)
{
switch (type) {
case HeaderType:
return QLatin1String(qt4FileTypes[0]);
case SourceType:
return QLatin1String(qt4FileTypes[1]);
case FormType:
return QLatin1String(qt4FileTypes[2]);
case ResourceType:
return QLatin1String(qt4FileTypes[3]);
case UnknownFileType:
default:
break;
}
return QString();
}
<commit_msg>Don't annoy Windows users with alien dir separators<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/
#include "qt4projectmanager.h"
#include "qt4projectmanagerconstants.h"
#include "qt4projectmanagerplugin.h"
#include "qt4nodes.h"
#include "qt4project.h"
#include "profilereader.h"
#include "qtversionmanager.h"
#include "qmakestep.h"
#include <coreplugin/icore.h>
#include <coreplugin/basefilewizard.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/vcsmanager.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/listutils.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QLinkedList>
#include <QtCore/QVariant>
#include <QtGui/QFileDialog>
#include <QtGui/QMenu>
#include <QtGui/QMessageBox>
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
using ProjectExplorer::BuildStep;
using ProjectExplorer::FileType;
using ProjectExplorer::HeaderType;
using ProjectExplorer::SourceType;
using ProjectExplorer::FormType;
using ProjectExplorer::ResourceType;
using ProjectExplorer::UnknownFileType;
// Known file types of a Qt 4 project
static const char* qt4FileTypes[] = {
"CppHeaderFiles",
"CppSourceFiles",
"Qt4FormFiles",
"Qt4ResourceFiles"
};
Qt4Manager::Qt4Manager(Qt4ProjectManagerPlugin *plugin)
: m_mimeType(QLatin1String(Qt4ProjectManager::Constants::PROFILE_MIMETYPE)),
m_plugin(plugin),
m_projectExplorer(0),
m_contextProject(0),
m_languageID(0)
{
m_languageID = Core::UniqueIDManager::instance()->
uniqueIdentifier(ProjectExplorer::Constants::LANG_CXX);
}
Qt4Manager::~Qt4Manager()
{
}
void Qt4Manager::registerProject(Qt4Project *project)
{
m_projects.append(project);
}
void Qt4Manager::unregisterProject(Qt4Project *project)
{
m_projects.removeOne(project);
}
void Qt4Manager::notifyChanged(const QString &name)
{
foreach (Qt4Project *pro, m_projects)
pro->notifyChanged(name);
}
void Qt4Manager::init()
{
m_projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
}
int Qt4Manager::projectContext() const
{
return m_plugin->projectContext();
}
int Qt4Manager::projectLanguage() const
{
return m_languageID;
}
QString Qt4Manager::mimeType() const
{
return m_mimeType;
}
ProjectExplorer::Project* Qt4Manager::openProject(const QString &fileName)
{
Core::MessageManager *messageManager = Core::ICore::instance()->messageManager();
messageManager->displayStatusBarMessage(tr("Loading project %1 ...").arg(fileName), 50000);
// TODO Make all file paths relative & remove this hack
// We convert the path to an absolute one here because qt4project.cpp
// && profileevaluator use absolute/canonical file paths all over the place
// Correct fix would be to remove these calls ...
QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();
if (canonicalFilePath.isEmpty()) {
messageManager->printToOutputPane(tr("Failed opening project '%1': Project file does not exist").arg(QDir::toNativeSeparators(canonicalFilePath)));
messageManager->displayStatusBarMessage(tr("Failed opening project"), 5000);
return 0;
}
foreach (ProjectExplorer::Project *pi, projectExplorer()->session()->projects()) {
if (canonicalFilePath == pi->file()->fileName()) {
messageManager->printToOutputPane(tr("Failed opening project '%1': Project already open").arg(QDir::toNativeSeparators(canonicalFilePath)));
messageManager->displayStatusBarMessage(tr("Failed opening project"), 5000);
return 0;
}
}
messageManager->displayStatusBarMessage(tr("Opening %1 ...").arg(fileName));
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
Qt4Project *pro = new Qt4Project(this, canonicalFilePath);
messageManager->displayStatusBarMessage(tr("Done opening project"), 5000);
return pro;
}
ProjectExplorer::ProjectExplorerPlugin *Qt4Manager::projectExplorer() const
{
return m_projectExplorer;
}
ProjectExplorer::Node *Qt4Manager::contextNode() const
{
return m_contextNode;
}
void Qt4Manager::setContextNode(ProjectExplorer::Node *node)
{
m_contextNode = node;
}
void Qt4Manager::setContextProject(ProjectExplorer::Project *project)
{
m_contextProject = project;
}
ProjectExplorer::Project *Qt4Manager::contextProject() const
{
return m_contextProject;
}
QtVersionManager *Qt4Manager::versionManager() const
{
return m_plugin->versionManager();
}
void Qt4Manager::runQMake()
{
runQMake(m_projectExplorer->currentProject());
}
void Qt4Manager::runQMakeContextMenu()
{
runQMake(m_contextProject);
}
void Qt4Manager::runQMake(ProjectExplorer::Project *p)
{
QMakeStep *qmakeStep = qobject_cast<Qt4Project *>(p)->qmakeStep();
//found qmakeStep, now use it
qmakeStep->setForced(true);
const QString &config = p->activeBuildConfiguration();
m_projectExplorer->buildManager()->appendStep(qmakeStep, config);
}
QString Qt4Manager::fileTypeId(ProjectExplorer::FileType type)
{
switch (type) {
case HeaderType:
return QLatin1String(qt4FileTypes[0]);
case SourceType:
return QLatin1String(qt4FileTypes[1]);
case FormType:
return QLatin1String(qt4FileTypes[2]);
case ResourceType:
return QLatin1String(qt4FileTypes[3]);
case UnknownFileType:
default:
break;
}
return QString();
}
<|endoftext|>
|
<commit_before>/*
*
* EthereumLikeWallet
*
* Created by El Khalil Bellakrid on 14/07/2018.
*
* The MIT License (MIT)
*
* Copyright (c) 2018 Ledger
*
* 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 "EthereumLikeWallet.h"
#include "EthereumLikeAccount.h"
#include <algorithm>
#include <async/wait.h>
#include <api/ErrorCode.hpp>
#include <api/AccountCallback.hpp>
#include <api/ConfigurationDefaults.hpp>
#include <api/KeychainEngines.hpp>
#include <ethereum/EthereumLikeExtendedPublicKey.h>
#include <wallet/common/database/AccountDatabaseHelper.h>
#include <wallet/ethereum/database/EthereumLikeAccountDatabaseHelper.h>
namespace ledger {
namespace core {
const api::WalletType EthereumLikeWallet::type = api::WalletType::ETHEREUM;
EthereumLikeWallet::EthereumLikeWallet(const std::string &name,
const std::shared_ptr<EthereumLikeBlockchainExplorer>& explorer,
const std::shared_ptr<EthereumLikeBlockchainObserver> &observer,
const std::shared_ptr<EthereumLikeKeychainFactory> &keychainFactory,
const EthereumLikeAccountSynchronizerFactory &synchronizer,
const std::shared_ptr<WalletPool> &pool, const api::Currency &network,
const std::shared_ptr<DynamicObject>& configuration,
const DerivationScheme& scheme
)
: AbstractWallet(name, network, pool, configuration, scheme) {
_explorer = explorer;
_observer = observer;
_keychainFactory = keychainFactory;
_synchronizerFactory = synchronizer;
}
bool EthereumLikeWallet::isSynchronizing() {
return false;
}
std::shared_ptr<api::EventBus> EthereumLikeWallet::synchronize() {
return nullptr;
}
FuturePtr<ledger::core::api::Account>
EthereumLikeWallet::newAccountWithInfo(const api::AccountCreationInfo &info) {
if (info.chainCodes.size() != 1 || info.publicKeys.size() != 1 || info.owners.size() != 1)
throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (only one public key is needed)");
auto self = getSelf();
return async<api::ExtendedKeyAccountCreationInfo>([self, info] () -> api::ExtendedKeyAccountCreationInfo {
if (info.owners.size() != info.derivations.size() || info.owners.size() != info.chainCodes.size() ||
info.publicKeys.size() != info.owners.size())
throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (size of arrays differs)");
api::ExtendedKeyAccountCreationInfo result;
if (info.chainCodes[0].size() != 32 || info.publicKeys[0].size() != 65)
throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (contains invalid public key(s))");
DerivationPath occurencePath(info.derivations[0]);
auto xpub = EthereumLikeExtendedPublicKey::fromRaw(
self->getCurrency(),
Option<std::vector<uint8_t>>(),
info.publicKeys[0],
info.chainCodes[0],
info.derivations[0]
);
result.owners.push_back(info.owners[0]);
result.derivations.push_back(info.derivations[0]);
result.extendedKeys.push_back(xpub->toBase58());
result.index = info.index;
return result;
}).flatMap<std::shared_ptr<ledger::core::api::Account>>(getContext(), [self] (const api::ExtendedKeyAccountCreationInfo& info) -> Future<std::shared_ptr<ledger::core::api::Account>> {
return self->newAccountWithExtendedKeyInfo(info);
});
}
FuturePtr<ledger::core::api::Account>
EthereumLikeWallet::newAccountWithExtendedKeyInfo(const api::ExtendedKeyAccountCreationInfo &info) {
if (info.extendedKeys.empty()) {
throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Empty extended keys passed to newAccountWithExtendedKeyInfo");
}
auto self = getSelf();
auto scheme = getDerivationScheme();
scheme.setCoinType(getCurrency().bip44CoinType).setAccountIndex(info.index);
auto xpubPath = scheme.getSchemeTo(DerivationSchemeLevel::ACCOUNT_INDEX).getPath();
auto index = info.index;
return async<std::shared_ptr<api::Account> >([=] () -> std::shared_ptr<api::Account> {
auto keychain = self->_keychainFactory->build(
index,
xpubPath,
getConfig(),
info,
getAccountInternalPreferences(index),
getCurrency()
);
soci::session sql(self->getDatabase()->getPool());
soci::transaction tr(sql);
auto accountUid = AccountDatabaseHelper::createAccountUid(self->getWalletUid(), index);
if (AccountDatabaseHelper::accountExists(sql, self->getWalletUid(), index))
throw make_exception(api::ErrorCode::ACCOUNT_ALREADY_EXISTS, "Account {}, for wallet '{}', already exists", index, self->getWalletUid());
AccountDatabaseHelper::createAccount(sql, self->getWalletUid(), index);
EthereumLikeAccountDatabaseHelper::createAccount(sql, self->getWalletUid(), index, info.extendedKeys[info.extendedKeys.size() - 1]);
tr.commit();
auto account = std::static_pointer_cast<api::Account>(std::make_shared<EthereumLikeAccount>(
self->shared_from_this(),
index,
self->_explorer,
self->_observer,
self->_synchronizerFactory(),
keychain
));
self->addAccountInstanceToInstanceCache(std::dynamic_pointer_cast<AbstractAccount>(account));
return account;
});
}
static DerivationScheme getAccountScheme(DerivationScheme &scheme) {
auto accountScheme = scheme.getSchemeTo(DerivationSchemeLevel::ACCOUNT_INDEX);
// To handle all exotic paths we should avoid private derivations
// So if node or/and address level are hardened, then they are included in account's derivation path
auto path = scheme.getPath();
auto hardenedDepth = path.getDepth();
while (hardenedDepth) {
if (path.isHardened(hardenedDepth - 1)) {
break;
}
hardenedDepth--;
}
auto lastHardenedScheme = scheme.getSchemeToDepth(hardenedDepth);
return accountScheme.getPath().getDepth() > lastHardenedScheme.getPath().getDepth() ? accountScheme : lastHardenedScheme;
}
Future<api::ExtendedKeyAccountCreationInfo>
EthereumLikeWallet::getExtendedKeyAccountCreationInfo(int32_t accountIndex) {
auto self = std::dynamic_pointer_cast<EthereumLikeWallet>(shared_from_this());
return async<api::ExtendedKeyAccountCreationInfo>([self, accountIndex] () -> api::ExtendedKeyAccountCreationInfo {
api::ExtendedKeyAccountCreationInfo info;
info.index = accountIndex;
auto scheme = self->getDerivationScheme();
scheme.setCoinType(self->getCurrency().bip44CoinType).setAccountIndex(accountIndex);;
auto keychainEngine = self->getConfiguration()->getString(api::Configuration::KEYCHAIN_ENGINE).value_or(api::ConfigurationDefaults::DEFAULT_KEYCHAIN);
if (keychainEngine == api::KeychainEngines::BIP32_P2PKH ||
keychainEngine == api::KeychainEngines::BIP49_P2SH) {
info.derivations.push_back(getAccountScheme(scheme).getPath().toString());
info.owners.push_back(std::string("main"));
} else {
throw make_exception(api::ErrorCode::IMPLEMENTATION_IS_MISSING, "No implementation found found for keychain {}", keychainEngine);
}
return info;
});
}
Future<api::AccountCreationInfo> EthereumLikeWallet::getAccountCreationInfo(int32_t accountIndex) {
auto self = std::dynamic_pointer_cast<EthereumLikeWallet>(shared_from_this());
return getExtendedKeyAccountCreationInfo(accountIndex).map<api::AccountCreationInfo>(getContext(), [self, accountIndex] (const api::ExtendedKeyAccountCreationInfo info) -> api::AccountCreationInfo {
api::AccountCreationInfo result;
result.index = accountIndex;
auto length = info.derivations.size();
for (auto i = 0; i < length; i++) {
DerivationPath path(info.derivations[i]);
auto owner = info.owners[i];
result.derivations.push_back(path.toString());
result.owners.push_back(owner);
}
return result;
});
}
std::shared_ptr<EthereumLikeWallet> EthereumLikeWallet::getSelf() {
return std::dynamic_pointer_cast<EthereumLikeWallet>(shared_from_this());
}
std::shared_ptr<AbstractAccount>
EthereumLikeWallet::createAccountInstance(soci::session &sql, const std::string &accountUid)
{
EthereumLikeAccountDatabaseEntry entry;
EthereumLikeAccountDatabaseHelper::queryAccount(sql, accountUid, entry);
auto scheme = getDerivationScheme();
scheme.setCoinType(getCurrency().bip44CoinType).setAccountIndex(entry.index);
auto xpubPath = getAccountScheme(scheme).getPath();
auto keychain = _keychainFactory->restore(entry.index, xpubPath, getConfig(), entry.address,
getAccountInternalPreferences(entry.index), getCurrency());
auto account = std::make_shared<EthereumLikeAccount>(shared_from_this(),
entry.index,
_explorer,
_observer,
_synchronizerFactory(),
keychain);
account->addERC20Accounts(sql, entry.erc20Accounts);
return account;
}
std::shared_ptr<EthereumLikeBlockchainExplorer> EthereumLikeWallet::getBlockchainExplorer() {
return _explorer;
}
}
}<commit_msg>Allow compact ETH pub keys (33 bytes)<commit_after>/*
*
* EthereumLikeWallet
*
* Created by El Khalil Bellakrid on 14/07/2018.
*
* The MIT License (MIT)
*
* Copyright (c) 2018 Ledger
*
* 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 "EthereumLikeWallet.h"
#include "EthereumLikeAccount.h"
#include <algorithm>
#include <async/wait.h>
#include <api/ErrorCode.hpp>
#include <api/AccountCallback.hpp>
#include <api/ConfigurationDefaults.hpp>
#include <api/KeychainEngines.hpp>
#include <ethereum/EthereumLikeExtendedPublicKey.h>
#include <wallet/common/database/AccountDatabaseHelper.h>
#include <wallet/ethereum/database/EthereumLikeAccountDatabaseHelper.h>
namespace ledger {
namespace core {
const api::WalletType EthereumLikeWallet::type = api::WalletType::ETHEREUM;
EthereumLikeWallet::EthereumLikeWallet(const std::string &name,
const std::shared_ptr<EthereumLikeBlockchainExplorer>& explorer,
const std::shared_ptr<EthereumLikeBlockchainObserver> &observer,
const std::shared_ptr<EthereumLikeKeychainFactory> &keychainFactory,
const EthereumLikeAccountSynchronizerFactory &synchronizer,
const std::shared_ptr<WalletPool> &pool, const api::Currency &network,
const std::shared_ptr<DynamicObject>& configuration,
const DerivationScheme& scheme
)
: AbstractWallet(name, network, pool, configuration, scheme) {
_explorer = explorer;
_observer = observer;
_keychainFactory = keychainFactory;
_synchronizerFactory = synchronizer;
}
bool EthereumLikeWallet::isSynchronizing() {
return false;
}
std::shared_ptr<api::EventBus> EthereumLikeWallet::synchronize() {
return nullptr;
}
FuturePtr<ledger::core::api::Account>
EthereumLikeWallet::newAccountWithInfo(const api::AccountCreationInfo &info) {
if (info.chainCodes.size() != 1 || info.publicKeys.size() != 1 || info.owners.size() != 1)
throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (only one public key is needed)");
auto self = getSelf();
return async<api::ExtendedKeyAccountCreationInfo>([self, info] () -> api::ExtendedKeyAccountCreationInfo {
if (info.owners.size() != info.derivations.size() || info.owners.size() != info.chainCodes.size() ||
info.publicKeys.size() != info.owners.size())
throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (size of arrays differs)");
api::ExtendedKeyAccountCreationInfo result;
if (info.chainCodes[0].size() != 32 || (info.publicKeys[0].size() != 65 && info.publicKeys[0].size() != 33))
throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (contains invalid public key(s))");
DerivationPath occurencePath(info.derivations[0]);
auto xpub = EthereumLikeExtendedPublicKey::fromRaw(
self->getCurrency(),
Option<std::vector<uint8_t>>(),
info.publicKeys[0],
info.chainCodes[0],
info.derivations[0]
);
result.owners.push_back(info.owners[0]);
result.derivations.push_back(info.derivations[0]);
result.extendedKeys.push_back(xpub->toBase58());
result.index = info.index;
return result;
}).flatMap<std::shared_ptr<ledger::core::api::Account>>(getContext(), [self] (const api::ExtendedKeyAccountCreationInfo& info) -> Future<std::shared_ptr<ledger::core::api::Account>> {
return self->newAccountWithExtendedKeyInfo(info);
});
}
FuturePtr<ledger::core::api::Account>
EthereumLikeWallet::newAccountWithExtendedKeyInfo(const api::ExtendedKeyAccountCreationInfo &info) {
if (info.extendedKeys.empty()) {
throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Empty extended keys passed to newAccountWithExtendedKeyInfo");
}
auto self = getSelf();
auto scheme = getDerivationScheme();
scheme.setCoinType(getCurrency().bip44CoinType).setAccountIndex(info.index);
auto xpubPath = scheme.getSchemeTo(DerivationSchemeLevel::ACCOUNT_INDEX).getPath();
auto index = info.index;
return async<std::shared_ptr<api::Account> >([=] () -> std::shared_ptr<api::Account> {
auto keychain = self->_keychainFactory->build(
index,
xpubPath,
getConfig(),
info,
getAccountInternalPreferences(index),
getCurrency()
);
soci::session sql(self->getDatabase()->getPool());
soci::transaction tr(sql);
auto accountUid = AccountDatabaseHelper::createAccountUid(self->getWalletUid(), index);
if (AccountDatabaseHelper::accountExists(sql, self->getWalletUid(), index))
throw make_exception(api::ErrorCode::ACCOUNT_ALREADY_EXISTS, "Account {}, for wallet '{}', already exists", index, self->getWalletUid());
AccountDatabaseHelper::createAccount(sql, self->getWalletUid(), index);
EthereumLikeAccountDatabaseHelper::createAccount(sql, self->getWalletUid(), index, info.extendedKeys[info.extendedKeys.size() - 1]);
tr.commit();
auto account = std::static_pointer_cast<api::Account>(std::make_shared<EthereumLikeAccount>(
self->shared_from_this(),
index,
self->_explorer,
self->_observer,
self->_synchronizerFactory(),
keychain
));
self->addAccountInstanceToInstanceCache(std::dynamic_pointer_cast<AbstractAccount>(account));
return account;
});
}
static DerivationScheme getAccountScheme(DerivationScheme &scheme) {
auto accountScheme = scheme.getSchemeTo(DerivationSchemeLevel::ACCOUNT_INDEX);
// To handle all exotic paths we should avoid private derivations
// So if node or/and address level are hardened, then they are included in account's derivation path
auto path = scheme.getPath();
auto hardenedDepth = path.getDepth();
while (hardenedDepth) {
if (path.isHardened(hardenedDepth - 1)) {
break;
}
hardenedDepth--;
}
auto lastHardenedScheme = scheme.getSchemeToDepth(hardenedDepth);
return accountScheme.getPath().getDepth() > lastHardenedScheme.getPath().getDepth() ? accountScheme : lastHardenedScheme;
}
Future<api::ExtendedKeyAccountCreationInfo>
EthereumLikeWallet::getExtendedKeyAccountCreationInfo(int32_t accountIndex) {
auto self = std::dynamic_pointer_cast<EthereumLikeWallet>(shared_from_this());
return async<api::ExtendedKeyAccountCreationInfo>([self, accountIndex] () -> api::ExtendedKeyAccountCreationInfo {
api::ExtendedKeyAccountCreationInfo info;
info.index = accountIndex;
auto scheme = self->getDerivationScheme();
scheme.setCoinType(self->getCurrency().bip44CoinType).setAccountIndex(accountIndex);;
auto keychainEngine = self->getConfiguration()->getString(api::Configuration::KEYCHAIN_ENGINE).value_or(api::ConfigurationDefaults::DEFAULT_KEYCHAIN);
if (keychainEngine == api::KeychainEngines::BIP32_P2PKH ||
keychainEngine == api::KeychainEngines::BIP49_P2SH) {
info.derivations.push_back(getAccountScheme(scheme).getPath().toString());
info.owners.push_back(std::string("main"));
} else {
throw make_exception(api::ErrorCode::IMPLEMENTATION_IS_MISSING, "No implementation found found for keychain {}", keychainEngine);
}
return info;
});
}
Future<api::AccountCreationInfo> EthereumLikeWallet::getAccountCreationInfo(int32_t accountIndex) {
auto self = std::dynamic_pointer_cast<EthereumLikeWallet>(shared_from_this());
return getExtendedKeyAccountCreationInfo(accountIndex).map<api::AccountCreationInfo>(getContext(), [self, accountIndex] (const api::ExtendedKeyAccountCreationInfo info) -> api::AccountCreationInfo {
api::AccountCreationInfo result;
result.index = accountIndex;
auto length = info.derivations.size();
for (auto i = 0; i < length; i++) {
DerivationPath path(info.derivations[i]);
auto owner = info.owners[i];
result.derivations.push_back(path.toString());
result.owners.push_back(owner);
}
return result;
});
}
std::shared_ptr<EthereumLikeWallet> EthereumLikeWallet::getSelf() {
return std::dynamic_pointer_cast<EthereumLikeWallet>(shared_from_this());
}
std::shared_ptr<AbstractAccount>
EthereumLikeWallet::createAccountInstance(soci::session &sql, const std::string &accountUid)
{
EthereumLikeAccountDatabaseEntry entry;
EthereumLikeAccountDatabaseHelper::queryAccount(sql, accountUid, entry);
auto scheme = getDerivationScheme();
scheme.setCoinType(getCurrency().bip44CoinType).setAccountIndex(entry.index);
auto xpubPath = getAccountScheme(scheme).getPath();
auto keychain = _keychainFactory->restore(entry.index, xpubPath, getConfig(), entry.address,
getAccountInternalPreferences(entry.index), getCurrency());
auto account = std::make_shared<EthereumLikeAccount>(shared_from_this(),
entry.index,
_explorer,
_observer,
_synchronizerFactory(),
keychain);
account->addERC20Accounts(sql, entry.erc20Accounts);
return account;
}
std::shared_ptr<EthereumLikeBlockchainExplorer> EthereumLikeWallet::getBlockchainExplorer() {
return _explorer;
}
}
}
<|endoftext|>
|
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include <bse/processor.hh>
#include <bse/signalmath.hh>
#include "bse/internal.hh"
#define DDEBUG(...) Bse::debug ("debugdsp", __VA_ARGS__)
namespace Bse {
/// Namespace used for DSP debugging definitiond.
namespace DebugDsp {
using namespace AudioSignal;
// == DbgParameterizer ==
// Debug module to test parameter handling
class DbgParameterizer : public AudioSignal::Processor {
IBusId stereoin, auxin;
OBusId stereout;
void
query_info (ProcessorInfo &info) override
{
info.uri = "Bse.DebugDsp.DbgParameterizer";
// info.version = "0";
info.label = "DbgParameterizer";
info.category = "Shaping";
}
void
initialize () override
{
start_param_group ("Main Settings");
add_param ("Main Input 1", "M1", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 2", "M2", "G:big", true);
add_param ("Main Input 3", "M3", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 4", "M4", "G:big", false);
add_param ("Main Input 5", "M5", "G:big", true);
add_param ("Main Input 6", "M6", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 7", "M7", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 8", "M8", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 9", "M9", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 10", "M10", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 11", "M11", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 12", "M12", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 13", "M13", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 14", "M14", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 15", "M15", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 16", "M16", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 17", "M17", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 18", "M18", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 19", "M19", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 20", "M20", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 21", "M21", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 22", "M22", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 23", "M23", 0, 100, "G:big", 11.0, "%");
start_param_group ("Additional Knobs");
add_param ("Additional Input 1", "A1", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 2", "A2", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 3", "A3", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 4", "A4", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 5", "A5", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 6", "A6", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 7", "A7", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 8" , "A8", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 9", "A9", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 10", "A10", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 11", "A11", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 12", "A12", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 13", "A13", 0, 100, "G:big", 11.0, "%");
start_param_group ("Volume");
add_param ("Volume1", "V1", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume2", "V2", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume3", "V3", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume4", "V4", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume5", "V5", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume6", "V6", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume7", "V7", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume8", "V8", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume9", "V9", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume10", "V10", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume11", "V11", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume12", "V12", 0, 100, "G:slider", 33.0, "%");
start_param_group ("Gain Envelope");
add_param ("Env1 Attack", "A", 0, 100, "G:big", 11.0, "%");
add_param ("Env1 Decay", "D", 0, 100, "G:big", 11.0, "%");
add_param ("Env1 Sustain", "S", 0, 100, "G:big", 11.0, "%");
add_param ("Env1 Release", "R", 0, 100, "G:big", 11.0, "%");
add_param ("Gain", "G", 0, 100, "G:slider", 33.0, "%",
"Amount of amplification for the input signal");
add_param ("Gain Reduction", "GR", -96, 12, "G:out:inversemeter", 0.0, "dB",
"Amount of gain reduction");
ChoiceEntries centries;
centries += { "Surround", "Usually 5.1 or 7.1 channel configuration" };
centries += { "Stereo31", "Stereo with side and LFE channels" };
centries += { "Stereo21", "Stereo with LFE channel" };
centries += { "Stereo", "Left and Right speaker combination" }; // 20
centries += { "Right" };
centries += { "Left" };
centries += { "Mono", "Sound configuration with a single speaker" };
add_param ("Channel Selection", "Chan", std::move (centries), "G:dropdown", 0,
"What channels are used for signal processing");
start_param_group ("ADSR Envelope");
add_param ("Env2 Attack", "A", 0, 100, "G:big", 11.0, "%");
add_param ("Env2 Decay", "D", 0, 100, "G:big", 11.0, "%");
add_param ("Env2 Sustain", "S", 0, 100, "G:big", 11.0, "%");
add_param ("Env2 Release", "R", 0, 100, "G:big", 11.0, "%");
}
void
configure (uint n_ibusses, const SpeakerArrangement *ibusses, uint n_obusses, const SpeakerArrangement *obusses) override
{
remove_all_buses();
stereoin = add_input_bus ("Stereo In", SpeakerArrangement::STEREO);
auxin = add_input_bus ("Aux In", SpeakerArrangement::STEREO);
stereout = add_output_bus ("Stereo Out", SpeakerArrangement::STEREO);
assert_return (bus_info (stereoin).ident == "stereo-in");
assert_return (bus_info (auxin ).ident == "aux-in");
assert_return (bus_info (stereout).ident == "stereo-out");
}
void
adjust_param (ParamId tag)
{}
void
reset (const RenderSetup &rs) override
{}
void
render (const RenderSetup &rs, uint n_frames) override
{
assert_return (n_ichannels (stereoin) == 2);
assert_return (n_ichannels (auxin) == 2);
assert_return (n_ochannels (stereout) == 2);
for (uint ch = 0; ch < 2; ch++)
{
const float *stinf = ifloats (stereoin, ch);
const float *auxf = ifloats (auxin, ch);
if ((stinf[0] == 0.0 && iconst (stereoin, ch, n_frames)) ||
(auxf[0] == 0.0 && iconst (auxin, ch, n_frames)))
assign_oblock (stereout, ch, 0.0);
else if (connected (stereout))
{
float *soutf = oblock (stereout, ch);
if (auxf[0] == 1.0 && iconst (auxin, ch, n_frames))
redirect_oblock (stereout, ch, stinf);
else if (stinf[0] == 1.0 && iconst (stereoin, ch, n_frames))
redirect_oblock (stereout, ch, auxf);
else // stinf.connected && auxf.connected
floatmul (soutf, stinf, auxf, n_frames);
}
}
}
};
static auto dbgparameterizer = Bse::enroll_asp<DbgParameterizer>();
} // DebugDsp
} // Bse
<commit_msg>BSE: debugdsp.cc: print debug info on incoming events<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include <bse/processor.hh>
#include <bse/signalmath.hh>
#include "bse/internal.hh"
#define DDEBUG(...) Bse::debug ("debugdsp", __VA_ARGS__)
namespace Bse {
/// Namespace used for DSP debugging definitiond.
namespace DebugDsp {
using namespace AudioSignal;
// == DbgParameterizer ==
// Debug module to test parameter handling
class DbgParameterizer : public AudioSignal::Processor {
IBusId stereoin, auxin;
OBusId stereout;
void
query_info (ProcessorInfo &info) override
{
info.uri = "Bse.DebugDsp.DbgParameterizer";
// info.version = "0";
info.label = "DbgParameterizer";
info.category = "Shaping";
}
void
initialize () override
{
start_param_group ("Main Settings");
add_param ("Main Input 1", "M1", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 2", "M2", "G:big", true);
add_param ("Main Input 3", "M3", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 4", "M4", "G:big", false);
add_param ("Main Input 5", "M5", "G:big", true);
add_param ("Main Input 6", "M6", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 7", "M7", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 8", "M8", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 9", "M9", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 10", "M10", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 11", "M11", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 12", "M12", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 13", "M13", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 14", "M14", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 15", "M15", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 16", "M16", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 17", "M17", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 18", "M18", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 19", "M19", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 20", "M20", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 21", "M21", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 22", "M22", 0, 100, "G:big", 11.0, "%");
add_param ("Main Input 23", "M23", 0, 100, "G:big", 11.0, "%");
start_param_group ("Additional Knobs");
add_param ("Additional Input 1", "A1", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 2", "A2", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 3", "A3", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 4", "A4", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 5", "A5", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 6", "A6", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 7", "A7", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 8" , "A8", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 9", "A9", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 10", "A10", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 11", "A11", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 12", "A12", 0, 100, "G:big", 11.0, "%");
add_param ("Additional Input 13", "A13", 0, 100, "G:big", 11.0, "%");
start_param_group ("Volume");
add_param ("Volume1", "V1", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume2", "V2", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume3", "V3", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume4", "V4", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume5", "V5", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume6", "V6", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume7", "V7", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume8", "V8", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume9", "V9", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume10", "V10", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume11", "V11", 0, 100, "G:slider", 33.0, "%");
add_param ("Volume12", "V12", 0, 100, "G:slider", 33.0, "%");
start_param_group ("Gain Envelope");
add_param ("Env1 Attack", "A", 0, 100, "G:big", 11.0, "%");
add_param ("Env1 Decay", "D", 0, 100, "G:big", 11.0, "%");
add_param ("Env1 Sustain", "S", 0, 100, "G:big", 11.0, "%");
add_param ("Env1 Release", "R", 0, 100, "G:big", 11.0, "%");
add_param ("Gain", "G", 0, 100, "G:slider", 33.0, "%",
"Amount of amplification for the input signal");
add_param ("Gain Reduction", "GR", -96, 12, "G:out:inversemeter", 0.0, "dB",
"Amount of gain reduction");
ChoiceEntries centries;
centries += { "Surround", "Usually 5.1 or 7.1 channel configuration" };
centries += { "Stereo31", "Stereo with side and LFE channels" };
centries += { "Stereo21", "Stereo with LFE channel" };
centries += { "Stereo", "Left and Right speaker combination" }; // 20
centries += { "Right" };
centries += { "Left" };
centries += { "Mono", "Sound configuration with a single speaker" };
add_param ("Channel Selection", "Chan", std::move (centries), "G:dropdown", 0,
"What channels are used for signal processing");
start_param_group ("ADSR Envelope");
add_param ("Env2 Attack", "A", 0, 100, "G:big", 11.0, "%");
add_param ("Env2 Decay", "D", 0, 100, "G:big", 11.0, "%");
add_param ("Env2 Sustain", "S", 0, 100, "G:big", 11.0, "%");
add_param ("Env2 Release", "R", 0, 100, "G:big", 11.0, "%");
}
void
configure (uint n_ibusses, const SpeakerArrangement *ibusses, uint n_obusses, const SpeakerArrangement *obusses) override
{
remove_all_buses();
stereoin = add_input_bus ("Stereo In", SpeakerArrangement::STEREO);
auxin = add_input_bus ("Aux In", SpeakerArrangement::STEREO);
stereout = add_output_bus ("Stereo Out", SpeakerArrangement::STEREO);
assert_return (bus_info (stereoin).ident == "stereo-in");
assert_return (bus_info (auxin ).ident == "aux-in");
assert_return (bus_info (stereout).ident == "stereo-out");
}
void
adjust_param (ParamId tag)
{}
void
reset (const RenderSetup &rs) override
{}
void
render (const RenderSetup &rs, uint n_frames) override
{
assert_return (n_ichannels (stereoin) == 2);
assert_return (n_ichannels (auxin) == 2);
assert_return (n_ochannels (stereout) == 2);
EventRange erange = get_event_input();
printerr ("DbgParameterizer: events_pending=%d\n", erange.events_pending());
for (const auto &ev : erange)
printerr ("DbgParameterizer: %s\n", ev.to_string());
for (uint ch = 0; ch < 2; ch++)
{
const float *stinf = ifloats (stereoin, ch);
const float *auxf = ifloats (auxin, ch);
if ((stinf[0] == 0.0 && iconst (stereoin, ch, n_frames)) ||
(auxf[0] == 0.0 && iconst (auxin, ch, n_frames)))
assign_oblock (stereout, ch, 0.0);
else if (connected (stereout))
{
float *soutf = oblock (stereout, ch);
if (auxf[0] == 1.0 && iconst (auxin, ch, n_frames))
redirect_oblock (stereout, ch, stinf);
else if (stinf[0] == 1.0 && iconst (stereoin, ch, n_frames))
redirect_oblock (stereout, ch, auxf);
else // stinf.connected && auxf.connected
floatmul (soutf, stinf, auxf, n_frames);
}
}
}
};
static auto dbgparameterizer = Bse::enroll_asp<DbgParameterizer>();
} // DebugDsp
} // Bse
<|endoftext|>
|
<commit_before>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
class MyQueue {
public:
stack<int> stack_newest_on_top, stack_oldest_on_top;
void push(int x) {
stack_newest_on_top.push(x);
stack<int> temp = stack_newest_on_top;
while (!stack_oldest_on_top.empty()) {
stack_oldest_on_top.pop();
}
while (!temp.empty()) {
stack_oldest_on_top.push(temp.top());
temp.pop();
}
}
void pop() {
stack_oldest_on_top.pop();
stack<int> temp = stack_oldest_on_top;
while (!stack_newest_on_top.empty()) {
stack_newest_on_top.pop();
}
while (!temp.empty()) {
stack_newest_on_top.push(temp.top());
temp.pop();
}
}
int front() {
return stack_oldest_on_top.top();
}
};
int main() {
MyQueue q1;
int q, type, x;
cin >> q;
for(int i = 0; i < q; i++) {
cin >> type;
if(type == 1) {
cin >> x;
q1.push(x);
}
else if(type == 2) {
q1.pop();
}
else cout << q1.front() << endl;
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
<commit_msg>[HACKERRANK] Queues: A Tale of Two Stacks V2<commit_after>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
class MyQueue {
public:
stack<int> stack_newest_on_top, stack_oldest_on_top;
int popCount;
MyQueue() {
popCount = 0;
};
void push(int x) {
stack_newest_on_top.push(x);
}
void pop() {
popCount++;
}
int front() {
stack<int> temp = stack_newest_on_top;
while (temp.size() - popCount > 1) {
temp.pop();
}
return temp.top();
}
};
int main() {
MyQueue q1;
int q, type, x;
cin >> q;
for(int i = 0; i < q; i++) {
cin >> type;
if(type == 1) {
cin >> x;
q1.push(x);
}
else if(type == 2) {
q1.pop();
}
else cout << q1.front() << endl;
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
<|endoftext|>
|
<commit_before>#include "Player.h"
Player::Player(void)
{
mHitbox.setPosition(200, 200);
mHitbox.setSize(sf::Vector2f(50, 80));
mHitbox.setOrigin(25, 40);
mHitbox.setFillColor(sf::Color::Magenta);
mSpeed = 2;
mJump = false;
}
Player::~Player(void)
{
}
Entity* Player::newPlayer()
{
return new Player();
}
void Player::update()
{
Entity::update();
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
mHitbox.move(-mSpeed, 0);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
mHitbox.move(mSpeed, 0);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space) &&
checkPixelCollision(Terrain::getInstance().getTerrainImage(), sf::Vector2f(0, 40)))
{
mJump = true;
}
if(mJump == true)
{
float jump = -10+mFallVelocity;
mHitbox.move(0, jump);
if(jump >= 0 ||
checkPixelCollision(Terrain::getInstance().getTerrainImage(), sf::Vector2f(0, 40)))
{
mJump = false;
std::cout << "no more jump" << std::endl;
}
}
while(checkPixelCollision(Terrain::getInstance().getTerrainImage(), sf::Vector2f(25, 0)))
{
mHitbox.move(-mSpeed, 0);
}
while(checkPixelCollision(Terrain::getInstance().getTerrainImage(), sf::Vector2f(-25, 0)))
{
mHitbox.move(mSpeed, 0);
}
while(checkPixelCollision(Terrain::getInstance().getTerrainImage(), sf::Vector2f(0, -40)))
{
mHitbox.move(0, mFallVelocity);
}
}<commit_msg>jump with up<commit_after>#include "Player.h"
Player::Player(void)
{
mHitbox.setPosition(200, 200);
mHitbox.setSize(sf::Vector2f(50, 80));
mHitbox.setOrigin(25, 40);
mHitbox.setFillColor(sf::Color::Magenta);
mSpeed = 2;
mJump = false;
}
Player::~Player(void)
{
}
Entity* Player::newPlayer()
{
return new Player();
}
void Player::update()
{
Entity::update();
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
mHitbox.move(-mSpeed, 0);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
mHitbox.move(mSpeed, 0);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up) &&
checkPixelCollision(Terrain::getInstance().getTerrainImage(), sf::Vector2f(0, 40)))
{
mJump = true;
}
if(mJump == true)
{
float jump = -10+mFallVelocity;
mHitbox.move(0, jump);
if(jump >= 0 ||
checkPixelCollision(Terrain::getInstance().getTerrainImage(), sf::Vector2f(0, 40)))
{
mJump = false;
std::cout << "no more jump" << std::endl;
}
}
while(checkPixelCollision(Terrain::getInstance().getTerrainImage(), sf::Vector2f(25, 0)))
{
mHitbox.move(-mSpeed, 0);
}
while(checkPixelCollision(Terrain::getInstance().getTerrainImage(), sf::Vector2f(-25, 0)))
{
mHitbox.move(mSpeed, 0);
}
while(checkPixelCollision(Terrain::getInstance().getTerrainImage(), sf::Vector2f(0, -40)))
{
mHitbox.move(0, mFallVelocity);
}
}<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
// This source file is part of Hect.
//
// Copyright (c) 2014 Colin Hill
//
// 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 "PhysicsSystem.h"
#include "Hect/Physics/Bullet.h"
#include "Hect/Logic/Components/RigidBody.h"
#include "Hect/Logic/Components/Transform.h"
#include "Hect/Logic/Systems/TransformSystem.h"
#include "Hect/Runtime/Engine.h"
using namespace hect;
PhysicsSystem::PhysicsSystem(Engine& engine, Scene& scene) :
System(scene, SystemTickStage_Subsequent),
gravity(Vector3::unitY() * Real(-9.8)),
_configuration(new btDefaultCollisionConfiguration()),
_dispatcher(new btCollisionDispatcher(_configuration.get())),
_broadphase(new btDbvtBroadphase()),
_solver(new btSequentialImpulseConstraintSolver()),
_world(new btDiscreteDynamicsWorld(_dispatcher.get(), _broadphase.get(), _solver.get(), _configuration.get()))
{
(void)engine;
scene.components<RigidBody>().addListener(*this);
}
void PhysicsSystem::applyForce(RigidBody& rigidBody, const Vector3& force, const Vector3& relativePosition)
{
rigidBody._rigidBody->applyForce(convertToBullet(force), convertToBullet(relativePosition));
}
void PhysicsSystem::updateRigidBody(RigidBody& rigidBody)
{
rigidBody._rigidBody->setLinearVelocity(convertToBullet(rigidBody.linearVelocity));
rigidBody._rigidBody->setAngularVelocity(convertToBullet(rigidBody.angularVelocity));
}
void PhysicsSystem::tick(Real timeStep)
{
// Update gravity if needed
Vector3 bulletGravity = convertFromBullet(_world->getGravity());
if (gravity != bulletGravity)
{
_world->setGravity(convertToBullet(gravity));
}
// Update the dynamics scene
_world->stepSimulation(timeStep, 4);
TransformSystem& transformSystem = scene().system<TransformSystem>();
// For each rigid body component
for (RigidBody& rigidBody : scene().components<RigidBody>())
{
Entity& entity = rigidBody.entity();
auto transform = entity.component<Transform>();
if (!entity.parent() && transform)
{
// Update the transform to what Bullet says it should be
btTransform bulletTransform;
((btDefaultMotionState*)rigidBody._rigidBody->getMotionState())->getWorldTransform(bulletTransform);
Transform newTransform = convertFromBullet(bulletTransform);
transform->localPosition = newTransform.localPosition;
transform->localScale = newTransform.localScale;
transform->localRotation = newTransform.localRotation;
}
// Update rigid body properties to what Bullet says it should be
rigidBody.linearVelocity = convertFromBullet(rigidBody._rigidBody->getLinearVelocity());
rigidBody.angularVelocity = convertFromBullet(rigidBody._rigidBody->getAngularVelocity());
}
}
void PhysicsSystem::receiveEvent(const ComponentEvent<RigidBody>& event)
{
Entity& entity = event.entity();
TransformSystem& transformSystem = scene().system<TransformSystem>();
auto transform = entity.component<Transform>();
if (transform)
{
auto rigidBody = entity.component<RigidBody>();
if (rigidBody)
{
if (event.type == ComponentEventType_Add)
{
Mesh& mesh = *rigidBody->mesh;
rigidBody->_collisionShape.reset(new btConvexTriangleMeshShape(toBulletMesh(&mesh)));
btScalar mass = rigidBody->mass;
btVector3 localInertia(0, 0, 0);
if (mass != 0.0)
{
rigidBody->_collisionShape->calculateLocalInertia(mass, localInertia);
}
btVector3 linearVelocity = convertToBullet(rigidBody->linearVelocity);
btVector3 angularVelocity = convertToBullet(rigidBody->angularVelocity);
transformSystem.forceUpdate(*transform);
rigidBody->_motionState.reset(new btDefaultMotionState(convertToBullet(*transform)));
btRigidBody::btRigidBodyConstructionInfo info(mass, rigidBody->_motionState.get(), rigidBody->_collisionShape.get(), localInertia);
rigidBody->_rigidBody.reset(new btRigidBody(info));
rigidBody->_rigidBody->setSleepingThresholds(0, 0);
rigidBody->_rigidBody->setLinearVelocity(linearVelocity);
rigidBody->_rigidBody->setAngularVelocity(angularVelocity);
rigidBody->_rigidBody->setAngularFactor(0.5);
_world->addRigidBody(rigidBody->_rigidBody.get());
}
else if (event.type == ComponentEventType_Remove)
{
_world->removeRigidBody(rigidBody->_rigidBody.get());
}
}
}
}
btTriangleMesh* PhysicsSystem::toBulletMesh(Mesh* mesh)
{
auto it = _bulletMeshes.find(mesh);
if (it != _bulletMeshes.end())
{
// The Bullet mesh was already created
return (*it).second.get();
}
else
{
// Create a Bullet mesh from the mesh and keep it to be looked up later
btTriangleMesh* bulletMesh = convertToBullet(*mesh);
_bulletMeshes[mesh] = std::shared_ptr<btTriangleMesh>(bulletMesh);
return bulletMesh;
}
}<commit_msg>Fixed Clang warning in PhysicsSystem::tick()<commit_after>///////////////////////////////////////////////////////////////////////////////
// This source file is part of Hect.
//
// Copyright (c) 2014 Colin Hill
//
// 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 "PhysicsSystem.h"
#include "Hect/Physics/Bullet.h"
#include "Hect/Logic/Components/RigidBody.h"
#include "Hect/Logic/Components/Transform.h"
#include "Hect/Logic/Systems/TransformSystem.h"
#include "Hect/Runtime/Engine.h"
using namespace hect;
PhysicsSystem::PhysicsSystem(Engine& engine, Scene& scene) :
System(scene, SystemTickStage_Subsequent),
gravity(Vector3::unitY() * Real(-9.8)),
_configuration(new btDefaultCollisionConfiguration()),
_dispatcher(new btCollisionDispatcher(_configuration.get())),
_broadphase(new btDbvtBroadphase()),
_solver(new btSequentialImpulseConstraintSolver()),
_world(new btDiscreteDynamicsWorld(_dispatcher.get(), _broadphase.get(), _solver.get(), _configuration.get()))
{
(void)engine;
scene.components<RigidBody>().addListener(*this);
}
void PhysicsSystem::applyForce(RigidBody& rigidBody, const Vector3& force, const Vector3& relativePosition)
{
rigidBody._rigidBody->applyForce(convertToBullet(force), convertToBullet(relativePosition));
}
void PhysicsSystem::updateRigidBody(RigidBody& rigidBody)
{
rigidBody._rigidBody->setLinearVelocity(convertToBullet(rigidBody.linearVelocity));
rigidBody._rigidBody->setAngularVelocity(convertToBullet(rigidBody.angularVelocity));
}
void PhysicsSystem::tick(Real timeStep)
{
// Update gravity if needed
Vector3 bulletGravity = convertFromBullet(_world->getGravity());
if (gravity != bulletGravity)
{
_world->setGravity(convertToBullet(gravity));
}
// Update the dynamics scene
_world->stepSimulation(timeStep, 4);
// For each rigid body component
for (RigidBody& rigidBody : scene().components<RigidBody>())
{
Entity& entity = rigidBody.entity();
auto transform = entity.component<Transform>();
if (!entity.parent() && transform)
{
// Update the transform to what Bullet says it should be
btTransform bulletTransform;
((btDefaultMotionState*)rigidBody._rigidBody->getMotionState())->getWorldTransform(bulletTransform);
Transform newTransform = convertFromBullet(bulletTransform);
transform->localPosition = newTransform.localPosition;
transform->localScale = newTransform.localScale;
transform->localRotation = newTransform.localRotation;
}
// Update rigid body properties to what Bullet says it should be
rigidBody.linearVelocity = convertFromBullet(rigidBody._rigidBody->getLinearVelocity());
rigidBody.angularVelocity = convertFromBullet(rigidBody._rigidBody->getAngularVelocity());
}
}
void PhysicsSystem::receiveEvent(const ComponentEvent<RigidBody>& event)
{
Entity& entity = event.entity();
TransformSystem& transformSystem = scene().system<TransformSystem>();
auto transform = entity.component<Transform>();
if (transform)
{
auto rigidBody = entity.component<RigidBody>();
if (rigidBody)
{
if (event.type == ComponentEventType_Add)
{
Mesh& mesh = *rigidBody->mesh;
rigidBody->_collisionShape.reset(new btConvexTriangleMeshShape(toBulletMesh(&mesh)));
btScalar mass = rigidBody->mass;
btVector3 localInertia(0, 0, 0);
if (mass != 0.0)
{
rigidBody->_collisionShape->calculateLocalInertia(mass, localInertia);
}
btVector3 linearVelocity = convertToBullet(rigidBody->linearVelocity);
btVector3 angularVelocity = convertToBullet(rigidBody->angularVelocity);
transformSystem.forceUpdate(*transform);
rigidBody->_motionState.reset(new btDefaultMotionState(convertToBullet(*transform)));
btRigidBody::btRigidBodyConstructionInfo info(mass, rigidBody->_motionState.get(), rigidBody->_collisionShape.get(), localInertia);
rigidBody->_rigidBody.reset(new btRigidBody(info));
rigidBody->_rigidBody->setSleepingThresholds(0, 0);
rigidBody->_rigidBody->setLinearVelocity(linearVelocity);
rigidBody->_rigidBody->setAngularVelocity(angularVelocity);
rigidBody->_rigidBody->setAngularFactor(0.5);
_world->addRigidBody(rigidBody->_rigidBody.get());
}
else if (event.type == ComponentEventType_Remove)
{
_world->removeRigidBody(rigidBody->_rigidBody.get());
}
}
}
}
btTriangleMesh* PhysicsSystem::toBulletMesh(Mesh* mesh)
{
auto it = _bulletMeshes.find(mesh);
if (it != _bulletMeshes.end())
{
// The Bullet mesh was already created
return (*it).second.get();
}
else
{
// Create a Bullet mesh from the mesh and keep it to be looked up later
btTriangleMesh* bulletMesh = convertToBullet(*mesh);
_bulletMeshes[mesh] = std::shared_ptr<btTriangleMesh>(bulletMesh);
return bulletMesh;
}
}<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "java/sql/Timestamp.hxx"
#include "java/tools.hxx"
#include <comphelper/types.hxx>
#include "connectivity/dbconversion.hxx"
using namespace ::comphelper;
using namespace connectivity;
//**************************************************************
//************ Class: java.sql.Date
//**************************************************************
const double fMilliSecondsPerDay = 86400000.0;
jclass java_sql_Date::theClass = 0;
java_sql_Date::java_sql_Date( const ::com::sun::star::util::Date& _rOut ) : java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Convert parameters
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toDateString(_rOut);
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Turn of Java-Call for the constructor
// initialise temporary variables
static const char * cSignature = "(Ljava/lang/String;)Ljava/sql/Date;";
jobject tempObj;
static jmethodID mID(NULL);
if ( !mID )
mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// and clean
}
java_sql_Date::~java_sql_Date()
{}
jclass java_sql_Date::getMyClass() const
{
return st_getMyClass();
}
jclass java_sql_Date::st_getMyClass()
{
// the class needs only be fetched once, that is why it is static
if( !theClass )
theClass = findMyClass("java/sql/Date");
return theClass;
}
// -----------------------------------------------------------------------------
java_sql_Date::operator ::com::sun::star::util::Date()
{
return ::dbtools::DBTypeConversion::toDate(toString());
}
//**************************************************************
//************ Class: java.sql.Time
//**************************************************************
jclass java_sql_Time::theClass = 0;
java_sql_Time::~java_sql_Time()
{}
jclass java_sql_Time::getMyClass() const
{
return st_getMyClass();
}
jclass java_sql_Time::st_getMyClass()
{
// the class needs only be fetched once, that is why it is static
if( !theClass )
theClass = findMyClass("java/sql/Time");
return theClass;
}
java_sql_Time::java_sql_Time( const ::com::sun::star::util::Time& _rOut ): java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Convert parameters
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toTimeString(_rOut);
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Turn off Java-Call for the constructor
// intialise temporary variables
static const char * cSignature = "(Ljava/lang/String;)Ljava/sql/Time;";
jobject tempObj;
static jmethodID mID(NULL);
if ( !mID )
mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
t.pEnv->DeleteLocalRef((jstring)args[0].l);
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// and clean
}
// -----------------------------------------------------------------------------
java_sql_Time::operator ::com::sun::star::util::Time()
{
return ::dbtools::DBTypeConversion::toTime(toString());
}
//**************************************************************
//************ Class: java.sql.Timestamp
//**************************************************************
jclass java_sql_Timestamp::theClass = 0;
java_sql_Timestamp::~java_sql_Timestamp()
{}
jclass java_sql_Timestamp::getMyClass() const
{
return st_getMyClass();
}
jclass java_sql_Timestamp::st_getMyClass()
{
// the class needs only be fetched once, that is why it is static
if( !theClass )
theClass = findMyClass("java/sql/Timestamp");
return theClass;
}
java_sql_Timestamp::java_sql_Timestamp(const ::com::sun::star::util::DateTime& _rOut)
:java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Convert parameters
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toDateTimeString(_rOut);
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Turn off Java-Call for the constructor
// initialise temporary variables
static const char * cSignature = "(Ljava/lang/String;)Ljava/sql/Timestamp;";
jobject tempObj;
static jmethodID mID(NULL);
if ( !mID )
mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// and clean
}
// -----------------------------------------------------------------------------
java_sql_Timestamp::operator ::com::sun::star::util::DateTime()
{
return ::dbtools::DBTypeConversion::toDateTime(toString());
}
// -----------------------------------------------------------------------------
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#736110: make clear that this is not part of the if<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "java/sql/Timestamp.hxx"
#include "java/tools.hxx"
#include <comphelper/types.hxx>
#include "connectivity/dbconversion.hxx"
using namespace ::comphelper;
using namespace connectivity;
//**************************************************************
//************ Class: java.sql.Date
//**************************************************************
const double fMilliSecondsPerDay = 86400000.0;
jclass java_sql_Date::theClass = 0;
java_sql_Date::java_sql_Date( const ::com::sun::star::util::Date& _rOut ) : java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Convert parameters
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toDateString(_rOut);
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Turn of Java-Call for the constructor
// initialise temporary variables
static const char * cSignature = "(Ljava/lang/String;)Ljava/sql/Date;";
jobject tempObj;
static jmethodID mID(NULL);
if ( !mID )
mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );
OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// and clean
}
java_sql_Date::~java_sql_Date()
{}
jclass java_sql_Date::getMyClass() const
{
return st_getMyClass();
}
jclass java_sql_Date::st_getMyClass()
{
// the class needs only be fetched once, that is why it is static
if( !theClass )
theClass = findMyClass("java/sql/Date");
return theClass;
}
// -----------------------------------------------------------------------------
java_sql_Date::operator ::com::sun::star::util::Date()
{
return ::dbtools::DBTypeConversion::toDate(toString());
}
//**************************************************************
//************ Class: java.sql.Time
//**************************************************************
jclass java_sql_Time::theClass = 0;
java_sql_Time::~java_sql_Time()
{}
jclass java_sql_Time::getMyClass() const
{
return st_getMyClass();
}
jclass java_sql_Time::st_getMyClass()
{
// the class needs only be fetched once, that is why it is static
if( !theClass )
theClass = findMyClass("java/sql/Time");
return theClass;
}
java_sql_Time::java_sql_Time( const ::com::sun::star::util::Time& _rOut ): java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Convert parameters
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toTimeString(_rOut);
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Turn off Java-Call for the constructor
// intialise temporary variables
static const char * cSignature = "(Ljava/lang/String;)Ljava/sql/Time;";
jobject tempObj;
static jmethodID mID(NULL);
if ( !mID )
mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
t.pEnv->DeleteLocalRef((jstring)args[0].l);
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// and clean
}
// -----------------------------------------------------------------------------
java_sql_Time::operator ::com::sun::star::util::Time()
{
return ::dbtools::DBTypeConversion::toTime(toString());
}
//**************************************************************
//************ Class: java.sql.Timestamp
//**************************************************************
jclass java_sql_Timestamp::theClass = 0;
java_sql_Timestamp::~java_sql_Timestamp()
{}
jclass java_sql_Timestamp::getMyClass() const
{
return st_getMyClass();
}
jclass java_sql_Timestamp::st_getMyClass()
{
// the class needs only be fetched once, that is why it is static
if( !theClass )
theClass = findMyClass("java/sql/Timestamp");
return theClass;
}
java_sql_Timestamp::java_sql_Timestamp(const ::com::sun::star::util::DateTime& _rOut)
:java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Convert parameters
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toDateTimeString(_rOut);
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Turn off Java-Call for the constructor
// initialise temporary variables
static const char * cSignature = "(Ljava/lang/String;)Ljava/sql/Timestamp;";
jobject tempObj;
static jmethodID mID(NULL);
if ( !mID )
mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// and clean
}
// -----------------------------------------------------------------------------
java_sql_Timestamp::operator ::com::sun::star::util::DateTime()
{
return ::dbtools::DBTypeConversion::toDateTime(toString());
}
// -----------------------------------------------------------------------------
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: Generate3DAMRDataSetWithPulse.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME Generate3DAMRDataSetWithPulse.cxx -- Generated sample 3D AMR dataset
//
// .SECTION Description
// This utility code generates a simple 3D AMR dataset with a gaussian
// pulse at the center. The resulting AMR dataset is written using the
// vtkXMLHierarchicalBoxDataSetWriter.
#include <iostream>
#include <cmath>
#include <sstream>
#include <cassert>
#include "vtkUniformGrid.h"
#include "vtkDataArray.h"
#include "vtkDoubleArray.h"
#include "vtkCell.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkAMRBox.h"
#include "vtkHierarchicalBoxDataSet.h"
#include "vtkXMLHierarchicalBoxDataWriter.h"
#include "vtkAMRUtilities.h"
struct PulseAttributes {
double origin[3]; // xyz for the center of the pulse
double width[3]; // the width of the pulse
double amplitude; // the amplitude of the pulse
} Pulse;
//
// Function prototype declarations
//
// Description:
// Sets the pulse attributes
void SetPulse();
// Description:
// Constructs a uniform grid instance given the prescribed
// origin, grid spacing and dimensions.
vtkUniformGrid* GetGrid( double* origin,double* h,int* ndim );
// Description:
// Computes the gaussian pulse at the cell center of the cell
// corresponding to the given cellIdx w.r.t the given grid.
double ComputePulseAt( vtkUniformGrid *grid, const int cellIdx );
// Description:
// Computes the cell center for the cell corresponding to cellIdx w.r.t.
// the given grid. The cell center is stored in the supplied buffer c.
void ComputeCellCenter( vtkUniformGrid *grid, const int cellIdx, double c[3] );
// Description:
// Constructs the vtkHierarchicalBoxDataSet.
vtkHierarchicalBoxDataSet* GetAMRDataSet();
// Description:
// Writes the amr data set using the prescribed prefix.
void WriteAMRData( vtkHierarchicalBoxDataSet *amrData, std::string prefix );
//
// Program main
//
int main( int argc, char **argv )
{
// STEP 0: Initialize gaussian pulse parameters
SetPulse();
// STEP 1: Get the AMR dataset
vtkHierarchicalBoxDataSet *amrDataSet = GetAMRDataSet();
assert( "pre: NULL AMR dataset" && ( amrDataSet != NULL ) );
WriteAMRData( amrDataSet, "Gaussian3D" );
return 0;
}
//=============================================================================
// Function Prototype Implementation
//=============================================================================
void SetPulse()
{
Pulse.origin[0] = Pulse.origin[1] = Pulse.origin[2] = -1.0;
Pulse.width[0] = Pulse.width[1] = Pulse.width[2] = 6.0;
Pulse.amplitude = 0.0001;
}
//------------------------------------------------------------------------------
void WriteAMRData( vtkHierarchicalBoxDataSet *amrData, std::string prefix )
{
assert( "pre: AMR Data is NULL!" && (amrData != NULL) );
vtkXMLHierarchicalBoxDataWriter *myAMRWriter=
vtkXMLHierarchicalBoxDataWriter::New();
std::ostringstream oss;
oss << prefix << ".vthb";
myAMRWriter->SetFileName( oss.str().c_str() );
myAMRWriter->SetInput( amrData );
myAMRWriter->Write();
myAMRWriter->Delete();
}
//------------------------------------------------------------------------------
vtkHierarchicalBoxDataSet* GetAMRDataSet()
{
vtkHierarchicalBoxDataSet *data = vtkHierarchicalBoxDataSet::New();
data->Initialize();
double origin[3];
double h[3];
int ndim[3];
int blockId = -1;
int level = -1;
int rank = 0;
// Root Block -- Block 0
ndim[0] = 6; ndim[1] = ndim[2] = 5;
h[0] = h[1] = h[2] = 1.0;
origin[0] = origin[1] = origin[2] = -2.0;
blockId = 0;
level = 0;
vtkUniformGrid *root = GetGrid(origin, h, ndim);
data->SetDataSet( level, blockId,root);
root->Delete();
// Block 1
ndim[0] = 3; ndim[1] = ndim[2] = 5;
h[0] = h[1] = h[2] = 0.5;
origin[0] = origin[1] = origin[2] = -2.0;
blockId = 0;
level = 1;
vtkUniformGrid *grid1 = GetGrid(origin, h, ndim);
data->SetDataSet( level, blockId,grid1);
grid1->Delete();
// Block 2
ndim[0] = 3; ndim[1] = ndim[2] = 5;
h[0] = h[1] = h[2] = 0.5;
origin[0] = 0.0; origin[1] = origin[2] = -1.0;
blockId = 1;
level = 1;
vtkUniformGrid *grid2 = GetGrid(origin, h, ndim);
data->SetDataSet( level, blockId,grid2);
grid2->Delete();
// Block 3
ndim[0] = 3; ndim[1] = ndim[2] = 7;
h[0] = h[1] = h[2] = 0.5;
origin[0] = 2.0; origin[1] = origin[2] = -1.0;
blockId = 2;
level = 1;
vtkUniformGrid *grid3 = GetGrid(origin, h, ndim);
data->SetDataSet( level, blockId,grid3);
grid3->Delete();
vtkAMRUtilities::GenerateMetaData( data, NULL );
data->GenerateVisibilityArrays();
return( data );
}
//------------------------------------------------------------------------------
void ComputeCellCenter( vtkUniformGrid *grid, const int cellIdx, double c[3] )
{
assert( "pre: grid != NULL" && (grid != NULL) );
assert( "pre: Null cell center buffer" && (c != NULL) );
assert( "pre: cellIdx in bounds" &&
(cellIdx >= 0) && (cellIdx < grid->GetNumberOfCells() ) );
vtkCell *myCell = grid->GetCell( cellIdx );
assert( "post: cell is NULL" && (myCell != NULL) );
double pCenter[3];
double *weights = new double[ myCell->GetNumberOfPoints() ];
int subId = myCell->GetParametricCenter( pCenter );
myCell->EvaluateLocation( subId,pCenter,c,weights );
delete [] weights;
}
//------------------------------------------------------------------------------
double ComputePulseAt( vtkUniformGrid *grid, const int cellIdx )
{
// Sanity check
assert( "pre: grid != NULL" && (grid != NULL) );
assert( "pre: cellIdx in bounds" &&
( (cellIdx >= 0) && (cellIdx < grid->GetNumberOfCells()) ) );
double xyzCenter[3];
ComputeCellCenter( grid, cellIdx, xyzCenter );
double r = 0.0;
for( int i=0; i < 2; ++i )
{
double dx = xyzCenter[i]-Pulse.origin[i];
r += (dx*dx) / (Pulse.width[i]*Pulse.width[i]);
}
double f = Pulse.amplitude*std::exp( -r );
std::cout << "G(" << xyzCenter[0] << ",";
std::cout << xyzCenter[1] << ",";
std::cout << xyzCenter[2] << ") = ";
std::cout << f << "\t";
std::cout << "r=" << r << std::endl;
std::cout.flush();
return( f );
}
//------------------------------------------------------------------------------
vtkUniformGrid* GetGrid( double* origin,double* h,int* ndim )
{
vtkUniformGrid *grd = vtkUniformGrid::New();
grd->Initialize();
grd->SetOrigin( origin );
grd->SetSpacing( h );
grd->SetDimensions( ndim );
vtkDoubleArray* xyz = vtkDoubleArray::New( );
xyz->SetName( "GaussianPulse" );
xyz->SetNumberOfComponents( 1 );
xyz->SetNumberOfTuples( grd->GetNumberOfCells() );
for( int cellIdx=0; cellIdx < grd->GetNumberOfCells(); ++cellIdx )
{
xyz->SetTuple1(cellIdx, ComputePulseAt(grd,cellIdx) );
} // END for all cells
grd->GetCellData()->AddArray(xyz);
xyz->Delete();
return grd;
}
<commit_msg>BUGFIX: Fix memory leak<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: Generate3DAMRDataSetWithPulse.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME Generate3DAMRDataSetWithPulse.cxx -- Generated sample 3D AMR dataset
//
// .SECTION Description
// This utility code generates a simple 3D AMR dataset with a gaussian
// pulse at the center. The resulting AMR dataset is written using the
// vtkXMLHierarchicalBoxDataSetWriter.
#include <iostream>
#include <cmath>
#include <sstream>
#include <cassert>
#include "vtkUniformGrid.h"
#include "vtkDataArray.h"
#include "vtkDoubleArray.h"
#include "vtkCell.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkAMRBox.h"
#include "vtkHierarchicalBoxDataSet.h"
#include "vtkXMLHierarchicalBoxDataWriter.h"
#include "vtkAMRUtilities.h"
struct PulseAttributes {
double origin[3]; // xyz for the center of the pulse
double width[3]; // the width of the pulse
double amplitude; // the amplitude of the pulse
} Pulse;
//
// Function prototype declarations
//
// Description:
// Sets the pulse attributes
void SetPulse();
// Description:
// Constructs a uniform grid instance given the prescribed
// origin, grid spacing and dimensions.
vtkUniformGrid* GetGrid( double* origin,double* h,int* ndim );
// Description:
// Computes the gaussian pulse at the cell center of the cell
// corresponding to the given cellIdx w.r.t the given grid.
double ComputePulseAt( vtkUniformGrid *grid, const int cellIdx );
// Description:
// Computes the cell center for the cell corresponding to cellIdx w.r.t.
// the given grid. The cell center is stored in the supplied buffer c.
void ComputeCellCenter( vtkUniformGrid *grid, const int cellIdx, double c[3] );
// Description:
// Constructs the vtkHierarchicalBoxDataSet.
vtkHierarchicalBoxDataSet* GetAMRDataSet();
// Description:
// Writes the amr data set using the prescribed prefix.
void WriteAMRData( vtkHierarchicalBoxDataSet *amrData, std::string prefix );
//
// Program main
//
int main( int argc, char **argv )
{
// STEP 0: Initialize gaussian pulse parameters
SetPulse();
// STEP 1: Get the AMR dataset
vtkHierarchicalBoxDataSet *amrDataSet = GetAMRDataSet();
assert( "pre: NULL AMR dataset" && ( amrDataSet != NULL ) );
WriteAMRData( amrDataSet, "Gaussian3D" );
amrDataSet->Delete();
return 0;
}
//=============================================================================
// Function Prototype Implementation
//=============================================================================
void SetPulse()
{
Pulse.origin[0] = Pulse.origin[1] = Pulse.origin[2] = -1.0;
Pulse.width[0] = Pulse.width[1] = Pulse.width[2] = 6.0;
Pulse.amplitude = 0.0001;
}
//------------------------------------------------------------------------------
void WriteAMRData( vtkHierarchicalBoxDataSet *amrData, std::string prefix )
{
assert( "pre: AMR Data is NULL!" && (amrData != NULL) );
vtkXMLHierarchicalBoxDataWriter *myAMRWriter=
vtkXMLHierarchicalBoxDataWriter::New();
std::ostringstream oss;
oss << prefix << ".vthb";
myAMRWriter->SetFileName( oss.str().c_str() );
myAMRWriter->SetInput( amrData );
myAMRWriter->Write();
myAMRWriter->Delete();
}
//------------------------------------------------------------------------------
vtkHierarchicalBoxDataSet* GetAMRDataSet()
{
vtkHierarchicalBoxDataSet *data = vtkHierarchicalBoxDataSet::New();
data->Initialize();
double origin[3];
double h[3];
int ndim[3];
int blockId = -1;
int level = -1;
int rank = 0;
// Root Block -- Block 0
ndim[0] = 6; ndim[1] = ndim[2] = 5;
h[0] = h[1] = h[2] = 1.0;
origin[0] = origin[1] = origin[2] = -2.0;
blockId = 0;
level = 0;
vtkUniformGrid *root = GetGrid(origin, h, ndim);
data->SetDataSet( level, blockId,root);
root->Delete();
// Block 1
ndim[0] = 3; ndim[1] = ndim[2] = 5;
h[0] = h[1] = h[2] = 0.5;
origin[0] = origin[1] = origin[2] = -2.0;
blockId = 0;
level = 1;
vtkUniformGrid *grid1 = GetGrid(origin, h, ndim);
data->SetDataSet( level, blockId,grid1);
grid1->Delete();
// Block 2
ndim[0] = 3; ndim[1] = ndim[2] = 5;
h[0] = h[1] = h[2] = 0.5;
origin[0] = 0.0; origin[1] = origin[2] = -1.0;
blockId = 1;
level = 1;
vtkUniformGrid *grid2 = GetGrid(origin, h, ndim);
data->SetDataSet( level, blockId,grid2);
grid2->Delete();
// Block 3
ndim[0] = 3; ndim[1] = ndim[2] = 7;
h[0] = h[1] = h[2] = 0.5;
origin[0] = 2.0; origin[1] = origin[2] = -1.0;
blockId = 2;
level = 1;
vtkUniformGrid *grid3 = GetGrid(origin, h, ndim);
data->SetDataSet( level, blockId,grid3);
grid3->Delete();
vtkAMRUtilities::GenerateMetaData( data, NULL );
data->GenerateVisibilityArrays();
return( data );
}
//------------------------------------------------------------------------------
void ComputeCellCenter( vtkUniformGrid *grid, const int cellIdx, double c[3] )
{
assert( "pre: grid != NULL" && (grid != NULL) );
assert( "pre: Null cell center buffer" && (c != NULL) );
assert( "pre: cellIdx in bounds" &&
(cellIdx >= 0) && (cellIdx < grid->GetNumberOfCells() ) );
vtkCell *myCell = grid->GetCell( cellIdx );
assert( "post: cell is NULL" && (myCell != NULL) );
double pCenter[3];
double *weights = new double[ myCell->GetNumberOfPoints() ];
int subId = myCell->GetParametricCenter( pCenter );
myCell->EvaluateLocation( subId,pCenter,c,weights );
delete [] weights;
}
//------------------------------------------------------------------------------
double ComputePulseAt( vtkUniformGrid *grid, const int cellIdx )
{
// Sanity check
assert( "pre: grid != NULL" && (grid != NULL) );
assert( "pre: cellIdx in bounds" &&
( (cellIdx >= 0) && (cellIdx < grid->GetNumberOfCells()) ) );
double xyzCenter[3];
ComputeCellCenter( grid, cellIdx, xyzCenter );
double r = 0.0;
for( int i=0; i < 2; ++i )
{
double dx = xyzCenter[i]-Pulse.origin[i];
r += (dx*dx) / (Pulse.width[i]*Pulse.width[i]);
}
double f = Pulse.amplitude*std::exp( -r );
std::cout << "G(" << xyzCenter[0] << ",";
std::cout << xyzCenter[1] << ",";
std::cout << xyzCenter[2] << ") = ";
std::cout << f << "\t";
std::cout << "r=" << r << std::endl;
std::cout.flush();
return( f );
}
//------------------------------------------------------------------------------
vtkUniformGrid* GetGrid( double* origin,double* h,int* ndim )
{
vtkUniformGrid *grd = vtkUniformGrid::New();
grd->Initialize();
grd->SetOrigin( origin );
grd->SetSpacing( h );
grd->SetDimensions( ndim );
vtkDoubleArray* xyz = vtkDoubleArray::New( );
xyz->SetName( "GaussianPulse" );
xyz->SetNumberOfComponents( 1 );
xyz->SetNumberOfTuples( grd->GetNumberOfCells() );
for( int cellIdx=0; cellIdx < grd->GetNumberOfCells(); ++cellIdx )
{
xyz->SetTuple1(cellIdx, ComputePulseAt(grd,cellIdx) );
} // END for all cells
grd->GetCellData()->AddArray(xyz);
xyz->Delete();
return grd;
}
<|endoftext|>
|
<commit_before>// Filename: stereoDisplayRegion.cxx
// Created by: drose (19Feb09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "stereoDisplayRegion.h"
#include "pandaNode.h"
TypeHandle StereoDisplayRegion::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::Constructor
// Access: Published
// Description:
////////////////////////////////////////////////////////////////////
StereoDisplayRegion::
StereoDisplayRegion(GraphicsOutput *window,
const LVecBase4 &dimensions,
DisplayRegion *left, DisplayRegion *right) :
DisplayRegion(window, dimensions),
_left_eye(left),
_right_eye(right)
{
nassertv(window == left->get_window() &&
window == right->get_window());
set_stereo_channel(Lens::SC_stereo);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::Destructor
// Access: Published, Virtual
// Description:
////////////////////////////////////////////////////////////////////
StereoDisplayRegion::
~StereoDisplayRegion() {
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_clear_active
// Access: Published, Virtual
// Description: Sets the clear-active flag for any bitplane.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_clear_active(int n, bool clear_active) {
// The clear_active flag gets set only on the parent, stereo display
// region.
DisplayRegion::set_clear_active(n, clear_active);
// Except for depth and stencil buffers. These also get set on the
// right display region by default, on the assumption that we want
// to clear these buffers between drawing the eyes, and that the
// right eye is the second of the pair.
switch (n) {
case RTP_stencil:
case RTP_depth_stencil:
case RTP_depth:
_right_eye->set_clear_active(n, clear_active);
break;
default:
break;
}
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_clear_value
// Access: Published, Virtual
// Description: Sets the clear value for any bitplane.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_clear_value(int n, const LColor &clear_value) {
DisplayRegion::set_clear_value(n, clear_value);
_left_eye->set_clear_value(n, clear_value);
_right_eye->set_clear_value(n, clear_value);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::disable_clears
// Access: Published, Virtual
// Description: Disables both the color and depth clear. See
// set_clear_color_active and set_clear_depth_active.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
disable_clears() {
DisplayRegion::disable_clears();
_left_eye->disable_clears();
_right_eye->disable_clears();
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_pixel_zoom
// Access: Published, Virtual
// Description: Sets the pixel_zoom for left and right eyes.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_pixel_zoom(PN_stdfloat pixel_zoom) {
DisplayRegion::set_pixel_zoom(pixel_zoom);
_left_eye->set_pixel_zoom(pixel_zoom);
_right_eye->set_pixel_zoom(pixel_zoom);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_dimensions
// Access: Published, Virtual
// Description: Sets both the left and right DisplayRegions to the
// indicated dimensions.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_dimensions(const LVecBase4 &dimensions) {
DisplayRegion::set_dimensions(dimensions);
_left_eye->set_dimensions(dimensions);
_right_eye->set_dimensions(dimensions);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::is_stereo
// Access: Published, Virtual
// Description: Returns true if this is a StereoDisplayRegion, false
// otherwise.
////////////////////////////////////////////////////////////////////
bool StereoDisplayRegion::
is_stereo() const {
return true;
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_camera
// Access: Published, Virtual
// Description: Sets both the left and right DisplayRegions to the
// indicated camera.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_camera(const NodePath &camera) {
DisplayRegion::set_camera(camera);
_left_eye->set_camera(camera);
_right_eye->set_camera(camera);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_active
// Access: Published, Virtual
// Description: Sets the active flag on both the left and right
// DisplayRegions to the indicated value.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_active(bool active) {
DisplayRegion::set_active(active);
_left_eye->set_active(active);
_right_eye->set_active(active);
if (active) {
// Reenable the appropriate eyes according to our stereo_channel
// setting.
set_stereo_channel(get_stereo_channel());
}
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_sort
// Access: Published, Virtual
// Description: Sets the indicated sort value on the overall
// DisplayRegion, the indicated sort value + 1 on the
// left eye, and the indicated sort value + 2 on the
// right eye.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_sort(int sort) {
DisplayRegion::set_sort(sort);
_left_eye->set_sort(sort + 1);
_right_eye->set_sort(sort + 2);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_stereo_channel
// Access: Published, Virtual
// Description: Sets the stereo channels on the left and right eyes,
// and also sets the active flags independently on both
// eyes. For a StereoDisplayRegion, a different action
// is performed for each different value:
//
// SC_stereo - the left eye is set to SC_left, the right
// eye to SC_right, and both eyes are activated.
//
// SC_left - the left eye is set to SC_left and
// activated; the right eye is deactivated.
//
// SC_right - the right eye is set to SC_right and
// activated; the left eye is deactivated.
//
// SC_mono - the left eye is set to SC_mono and
// activated; the right eye is deactivated.
//
// This call also resets tex_view_offset to its default
// value, which is 0 for the left eye or 1 for the right
// eye of a stereo display region, or 0 for a mono
// display region.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_stereo_channel(Lens::StereoChannel stereo_channel) {
DisplayRegion::set_stereo_channel(stereo_channel);
if (!is_active()) {
return;
}
switch (stereo_channel) {
case Lens::SC_stereo:
_left_eye->set_stereo_channel(Lens::SC_left);
_left_eye->set_active(true);
_right_eye->set_stereo_channel(Lens::SC_right);
_right_eye->set_active(true);
break;
case Lens::SC_left:
_left_eye->set_stereo_channel(Lens::SC_left);
_left_eye->set_active(true);
_right_eye->set_active(false);
break;
case Lens::SC_right:
_left_eye->set_active(false);
_right_eye->set_stereo_channel(Lens::SC_right);
_right_eye->set_active(true);
break;
case Lens::SC_mono:
_left_eye->set_stereo_channel(Lens::SC_mono);
_left_eye->set_active(true);
_right_eye->set_active(false);
break;
}
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_tex_view_offset
// Access: Published, Virtual
// Description: Sets the current texture view offset for this
// DisplayRegion. This is normally set to zero. If
// nonzero, it is used to select a particular view of
// any multiview textures that are rendered within this
// DisplayRegion.
//
// When you call this on a StereoDisplayRegion, it
// automatically sets the specified value on the left
// eye, and the specified value + 1 on the right eye.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_tex_view_offset(int tex_view_offset) {
DisplayRegion::set_tex_view_offset(tex_view_offset);
_left_eye->set_tex_view_offset(tex_view_offset);
_right_eye->set_tex_view_offset(tex_view_offset + 1);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_incomplete_render
// Access: Published, Virtual
// Description: Sets the incomplete_render flag on both the left and
// right DisplayRegions to the indicated value.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_incomplete_render(bool incomplete_render) {
DisplayRegion::set_incomplete_render(incomplete_render);
_left_eye->set_incomplete_render(incomplete_render);
_right_eye->set_incomplete_render(incomplete_render);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_texture_reload_priority
// Access: Published, Virtual
// Description: Sets the texture_reload_priority on both the left and
// right DisplayRegions to the indicated value.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_texture_reload_priority(int texture_reload_priority) {
DisplayRegion::set_texture_reload_priority(texture_reload_priority);
_left_eye->set_texture_reload_priority(texture_reload_priority);
_right_eye->set_texture_reload_priority(texture_reload_priority);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_cull_traverser
// Access: Published, Virtual
// Description: Sets the CullTraverser for both the left and right
// DisplayRegions.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_cull_traverser(CullTraverser *trav) {
DisplayRegion::set_cull_traverser(trav);
_left_eye->set_cull_traverser(trav);
_right_eye->set_cull_traverser(trav);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_cube_map_index
// Access: Published, Virtual
// Description: Sets the cube_map_index on both the left and
// right DisplayRegions to the indicated value.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_cube_map_index(int cube_map_index) {
DisplayRegion::set_cube_map_index(cube_map_index);
_left_eye->set_cube_map_index(cube_map_index);
_right_eye->set_cube_map_index(cube_map_index);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::output
// Access: Published, Virtual
// Description:
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
output(ostream &out) const {
out << "StereoDisplayRegion(" << *_left_eye << ")";
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::make_cull_result_graph
// Access: Published, Virtual
// Description: Returns a special scene graph constructed to
// represent the results of the last frame's cull
// operation.
////////////////////////////////////////////////////////////////////
PT(PandaNode) StereoDisplayRegion::
make_cull_result_graph() {
PT(PandaNode) root = new PandaNode("stereo");
PT(PandaNode) left = _left_eye->make_cull_result_graph();
left->set_name("left");
root->add_child(left, _left_eye->get_sort());
PT(PandaNode) right = _right_eye->make_cull_result_graph();
right->set_name("right");
root->add_child(right, _right_eye->get_sort());
return root;
}
<commit_msg>fix stereo rendering in pview<commit_after>// Filename: stereoDisplayRegion.cxx
// Created by: drose (19Feb09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "stereoDisplayRegion.h"
#include "pandaNode.h"
TypeHandle StereoDisplayRegion::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::Constructor
// Access: Published
// Description:
////////////////////////////////////////////////////////////////////
StereoDisplayRegion::
StereoDisplayRegion(GraphicsOutput *window,
const LVecBase4 &dimensions,
DisplayRegion *left, DisplayRegion *right) :
DisplayRegion(window, dimensions),
_left_eye(left),
_right_eye(right)
{
nassertv(window == left->get_window() &&
window == right->get_window());
set_stereo_channel(Lens::SC_stereo);
set_sort(0);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::Destructor
// Access: Published, Virtual
// Description:
////////////////////////////////////////////////////////////////////
StereoDisplayRegion::
~StereoDisplayRegion() {
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_clear_active
// Access: Published, Virtual
// Description: Sets the clear-active flag for any bitplane.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_clear_active(int n, bool clear_active) {
// The clear_active flag gets set only on the parent, stereo display
// region.
DisplayRegion::set_clear_active(n, clear_active);
// Except for depth and stencil buffers. These also get set on the
// right display region by default, on the assumption that we want
// to clear these buffers between drawing the eyes, and that the
// right eye is the second of the pair.
switch (n) {
case RTP_stencil:
case RTP_depth_stencil:
case RTP_depth:
_right_eye->set_clear_active(n, clear_active);
break;
default:
break;
}
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_clear_value
// Access: Published, Virtual
// Description: Sets the clear value for any bitplane.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_clear_value(int n, const LColor &clear_value) {
DisplayRegion::set_clear_value(n, clear_value);
_left_eye->set_clear_value(n, clear_value);
_right_eye->set_clear_value(n, clear_value);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::disable_clears
// Access: Published, Virtual
// Description: Disables both the color and depth clear. See
// set_clear_color_active and set_clear_depth_active.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
disable_clears() {
DisplayRegion::disable_clears();
_left_eye->disable_clears();
_right_eye->disable_clears();
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_pixel_zoom
// Access: Published, Virtual
// Description: Sets the pixel_zoom for left and right eyes.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_pixel_zoom(PN_stdfloat pixel_zoom) {
DisplayRegion::set_pixel_zoom(pixel_zoom);
_left_eye->set_pixel_zoom(pixel_zoom);
_right_eye->set_pixel_zoom(pixel_zoom);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_dimensions
// Access: Published, Virtual
// Description: Sets both the left and right DisplayRegions to the
// indicated dimensions.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_dimensions(const LVecBase4 &dimensions) {
DisplayRegion::set_dimensions(dimensions);
_left_eye->set_dimensions(dimensions);
_right_eye->set_dimensions(dimensions);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::is_stereo
// Access: Published, Virtual
// Description: Returns true if this is a StereoDisplayRegion, false
// otherwise.
////////////////////////////////////////////////////////////////////
bool StereoDisplayRegion::
is_stereo() const {
return true;
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_camera
// Access: Published, Virtual
// Description: Sets both the left and right DisplayRegions to the
// indicated camera.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_camera(const NodePath &camera) {
DisplayRegion::set_camera(camera);
_left_eye->set_camera(camera);
_right_eye->set_camera(camera);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_active
// Access: Published, Virtual
// Description: Sets the active flag on both the left and right
// DisplayRegions to the indicated value.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_active(bool active) {
DisplayRegion::set_active(active);
_left_eye->set_active(active);
_right_eye->set_active(active);
if (active) {
// Reenable the appropriate eyes according to our stereo_channel
// setting.
set_stereo_channel(get_stereo_channel());
}
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_sort
// Access: Published, Virtual
// Description: Sets the indicated sort value on the overall
// DisplayRegion, the indicated sort value + 1 on the
// left eye, and the indicated sort value + 2 on the
// right eye.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_sort(int sort) {
DisplayRegion::set_sort(sort);
_left_eye->set_sort(sort + 1);
_right_eye->set_sort(sort + 2);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_stereo_channel
// Access: Published, Virtual
// Description: Sets the stereo channels on the left and right eyes,
// and also sets the active flags independently on both
// eyes. For a StereoDisplayRegion, a different action
// is performed for each different value:
//
// SC_stereo - the left eye is set to SC_left, the right
// eye to SC_right, and both eyes are activated.
//
// SC_left - the left eye is set to SC_left and
// activated; the right eye is deactivated.
//
// SC_right - the right eye is set to SC_right and
// activated; the left eye is deactivated.
//
// SC_mono - the left eye is set to SC_mono and
// activated; the right eye is deactivated.
//
// This call also resets tex_view_offset to its default
// value, which is 0 for the left eye or 1 for the right
// eye of a stereo display region, or 0 for a mono
// display region.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_stereo_channel(Lens::StereoChannel stereo_channel) {
DisplayRegion::set_stereo_channel(stereo_channel);
if (!is_active()) {
return;
}
switch (stereo_channel) {
case Lens::SC_stereo:
_left_eye->set_stereo_channel(Lens::SC_left);
_left_eye->set_active(true);
_right_eye->set_stereo_channel(Lens::SC_right);
_right_eye->set_active(true);
break;
case Lens::SC_left:
_left_eye->set_stereo_channel(Lens::SC_left);
_left_eye->set_active(true);
_right_eye->set_active(false);
break;
case Lens::SC_right:
_left_eye->set_active(false);
_right_eye->set_stereo_channel(Lens::SC_right);
_right_eye->set_active(true);
break;
case Lens::SC_mono:
_left_eye->set_stereo_channel(Lens::SC_mono);
_left_eye->set_active(true);
_right_eye->set_active(false);
break;
}
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_tex_view_offset
// Access: Published, Virtual
// Description: Sets the current texture view offset for this
// DisplayRegion. This is normally set to zero. If
// nonzero, it is used to select a particular view of
// any multiview textures that are rendered within this
// DisplayRegion.
//
// When you call this on a StereoDisplayRegion, it
// automatically sets the specified value on the left
// eye, and the specified value + 1 on the right eye.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_tex_view_offset(int tex_view_offset) {
DisplayRegion::set_tex_view_offset(tex_view_offset);
_left_eye->set_tex_view_offset(tex_view_offset);
_right_eye->set_tex_view_offset(tex_view_offset + 1);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_incomplete_render
// Access: Published, Virtual
// Description: Sets the incomplete_render flag on both the left and
// right DisplayRegions to the indicated value.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_incomplete_render(bool incomplete_render) {
DisplayRegion::set_incomplete_render(incomplete_render);
_left_eye->set_incomplete_render(incomplete_render);
_right_eye->set_incomplete_render(incomplete_render);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_texture_reload_priority
// Access: Published, Virtual
// Description: Sets the texture_reload_priority on both the left and
// right DisplayRegions to the indicated value.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_texture_reload_priority(int texture_reload_priority) {
DisplayRegion::set_texture_reload_priority(texture_reload_priority);
_left_eye->set_texture_reload_priority(texture_reload_priority);
_right_eye->set_texture_reload_priority(texture_reload_priority);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_cull_traverser
// Access: Published, Virtual
// Description: Sets the CullTraverser for both the left and right
// DisplayRegions.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_cull_traverser(CullTraverser *trav) {
DisplayRegion::set_cull_traverser(trav);
_left_eye->set_cull_traverser(trav);
_right_eye->set_cull_traverser(trav);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::set_cube_map_index
// Access: Published, Virtual
// Description: Sets the cube_map_index on both the left and
// right DisplayRegions to the indicated value.
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
set_cube_map_index(int cube_map_index) {
DisplayRegion::set_cube_map_index(cube_map_index);
_left_eye->set_cube_map_index(cube_map_index);
_right_eye->set_cube_map_index(cube_map_index);
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::output
// Access: Published, Virtual
// Description:
////////////////////////////////////////////////////////////////////
void StereoDisplayRegion::
output(ostream &out) const {
out << "StereoDisplayRegion(" << *_left_eye << ")";
}
////////////////////////////////////////////////////////////////////
// Function: StereoDisplayRegion::make_cull_result_graph
// Access: Published, Virtual
// Description: Returns a special scene graph constructed to
// represent the results of the last frame's cull
// operation.
////////////////////////////////////////////////////////////////////
PT(PandaNode) StereoDisplayRegion::
make_cull_result_graph() {
PT(PandaNode) root = new PandaNode("stereo");
PT(PandaNode) left = _left_eye->make_cull_result_graph();
left->set_name("left");
root->add_child(left, _left_eye->get_sort());
PT(PandaNode) right = _right_eye->make_cull_result_graph();
right->set_name("right");
root->add_child(right, _right_eye->get_sort());
return root;
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2019, John Haddon. 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 John Haddon nor the names of
// any other contributors to this software 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 "GafferUI/AnnotationsGadget.h"
#include "GafferUI/GraphGadget.h"
#include "GafferUI/ImageGadget.h"
#include "GafferUI/NodeGadget.h"
#include "GafferUI/Style.h"
#include "Gaffer/Metadata.h"
#include "Gaffer/MetadataAlgo.h"
#include "boost/algorithm/string/predicate.hpp"
#include "boost/bind.hpp"
#include "boost/bind/placeholders.hpp"
using namespace GafferUI;
using namespace Gaffer;
using namespace IECore;
using namespace Imath;
using namespace std;
//////////////////////////////////////////////////////////////////////////
// Internal utilities
//////////////////////////////////////////////////////////////////////////
namespace
{
Box2f nodeFrame( const NodeGadget *nodeGadget )
{
const Box3f b = nodeGadget->transformedBound( nullptr );
return Box2f(
V2f( b.min.x, b.min.y ),
V2f( b.max.x, b.max.y )
);
}
IECoreGL::Texture *bookmarkTexture()
{
static IECoreGL::TexturePtr bookmarkTexture;
if( !bookmarkTexture )
{
bookmarkTexture = ImageGadget::textureLoader()->load( "bookmarkStar2.png" );
IECoreGL::Texture::ScopedBinding binding( *bookmarkTexture );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER );
}
return bookmarkTexture.get();
}
IECoreGL::Texture *numericBookmarkTexture()
{
static IECoreGL::TexturePtr numericBookmarkTexture;
if( !numericBookmarkTexture )
{
numericBookmarkTexture = ImageGadget::textureLoader()->load( "bookmarkStar.png" );
IECoreGL::Texture::ScopedBinding binding( *numericBookmarkTexture );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER );
}
return numericBookmarkTexture.get();
}
float g_offset = 0.5;
float g_borderWidth = 0.5;
float g_spacing = 0.25;
} // namespace
//////////////////////////////////////////////////////////////////////////
// AnnotationsGadget
//////////////////////////////////////////////////////////////////////////
GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( AnnotationsGadget );
AnnotationsGadget::AnnotationsGadget()
: Gadget( "AnnotationsGadget" )
{
Metadata::nodeValueChangedSignal().connect(
boost::bind( &AnnotationsGadget::nodeMetadataChanged, this, ::_1, ::_2, ::_3 )
);
}
AnnotationsGadget::~AnnotationsGadget()
{
}
bool AnnotationsGadget::acceptsParent( const GraphComponent *potentialParent ) const
{
return runTimeCast<const GraphGadget>( potentialParent );
}
void AnnotationsGadget::parentChanging( Gaffer::GraphComponent *newParent )
{
m_annotations.clear();
m_graphGadgetChildAddedConnection.disconnect();
m_graphGadgetChildRemovedConnection.disconnect();
if( newParent )
{
m_graphGadgetChildAddedConnection = newParent->childAddedSignal().connect(
boost::bind( &AnnotationsGadget::graphGadgetChildAdded, this, ::_2 )
);
m_graphGadgetChildRemovedConnection = newParent->childRemovedSignal().connect(
boost::bind( &AnnotationsGadget::graphGadgetChildRemoved, this, ::_2 )
);
}
}
void AnnotationsGadget::doRenderLayer( Layer layer, const Style *style ) const
{
if( layer != GraphLayer::Overlay )
{
return;
}
vector<string> names;
for( auto &ga : m_annotations )
{
const Node *node = ga.first->node();
Annotations &annotations = ga.second;
if( annotations.dirty )
{
annotations.renderable = false;
annotations.bookmarked = Gaffer::MetadataAlgo::getBookmarked( node );
annotations.renderable |= annotations.bookmarked;
if( int bookmark = MetadataAlgo::numericBookmark( node ) )
{
annotations.numericBookmark = std::to_string( bookmark );
annotations.renderable = true;
}
else
{
annotations.numericBookmark = InternedString();
}
annotations.standardAnnotations.clear();
names.clear();
MetadataAlgo::annotations( node, names );
for( const auto &name : names )
{
annotations.standardAnnotations.push_back(
MetadataAlgo::getAnnotation( node, name, /* inheritTemplate = */ true )
);
}
annotations.renderable |= (bool)annotations.standardAnnotations.size();
annotations.dirty = false;
}
if( !annotations.renderable )
{
continue;
}
const Box2f b = nodeFrame( ga.first );
if( annotations.bookmarked )
{
style->renderImage( Box2f( V2f( b.min.x - 1.0, b.max.y - 1.0 ), V2f( b.min.x + 1.0, b.max.y + 1.0 ) ), bookmarkTexture() );
}
if( annotations.numericBookmark.string().size() )
{
if( !annotations.bookmarked )
{
style->renderImage( Box2f( V2f( b.min.x - 1.0, b.max.y - 1.0 ), V2f( b.min.x + 1.0, b.max.y + 1.0 ) ), numericBookmarkTexture() );
}
const Box3f textBounds = style->textBound( Style::LabelText, annotations.numericBookmark.string() );
const Imath::Color4f textColor( 1.0f );
glPushMatrix();
IECoreGL::glTranslate( V2f( b.min.x + 1.0 - textBounds.size().x * 0.5, b.max.y - textBounds.size().y * 0.5 - 0.7 ) );
style->renderText( Style::BodyText, annotations.numericBookmark.string(), Style::NormalState, &textColor );
glPopMatrix();
}
if( annotations.standardAnnotations.size() )
{
glPushMatrix();
IECoreGL::glTranslate( V2f( b.max.x + g_offset + g_borderWidth, b.max.y - g_borderWidth ) );
const Color4f midGrey( 0.65, 0.65, 0.65, 1.0 );
float previousHeight = 0;
for( const auto &a : annotations.standardAnnotations )
{
Box3f textBounds = style->textBound( Style::BodyText, a.text() );
float yOffset;
if( &a == &annotations.standardAnnotations.front() )
{
yOffset = -style->characterBound( Style::BodyText ).max.y;
}
else
{
yOffset = -previousHeight -g_spacing;
}
IECoreGL::glTranslate( V2f( 0, yOffset ) );
/// \todo We're using `renderNodeFrame()` because it's the only way we can specify a colour,
/// but really we want `renderFrame()` to provide that option. Or we could consider having
/// explicit annotation rendering methods in the Style class.
style->renderNodeFrame(
Box2f( V2f( 0, textBounds.min.y ), V2f( textBounds.max.x, textBounds.max.y ) ),
g_borderWidth, Style::NormalState,
&a.color()
);
style->renderText( Style::BodyText, a.text(), Style::NormalState, &midGrey );
previousHeight = textBounds.size().y + g_borderWidth * 2;
}
glPopMatrix();
}
}
}
GraphGadget *AnnotationsGadget::graphGadget()
{
return parent<GraphGadget>();
}
const GraphGadget *AnnotationsGadget::graphGadget() const
{
return parent<GraphGadget>();
}
void AnnotationsGadget::graphGadgetChildAdded( GraphComponent *child )
{
if( NodeGadget *nodeGadget = runTimeCast<NodeGadget>( child ) )
{
m_annotations[nodeGadget] = Annotations();
}
}
void AnnotationsGadget::graphGadgetChildRemoved( const GraphComponent *child )
{
if( const NodeGadget *nodeGadget = runTimeCast<const NodeGadget>( child ) )
{
m_annotations.erase( nodeGadget );
}
}
void AnnotationsGadget::nodeMetadataChanged( IECore::TypeId nodeTypeId, IECore::InternedString key, Gaffer::Node *node )
{
if( !node )
{
// We only expect annotations to be registered
// as per-instance metadate.
return;
}
if(
!MetadataAlgo::bookmarkedAffectedByChange( key ) &&
!MetadataAlgo::numericBookmarkAffectedByChange( key ) &&
!boost::starts_with( key.c_str(), "annotation:" )
)
{
return;
}
if( auto gadget = graphGadget()->nodeGadget( node ) )
{
auto it = m_annotations.find( gadget );
assert( it != m_annotations.end() );
it->second.dirty = true;
dirty( DirtyType::Render );
}
}
<commit_msg>AnnotationsGadget : Improve legibility of text on bright backgrounds<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2019, John Haddon. 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 John Haddon nor the names of
// any other contributors to this software 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 "GafferUI/AnnotationsGadget.h"
#include "GafferUI/GraphGadget.h"
#include "GafferUI/ImageGadget.h"
#include "GafferUI/NodeGadget.h"
#include "GafferUI/Style.h"
#include "Gaffer/Metadata.h"
#include "Gaffer/MetadataAlgo.h"
#include "boost/algorithm/string/predicate.hpp"
#include "boost/bind.hpp"
#include "boost/bind/placeholders.hpp"
using namespace GafferUI;
using namespace Gaffer;
using namespace IECore;
using namespace Imath;
using namespace std;
//////////////////////////////////////////////////////////////////////////
// Internal utilities
//////////////////////////////////////////////////////////////////////////
namespace
{
Box2f nodeFrame( const NodeGadget *nodeGadget )
{
const Box3f b = nodeGadget->transformedBound( nullptr );
return Box2f(
V2f( b.min.x, b.min.y ),
V2f( b.max.x, b.max.y )
);
}
IECoreGL::Texture *bookmarkTexture()
{
static IECoreGL::TexturePtr bookmarkTexture;
if( !bookmarkTexture )
{
bookmarkTexture = ImageGadget::textureLoader()->load( "bookmarkStar2.png" );
IECoreGL::Texture::ScopedBinding binding( *bookmarkTexture );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER );
}
return bookmarkTexture.get();
}
IECoreGL::Texture *numericBookmarkTexture()
{
static IECoreGL::TexturePtr numericBookmarkTexture;
if( !numericBookmarkTexture )
{
numericBookmarkTexture = ImageGadget::textureLoader()->load( "bookmarkStar.png" );
IECoreGL::Texture::ScopedBinding binding( *numericBookmarkTexture );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER );
}
return numericBookmarkTexture.get();
}
float luminance( const Color3f &c )
{
return c.dot( V3f( 0.2126, 0.7152, 0.0722 ) );
}
float g_offset = 0.5;
float g_borderWidth = 0.5;
float g_spacing = 0.25;
} // namespace
//////////////////////////////////////////////////////////////////////////
// AnnotationsGadget
//////////////////////////////////////////////////////////////////////////
GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( AnnotationsGadget );
AnnotationsGadget::AnnotationsGadget()
: Gadget( "AnnotationsGadget" )
{
Metadata::nodeValueChangedSignal().connect(
boost::bind( &AnnotationsGadget::nodeMetadataChanged, this, ::_1, ::_2, ::_3 )
);
}
AnnotationsGadget::~AnnotationsGadget()
{
}
bool AnnotationsGadget::acceptsParent( const GraphComponent *potentialParent ) const
{
return runTimeCast<const GraphGadget>( potentialParent );
}
void AnnotationsGadget::parentChanging( Gaffer::GraphComponent *newParent )
{
m_annotations.clear();
m_graphGadgetChildAddedConnection.disconnect();
m_graphGadgetChildRemovedConnection.disconnect();
if( newParent )
{
m_graphGadgetChildAddedConnection = newParent->childAddedSignal().connect(
boost::bind( &AnnotationsGadget::graphGadgetChildAdded, this, ::_2 )
);
m_graphGadgetChildRemovedConnection = newParent->childRemovedSignal().connect(
boost::bind( &AnnotationsGadget::graphGadgetChildRemoved, this, ::_2 )
);
}
}
void AnnotationsGadget::doRenderLayer( Layer layer, const Style *style ) const
{
if( layer != GraphLayer::Overlay )
{
return;
}
vector<string> names;
for( auto &ga : m_annotations )
{
const Node *node = ga.first->node();
Annotations &annotations = ga.second;
if( annotations.dirty )
{
annotations.renderable = false;
annotations.bookmarked = Gaffer::MetadataAlgo::getBookmarked( node );
annotations.renderable |= annotations.bookmarked;
if( int bookmark = MetadataAlgo::numericBookmark( node ) )
{
annotations.numericBookmark = std::to_string( bookmark );
annotations.renderable = true;
}
else
{
annotations.numericBookmark = InternedString();
}
annotations.standardAnnotations.clear();
names.clear();
MetadataAlgo::annotations( node, names );
for( const auto &name : names )
{
annotations.standardAnnotations.push_back(
MetadataAlgo::getAnnotation( node, name, /* inheritTemplate = */ true )
);
}
annotations.renderable |= (bool)annotations.standardAnnotations.size();
annotations.dirty = false;
}
if( !annotations.renderable )
{
continue;
}
const Box2f b = nodeFrame( ga.first );
if( annotations.bookmarked )
{
style->renderImage( Box2f( V2f( b.min.x - 1.0, b.max.y - 1.0 ), V2f( b.min.x + 1.0, b.max.y + 1.0 ) ), bookmarkTexture() );
}
if( annotations.numericBookmark.string().size() )
{
if( !annotations.bookmarked )
{
style->renderImage( Box2f( V2f( b.min.x - 1.0, b.max.y - 1.0 ), V2f( b.min.x + 1.0, b.max.y + 1.0 ) ), numericBookmarkTexture() );
}
const Box3f textBounds = style->textBound( Style::LabelText, annotations.numericBookmark.string() );
const Imath::Color4f textColor( 1.0f );
glPushMatrix();
IECoreGL::glTranslate( V2f( b.min.x + 1.0 - textBounds.size().x * 0.5, b.max.y - textBounds.size().y * 0.5 - 0.7 ) );
style->renderText( Style::BodyText, annotations.numericBookmark.string(), Style::NormalState, &textColor );
glPopMatrix();
}
if( annotations.standardAnnotations.size() )
{
glPushMatrix();
IECoreGL::glTranslate( V2f( b.max.x + g_offset + g_borderWidth, b.max.y - g_borderWidth ) );
const Color4f darkGrey( 0.1, 0.1, 0.1, 1.0 );
const Color4f midGrey( 0.65, 0.65, 0.65, 1.0 );
float previousHeight = 0;
for( const auto &a : annotations.standardAnnotations )
{
Box3f textBounds = style->textBound( Style::BodyText, a.text() );
float yOffset;
if( &a == &annotations.standardAnnotations.front() )
{
yOffset = -style->characterBound( Style::BodyText ).max.y;
}
else
{
yOffset = -previousHeight -g_spacing;
}
IECoreGL::glTranslate( V2f( 0, yOffset ) );
/// \todo We're using `renderNodeFrame()` because it's the only way we can specify a colour,
/// but really we want `renderFrame()` to provide that option. Or we could consider having
/// explicit annotation rendering methods in the Style class.
style->renderNodeFrame(
Box2f( V2f( 0, textBounds.min.y ), V2f( textBounds.max.x, textBounds.max.y ) ),
g_borderWidth, Style::NormalState,
&a.color()
);
style->renderText(
Style::BodyText, a.text(), Style::NormalState,
luminance( a.color() ) > 0.4 ? &darkGrey : &midGrey
);
previousHeight = textBounds.size().y + g_borderWidth * 2;
}
glPopMatrix();
}
}
}
GraphGadget *AnnotationsGadget::graphGadget()
{
return parent<GraphGadget>();
}
const GraphGadget *AnnotationsGadget::graphGadget() const
{
return parent<GraphGadget>();
}
void AnnotationsGadget::graphGadgetChildAdded( GraphComponent *child )
{
if( NodeGadget *nodeGadget = runTimeCast<NodeGadget>( child ) )
{
m_annotations[nodeGadget] = Annotations();
}
}
void AnnotationsGadget::graphGadgetChildRemoved( const GraphComponent *child )
{
if( const NodeGadget *nodeGadget = runTimeCast<const NodeGadget>( child ) )
{
m_annotations.erase( nodeGadget );
}
}
void AnnotationsGadget::nodeMetadataChanged( IECore::TypeId nodeTypeId, IECore::InternedString key, Gaffer::Node *node )
{
if( !node )
{
// We only expect annotations to be registered
// as per-instance metadate.
return;
}
if(
!MetadataAlgo::bookmarkedAffectedByChange( key ) &&
!MetadataAlgo::numericBookmarkAffectedByChange( key ) &&
!boost::starts_with( key.c_str(), "annotation:" )
)
{
return;
}
if( auto gadget = graphGadget()->nodeGadget( node ) )
{
auto it = m_annotations.find( gadget );
assert( it != m_annotations.end() );
it->second.dirty = true;
dirty( DirtyType::Render );
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkQtChartSeriesModelRange.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
/// \file vtkQtChartSeriesModelRange.cxx
/// \date February 19, 2008
#ifdef _MSC_VER
// Disable warnings that Qt headers give.
#pragma warning(disable:4127)
#endif
#include "vtkQtChartSeriesModelRange.h"
#include "vtkQtChartSeriesModel.h"
#include <QDate>
#include <QDateTime>
#include <QTime>
vtkQtChartSeriesModelRange::vtkQtChartSeriesModelRange(QObject *parentObject)
: QObject(parentObject)
{
this->Model = 0;
this->XRangeShared = false;
}
void vtkQtChartSeriesModelRange::setModel(vtkQtChartSeriesModel *model,
bool xShared)
{
if(this->Model != model)
{
if(this->Model)
{
this->disconnect(this->Model, 0, this, 0);
}
this->Model = model;
if(this->Model)
{
// Use the series change signals to update the ranges.
this->connect(this->Model, SIGNAL(modelReset()),
this, SLOT(resetSeries()));
this->connect(this->Model, SIGNAL(seriesInserted(int, int)),
this, SLOT(insertSeries(int, int)));
this->connect(this->Model, SIGNAL(seriesRemoved(int, int)),
this, SLOT(removeSeries(int, int)));
}
this->XRangeShared = xShared;
this->resetSeries();
}
else if(this->XRangeShared != xShared)
{
this->XRangeShared = xShared;
this->resetSeries();
}
}
QList<QVariant> vtkQtChartSeriesModelRange::getSeriesRange(int series,
int component) const
{
if(series >= 0 && series < this->Range[1].size())
{
if(component == 0 && this->XRangeShared)
{
series = 0;
}
return this->Range[component][series];
}
return QList<QVariant>();
}
void vtkQtChartSeriesModelRange::resetSeries()
{
// Clean up the range information.
this->Range[0].clear();
this->Range[1].clear();
// Add the new model series.
if(this->Model)
{
int total = this->Model->getNumberOfSeries();
if(total > 0)
{
this->insertSeries(0, total - 1);
}
}
}
void vtkQtChartSeriesModelRange::insertSeries(int first, int last)
{
if(this->Model)
{
// Add range entries for the series.
if(this->XRangeShared && this->Range[1].size() == 0)
{
this->Range[0].append(this->computeSeriesRange(0, 0));
}
for( ; first <= last; first++)
{
this->Range[1].insert(first, this->computeSeriesRange(first, 1));
if(!this->XRangeShared)
{
this->Range[0].insert(first, this->computeSeriesRange(first, 0));
}
}
}
}
void vtkQtChartSeriesModelRange::removeSeries(int first, int last)
{
// Remove range entries for the series.
for( ; last >= first; last--)
{
this->Range[1].removeAt(last);
if(!this->XRangeShared)
{
this->Range[0].removeAt(last);
}
}
if(this->XRangeShared && this->Range[1].size() == 0)
{
this->Range[0].clear();
}
}
QList<QVariant> vtkQtChartSeriesModelRange::computeSeriesRange(int series,
int component)
{
QList<QVariant> range;
if(this->Model)
{
int total = this->Model->getNumberOfSeriesValues(series);
if(total > 0)
{
// Use the first value to determine the type.
QVariant value = this->Model->getSeriesValue(series, 0, component);
QVariant::Type valueType = value.type();
if(valueType == QVariant::String)
{
return range;
}
range.append(value);
range.append(value);
for(int i = 1; i < total; i++)
{
value = this->Model->getSeriesValue(series, i, component);
if(value.type() != valueType)
{
continue;
}
if(valueType == QVariant::Int)
{
range[0] = qMin<int>(value.toInt(), range[0].toInt());
range[1] = qMax<int>(value.toInt(), range[1].toInt());
}
else if(valueType == QVariant::Double)
{
range[0] = qMin<double>(value.toDouble(), range[0].toDouble());
range[1] = qMax<double>(value.toDouble(), range[1].toDouble());
}
else if(valueType == QVariant::Date)
{
range[0] = qMin<QDate>(value.toDate(), range[0].toDate());
range[1] = qMax<QDate>(value.toDate(), range[1].toDate());
}
else if(valueType == QVariant::DateTime)
{
range[0] = qMin<QDateTime>(value.toDateTime(),
range[0].toDateTime());
range[1] = qMax<QDateTime>(value.toDateTime(),
range[1].toDateTime());
}
else if(valueType == QVariant::Time)
{
range[0] = qMin<QTime>(value.toTime(), range[0].toTime());
range[1] = qMax<QTime>(value.toTime(), range[1].toTime());
}
}
}
}
return range;
}
<commit_msg>ENH: Committing following patches from CVS Head: * ENH: Correctly handle range of data with NaN in it. * COMP: Suppress warning about uninitialized variable (which never actually happens).<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkQtChartSeriesModelRange.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
/// \file vtkQtChartSeriesModelRange.cxx
/// \date February 19, 2008
#ifdef _MSC_VER
// Disable warnings that Qt headers give.
#pragma warning(disable:4127)
#endif
#include "vtkQtChartSeriesModelRange.h"
#include "vtkQtChartSeriesModel.h"
#include <QDate>
#include <QDateTime>
#include <QTime>
#include <math.h>
#ifndef isnan
// This is compiler specific not platform specific: MinGW doesn't need that.
# if defined(_MSC_VER) || defined(__BORLANDC__)
# include <float.h>
# define isnan(x) _isnan(x)
# endif
#endif
vtkQtChartSeriesModelRange::vtkQtChartSeriesModelRange(QObject *parentObject)
: QObject(parentObject)
{
this->Model = 0;
this->XRangeShared = false;
}
void vtkQtChartSeriesModelRange::setModel(vtkQtChartSeriesModel *model,
bool xShared)
{
if(this->Model != model)
{
if(this->Model)
{
this->disconnect(this->Model, 0, this, 0);
}
this->Model = model;
if(this->Model)
{
// Use the series change signals to update the ranges.
this->connect(this->Model, SIGNAL(modelReset()),
this, SLOT(resetSeries()));
this->connect(this->Model, SIGNAL(seriesInserted(int, int)),
this, SLOT(insertSeries(int, int)));
this->connect(this->Model, SIGNAL(seriesRemoved(int, int)),
this, SLOT(removeSeries(int, int)));
}
this->XRangeShared = xShared;
this->resetSeries();
}
else if(this->XRangeShared != xShared)
{
this->XRangeShared = xShared;
this->resetSeries();
}
}
QList<QVariant> vtkQtChartSeriesModelRange::getSeriesRange(int series,
int component) const
{
if(series >= 0 && series < this->Range[1].size())
{
if(component == 0 && this->XRangeShared)
{
series = 0;
}
return this->Range[component][series];
}
return QList<QVariant>();
}
void vtkQtChartSeriesModelRange::resetSeries()
{
// Clean up the range information.
this->Range[0].clear();
this->Range[1].clear();
// Add the new model series.
if(this->Model)
{
int total = this->Model->getNumberOfSeries();
if(total > 0)
{
this->insertSeries(0, total - 1);
}
}
}
void vtkQtChartSeriesModelRange::insertSeries(int first, int last)
{
if(this->Model)
{
// Add range entries for the series.
if(this->XRangeShared && this->Range[1].size() == 0)
{
this->Range[0].append(this->computeSeriesRange(0, 0));
}
for( ; first <= last; first++)
{
this->Range[1].insert(first, this->computeSeriesRange(first, 1));
if(!this->XRangeShared)
{
this->Range[0].insert(first, this->computeSeriesRange(first, 0));
}
}
}
}
void vtkQtChartSeriesModelRange::removeSeries(int first, int last)
{
// Remove range entries for the series.
for( ; last >= first; last--)
{
this->Range[1].removeAt(last);
if(!this->XRangeShared)
{
this->Range[0].removeAt(last);
}
}
if(this->XRangeShared && this->Range[1].size() == 0)
{
this->Range[0].clear();
}
}
QList<QVariant> vtkQtChartSeriesModelRange::computeSeriesRange(int series,
int component)
{
QList<QVariant> range;
if(this->Model)
{
int total = this->Model->getNumberOfSeriesValues(series);
int i;
QVariant value;
QVariant::Type valueType = QVariant::Invalid;
// Find the first non-NULL, non-NaN value. Use it to determine type
// and initialize min/max values.
for (i = 0; i < total; i++)
{
value = this->Model->getSeriesValue(series, i, component);
valueType = value.type();
// Check to see if the the value is invalid and we have to continue loop.
if (value.isNull()) continue;
if (!value.isValid()) continue;
if ((valueType == QVariant::Double) && isnan(value.toDouble())) continue;
// If we got here, we passed all the checks. Break out.
break;
}
// If we found a valid entry that is not a string (for which range has no
// meaning), then continue to compute the range.
if ((i < total) && (valueType != QVariant::String))
{
range.append(value);
range.append(value);
// Continue iteration over values.
for(i++; i < total; i++)
{
value = this->Model->getSeriesValue(series, i, component);
if(value.type() != valueType)
{
continue;
}
if(valueType == QVariant::Int)
{
range[0] = qMin<int>(value.toInt(), range[0].toInt());
range[1] = qMax<int>(value.toInt(), range[1].toInt());
}
else if(valueType == QVariant::Double)
{
if (!isnan(value.toDouble()))
{
range[0] = qMin<double>(value.toDouble(), range[0].toDouble());
range[1] = qMax<double>(value.toDouble(), range[1].toDouble());
}
}
else if(valueType == QVariant::Date)
{
range[0] = qMin<QDate>(value.toDate(), range[0].toDate());
range[1] = qMax<QDate>(value.toDate(), range[1].toDate());
}
else if(valueType == QVariant::DateTime)
{
range[0] = qMin<QDateTime>(value.toDateTime(),
range[0].toDateTime());
range[1] = qMax<QDateTime>(value.toDateTime(),
range[1].toDateTime());
}
else if(valueType == QVariant::Time)
{
range[0] = qMin<QTime>(value.toTime(), range[0].toTime());
range[1] = qMax<QTime>(value.toTime(), range[1].toTime());
}
}
}
}
return range;
}
<|endoftext|>
|
<commit_before>#include "augs/templates/container_templates.h"
#include "augs/audio/sound_buffer.h"
#include "game/transcendental/cosmos.h"
#include "game/transcendental/entity_handle.h"
#include "game/transcendental/data_living_one_step.h"
#include "game/messages/start_sound_effect.h"
#include "game/components/interpolation_component.h"
#include "game/components/fixtures_component.h"
#include "view/audiovisual_state/systems/interpolation_system.h"
#include "view/audiovisual_state/systems/sound_system.h"
#include "view/viewables/loaded_sounds.h"
#include "augs/audio/audio_settings.h"
entity_id get_target_if_any(const absolute_or_local& l) {
if (const auto chasing = std::get_if<orbital_chasing>(&l)) {
return chasing->target;
}
return {};
}
void sound_system::clear() {
short_sounds.clear();
fading_sources.clear();
}
void sound_system::clear_sources_playing(const assets::sound_buffer_id id) {
erase_if(fading_sources, [id](fading_source& source) {
return id == source.id;
});
erase_if(short_sounds, [id](short_sound_cache& it) {
return id == it.original_effect.id;
});
}
void sound_system::clear_dead_entities(const cosmos& new_cosmos) {
erase_if(short_sounds, [&](short_sound_cache& it) {
if (new_cosmos[get_target_if_any(it.positioning)].dead()) {
if (!it.previous_transform) {
return true;
}
it.positioning = *it.previous_transform;
}
return false;
});
}
void sound_system::update_listener(
const const_entity_handle listener,
const interpolation_system& sys
) {
const auto si = listener.get_cosmos().get_si();
const auto listener_pos = listener.get_viewing_transform(sys).pos;
augs::set_listener_position(si, listener_pos);
augs::set_listener_velocity(si, listener.get_effective_velocity());
augs::set_listener_orientation({ 0.f, -1.f, 0.f, 0.f, 0.f, -1.f });
}
void sound_system::update_effects_from_messages(
const_logic_step step,
const loaded_sounds& manager,
const interpolation_system& interp,
const viewer_eye ear
) {
const auto listening_character = ear.viewed_character;
const auto& cosmos = listening_character.get_cosmos();
const auto si = cosmos.get_si();
{
const auto& events = step.get_queue<messages::stop_sound_effect>();
for (auto& e : events) {
erase_if(short_sounds, [&](short_sound_cache& c){
if (const auto m = e.match_chased_subject) {
if (*m != get_target_if_any(c.positioning)) {
return false;
}
}
if (const auto m = e.match_effect_id) {
if (*m != c.original_effect.id) {
return false;
}
}
if (const auto& effect = c.original_effect;
effect.modifier.fade_on_exit
) {
auto& source = c.source;
if (source.is_playing()) {
fading_sources.push_back({ effect.id, std::move(source) });
}
}
return true;
});
}
}
const auto& events = step.get_queue<messages::start_sound_effect>();
for (auto& e : events) {
short_sounds.emplace_back();
auto& cache = short_sounds.back();
cache.original_effect = e.effect;
cache.original_start = e.start;
cache.positioning = e.start.positioning;
cache.previous_transform = find_transform(e.start.positioning, cosmos, interp);
auto& source = cache.source;
{
const auto effect_id = e.effect.id;
const auto& variations = manager.at(effect_id).variations;
const auto chosen_variation = e.start.variation_number % variations.size();
const auto& buffer = variations[chosen_variation];
const bool is_direct_listener = listening_character == e.start.direct_listener;
const auto& requested_buf =
is_direct_listener ? buffer.stereo_or_mono() : buffer.mono_or_stereo()
;
source.bind_buffer(requested_buf);
source.set_direct_channels(is_direct_listener);
}
source.play();
const auto& modifier = e.effect.modifier;
source.set_max_distance(si, modifier.max_distance);
source.set_reference_distance(si, modifier.reference_distance);
source.set_looping(modifier.repetitions == -1);
}
}
void sound_system::update_sound_properties(
const augs::audio_volume_settings& settings,
const loaded_sounds& manager,
const interpolation_system& interp,
const viewer_eye ear,
const augs::delta dt
) {
#if 0
auto queried_size = cone.visible_world_area;
queried_size.set(10000.f, 10000.f);
#endif
const auto listening_character = ear.viewed_character;
update_listener(listening_character, interp);
const auto& cosmos = listening_character.get_cosmos();
const auto si = cosmos.get_si();
const auto listener_pos = listening_character.get_viewing_transform(interp).pos;
erase_if(short_sounds, [&](short_sound_cache& cache) {
const auto& positioning = cache.positioning;
const auto maybe_transform = find_transform(positioning, cosmos, interp);
auto& source = cache.source;
if (!maybe_transform) {
source.set_gain(0.f);
}
const auto current_transform = *maybe_transform;
{
const auto dist_from_listener = (listener_pos - current_transform.pos).length();
const float absorption = std::min(10.f, static_cast<float>(pow(std::max(0.f, dist_from_listener - 2220.f)/520.f, 2)));
source.set_air_absorption_factor(absorption);
}
{
if (cache.previous_transform) {
const auto displacement = current_transform - *cache.previous_transform;
cache.previous_transform = current_transform;
const auto effective_velocity = displacement.pos * dt.in_seconds();
source.set_velocity(si, effective_velocity);
}
}
const auto& input = cache.original_effect;
source.set_pitch(input.modifier.pitch);
source.set_gain(input.modifier.gain * settings.sound_effects);
source.set_position(si, current_transform.pos);
return !source.is_playing();
});
}
void sound_system::fade_sources(const augs::delta dt) {
erase_if(fading_sources, [dt](fading_source& f) {
auto& source = f.source;
const auto new_gain = source.get_gain() - dt.in_seconds()*3.f;
const auto new_pitch = source.get_pitch() - dt.in_seconds()/3.f;
if (new_pitch > 0.1f) {
source.set_pitch(new_pitch);
}
if (new_gain > 0.f) {
source.set_gain(new_gain);
return false;
}
return true;
});
}
<commit_msg>guarding for nonexistent sound effects<commit_after>#include "augs/templates/container_templates.h"
#include "augs/audio/sound_buffer.h"
#include "game/transcendental/cosmos.h"
#include "game/transcendental/entity_handle.h"
#include "game/transcendental/data_living_one_step.h"
#include "game/messages/start_sound_effect.h"
#include "game/components/interpolation_component.h"
#include "game/components/fixtures_component.h"
#include "view/audiovisual_state/systems/interpolation_system.h"
#include "view/audiovisual_state/systems/sound_system.h"
#include "view/viewables/loaded_sounds.h"
#include "augs/audio/audio_settings.h"
entity_id get_target_if_any(const absolute_or_local& l) {
if (const auto chasing = std::get_if<orbital_chasing>(&l)) {
return chasing->target;
}
return {};
}
void sound_system::clear() {
short_sounds.clear();
fading_sources.clear();
}
void sound_system::clear_sources_playing(const assets::sound_buffer_id id) {
erase_if(fading_sources, [id](fading_source& source) {
return id == source.id;
});
erase_if(short_sounds, [id](short_sound_cache& it) {
return id == it.original_effect.id;
});
}
void sound_system::clear_dead_entities(const cosmos& new_cosmos) {
erase_if(short_sounds, [&](short_sound_cache& it) {
if (new_cosmos[get_target_if_any(it.positioning)].dead()) {
if (!it.previous_transform) {
return true;
}
it.positioning = *it.previous_transform;
}
return false;
});
}
void sound_system::update_listener(
const const_entity_handle listener,
const interpolation_system& sys
) {
const auto si = listener.get_cosmos().get_si();
const auto listener_pos = listener.get_viewing_transform(sys).pos;
augs::set_listener_position(si, listener_pos);
augs::set_listener_velocity(si, listener.get_effective_velocity());
augs::set_listener_orientation({ 0.f, -1.f, 0.f, 0.f, 0.f, -1.f });
}
void sound_system::update_effects_from_messages(
const_logic_step step,
const loaded_sounds& manager,
const interpolation_system& interp,
const viewer_eye ear
) {
const auto listening_character = ear.viewed_character;
const auto& cosmos = listening_character.get_cosmos();
const auto si = cosmos.get_si();
{
const auto& events = step.get_queue<messages::stop_sound_effect>();
for (auto& e : events) {
erase_if(short_sounds, [&](short_sound_cache& c){
if (const auto m = e.match_chased_subject) {
if (*m != get_target_if_any(c.positioning)) {
return false;
}
}
if (const auto m = e.match_effect_id) {
if (*m != c.original_effect.id) {
return false;
}
}
if (const auto& effect = c.original_effect;
effect.modifier.fade_on_exit
) {
auto& source = c.source;
if (source.is_playing()) {
fading_sources.push_back({ effect.id, std::move(source) });
}
}
return true;
});
}
}
const auto& events = step.get_queue<messages::start_sound_effect>();
for (auto& e : events) {
const auto effect_id = e.effect.id;
if (const auto source_effect = mapped_or_nullptr(manager, effect_id)) {
short_sounds.emplace_back();
auto& cache = short_sounds.back();
cache.original_effect = e.effect;
cache.original_start = e.start;
cache.positioning = e.start.positioning;
cache.previous_transform = find_transform(e.start.positioning, cosmos, interp);
auto& source = cache.source;
{
const auto& variations = source_effect->variations;
const auto chosen_variation = e.start.variation_number % variations.size();
const auto& buffer = variations[chosen_variation];
const bool is_direct_listener = listening_character == e.start.direct_listener;
const auto& requested_buf =
is_direct_listener ? buffer.stereo_or_mono() : buffer.mono_or_stereo()
;
source.bind_buffer(requested_buf);
source.set_direct_channels(is_direct_listener);
}
source.play();
const auto& modifier = e.effect.modifier;
source.set_max_distance(si, modifier.max_distance);
source.set_reference_distance(si, modifier.reference_distance);
source.set_looping(modifier.repetitions == -1);
}
}
}
void sound_system::update_sound_properties(
const augs::audio_volume_settings& settings,
const loaded_sounds& manager,
const interpolation_system& interp,
const viewer_eye ear,
const augs::delta dt
) {
#if 0
auto queried_size = cone.visible_world_area;
queried_size.set(10000.f, 10000.f);
#endif
const auto listening_character = ear.viewed_character;
update_listener(listening_character, interp);
const auto& cosmos = listening_character.get_cosmos();
const auto si = cosmos.get_si();
const auto listener_pos = listening_character.get_viewing_transform(interp).pos;
erase_if(short_sounds, [&](short_sound_cache& cache) {
const auto& positioning = cache.positioning;
const auto maybe_transform = find_transform(positioning, cosmos, interp);
auto& source = cache.source;
if (!maybe_transform) {
source.set_gain(0.f);
}
const auto current_transform = *maybe_transform;
{
const auto dist_from_listener = (listener_pos - current_transform.pos).length();
const float absorption = std::min(10.f, static_cast<float>(pow(std::max(0.f, dist_from_listener - 2220.f)/520.f, 2)));
source.set_air_absorption_factor(absorption);
}
{
if (cache.previous_transform) {
const auto displacement = current_transform - *cache.previous_transform;
cache.previous_transform = current_transform;
const auto effective_velocity = displacement.pos * dt.in_seconds();
source.set_velocity(si, effective_velocity);
}
}
const auto& input = cache.original_effect;
source.set_pitch(input.modifier.pitch);
source.set_gain(input.modifier.gain * settings.sound_effects);
source.set_position(si, current_transform.pos);
return !source.is_playing();
});
}
void sound_system::fade_sources(const augs::delta dt) {
erase_if(fading_sources, [dt](fading_source& f) {
auto& source = f.source;
const auto new_gain = source.get_gain() - dt.in_seconds()*3.f;
const auto new_pitch = source.get_pitch() - dt.in_seconds()/3.f;
if (new_pitch > 0.1f) {
source.set_pitch(new_pitch);
}
if (new_gain > 0.f) {
source.set_gain(new_gain);
return false;
}
return true;
});
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the
// University of Virginia, University of Heidelberg, and University
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
/*
* CQMethodParametersDM.cpp
*
* Created on: Oct 9, 2015
* Author: shoops
*/
#include "CQParameterGroupDM.h"
#include "qtUtilities.h"
#include "utilities/CCopasiParameterGroup.h"
#include "resourcesUI/CQIconResource.h"
#define COL_NAME 0
#define COL_VALUE 1
#define COL_TYPE 2
#define COLUMN_COUNT 2
CQParameterGroupDM::CQParameterGroupDM(QObject * pParent):
QAbstractItemModel(pParent),
mTopLevelGroups(),
mAdvanced(true)
{}
// virtual
CQParameterGroupDM::~CQParameterGroupDM()
{}
// virtual
int CQParameterGroupDM::columnCount(const QModelIndex & /* parent */) const
{
return COLUMN_COUNT;
}
// virtual
QVariant CQParameterGroupDM::data(const QModelIndex & index, int role) const
{
CCopasiParameter * pNode = nodeFromIndex(index);
if (pNode == NULL) return QVariant();
switch (role)
{
case Qt::UserRole + 1:
if (index.column() == COL_NAME)
return QString(pNode->isBasic() || !pNode->isDefault() ? "basic" : "advanced");
break;
case Qt::UserRole + 2:
if (index.column() == COL_NAME)
return QString(pNode->isBasic() ? "basic" : "advanced");
break;
default:
switch (index.column())
{
case COL_NAME:
return nameData(pNode, role);
break;
case COL_VALUE:
return valueData(pNode, role);
break;
case COL_TYPE:
return typeData(pNode, role);
break;
}
}
return QVariant();
}
// virtual
Qt::ItemFlags CQParameterGroupDM::flags(const QModelIndex &index) const
{
CCopasiParameter * pNode = nodeFromIndex(index);
if (pNode == NULL)
{
return Qt::ItemIsEnabled;
}
Qt::ItemFlags Flags = QAbstractItemModel::flags(index);
if (pNode->isEditable())
Flags |= Qt::ItemIsEditable;
else
Flags &= ~Qt::ItemIsEditable;
if (index.column() == COL_VALUE)
{
if (pNode->getType() == CCopasiParameter::Type::BOOL)
return Flags | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
if (pNode->hasValidValues())
{
emit signalCreateComboBox(index);
}
else if (pNode->getType() == CCopasiParameter::Type::GROUP &&
static_cast< CCopasiParameterGroup * >(pNode)->haveTemplate())
{
emit signalCreatePushButton(index);
}
else
{
emit signalCloseEditor(index);
}
if (pNode->getType() == CCopasiParameter::Type::CN)
{
return (Flags | Qt::ItemIsEnabled) & ~Qt::ItemIsEditable;
}
return Flags | Qt::ItemIsEnabled;
}
return QAbstractItemModel::flags(index) & ~Qt::ItemIsEditable;
}
// virtual
QVariant CQParameterGroupDM::headerData(int section, Qt::Orientation /* orientation */, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
switch (section)
{
case COL_NAME:
return QVariant("Name");
break;
case COL_TYPE:
return QVariant("Type");
break;
case COL_VALUE:
return QVariant("Value");
break;
}
return QVariant();
}
// virtual
QModelIndex CQParameterGroupDM::index(int row, int column, const QModelIndex & parent) const
{
CCopasiParameterGroup * pParent = static_cast< CCopasiParameterGroup * >(nodeFromIndex(parent));
int Row = row;
if (pParent == NULL &&
mTopLevelGroups.size() > 0)
{
QVector< CCopasiParameterGroup * >::const_iterator it = mTopLevelGroups.constBegin();
QVector< CCopasiParameterGroup * >::const_iterator end = mTopLevelGroups.constEnd();
for (; it != end; ++it)
if (Row < (int)(*it)->size())
{
if (mAdvanced)
{
return createIndex(row, column, *((*it)->beginIndex() + Row));
}
CCopasiParameterGroup::index_iterator itRow = (*it)->beginIndex();
CCopasiParameterGroup::index_iterator endRow = (*it)->endIndex();
for (; itRow != endRow; ++itRow)
{
if ((*itRow)->isBasic()) --Row;
if (Row == -1)
{
return createIndex(row, column, *(itRow));
}
}
return QModelIndex();
}
else
{
Row -= (int)(*it)->size();
}
return QModelIndex();
}
if (pParent != NULL && row < (int) pParent->size())
{
if (mAdvanced)
{
return createIndex(row, column, *(pParent->beginIndex() + row));
}
CCopasiParameterGroup::index_iterator itRow = pParent->beginIndex();
CCopasiParameterGroup::index_iterator endRow = pParent->endIndex();
for (; itRow != endRow; ++itRow)
{
if ((*itRow)->isBasic()) --Row;
if (Row == -1)
{
return createIndex(row, column, *(itRow));
}
}
}
return QModelIndex();
}
// virtual
QModelIndex CQParameterGroupDM::parent(const QModelIndex & index) const
{
CCopasiParameter * pNode = nodeFromIndex(index);
if (pNode == NULL || isTopLevelGroup(pNode))
{
return QModelIndex();
}
if (isTopLevelGroup(dynamic_cast<CCopasiParameter *>(pNode->getObjectParent())))
{
return QModelIndex();
}
CCopasiParameter * pParent = static_cast< CCopasiParameter * >(pNode->getObjectParent());
return createIndex(getRow(pParent), 0, pParent);
}
// virtual
int CQParameterGroupDM::rowCount(const QModelIndex & parent) const
{
CCopasiParameter::UserInterfaceFlag Exclude(CCopasiParameter::eUserInterfaceFlag::unsupported);
CCopasiParameter::UserInterfaceFlag Require(mAdvanced ? CCopasiParameter::UserInterfaceFlag::None : CCopasiParameter::eUserInterfaceFlag::basic);
if (!parent.isValid())
{
QVector< CCopasiParameterGroup * >::const_iterator it = mTopLevelGroups.constBegin();
QVector< CCopasiParameterGroup * >::const_iterator end = mTopLevelGroups.constEnd();
int size = 0;
for (; it != end; ++it)
{
size += (int)(*it)->size(Require, Exclude);
}
return size;
}
CCopasiParameter * pParent = nodeFromIndex(parent);
switch (pParent->getType())
{
case CCopasiParameter::Type::GROUP:
return (int) static_cast< CCopasiParameterGroup * >(pParent)->size(Require, Exclude);
break;
default:
break;
}
return 0;
}
// virtual
bool CQParameterGroupDM::setData(const QModelIndex &_index, const QVariant &value, int role)
{
CCopasiParameter * pNode = nodeFromIndex(_index);
if (pNode == NULL) return false;
bool success = false;
if (role == Qt::EditRole ||
role == Qt::CheckStateRole)
{
switch (_index.column())
{
case COL_VALUE:
success = setParameterValue(pNode, value);
break;
default:
success = true;
break;
}
}
return success;
}
void CQParameterGroupDM::setAdvanced(const bool & advanced)
{
mAdvanced = advanced;
}
void CQParameterGroupDM::pushGroup(CCopasiParameterGroup * pTopLevelGroup)
{
assert(pTopLevelGroup != NULL);
QVector< CCopasiParameterGroup * >::const_iterator it = mTopLevelGroups.constBegin();
QVector< CCopasiParameterGroup * >::const_iterator end = mTopLevelGroups.constEnd();
for (; it != end; ++it)
if (*it == pTopLevelGroup) return;
beginResetModel();
mTopLevelGroups.append(pTopLevelGroup);
endResetModel();
}
void CQParameterGroupDM::popGroup(CCopasiParameterGroup * pTopLevelGroup)
{
QVector< CCopasiParameterGroup * >::iterator it = mTopLevelGroups.begin();
QVector< CCopasiParameterGroup * >::iterator end = mTopLevelGroups.end();
for (; it != end; ++it)
if (*it == pTopLevelGroup)
{
beginResetModel();
mTopLevelGroups.erase(it);
endResetModel();
}
}
void CQParameterGroupDM::clearGroups()
{
beginResetModel();
mTopLevelGroups.clear();
endResetModel();
}
void CQParameterGroupDM::beginResetModel()
{
QAbstractItemModel::beginResetModel();
}
void CQParameterGroupDM::endResetModel()
{
QAbstractItemModel::endResetModel();
}
QModelIndex CQParameterGroupDM::index(CCopasiParameter * pNode) const
{
if (pNode == NULL)
{
return QModelIndex();
}
if (isTopLevelGroup(pNode))
{
return index(0, 0, QModelIndex());
}
QModelIndex Parent = index(static_cast< CCopasiParameter * >(pNode->getObjectParent()));
return index(getRow(pNode), 0, Parent);
}
bool CQParameterGroupDM::isTopLevelGroup(CCopasiParameter * pNode) const
{
QVector< CCopasiParameterGroup * >::const_iterator it = mTopLevelGroups.constBegin();
QVector< CCopasiParameterGroup * >::const_iterator end = mTopLevelGroups.constEnd();
for (; it != end; ++it)
if (*it == pNode) return true;
return false;
}
// static
CCopasiParameter * CQParameterGroupDM::nodeFromIndex(const QModelIndex & index)
{
if (!index.isValid()) return NULL;
QModelIndex Source = index;
while (Source.model()->inherits("QSortFilterProxyModel"))
{
Source = static_cast< const QSortFilterProxyModel *>(Source.model())->mapToSource(index);
}
return static_cast< CCopasiParameter * >(Source.internalPointer());
}
int CQParameterGroupDM::getRow(const CCopasiParameter * pNode) const
{
if (pNode == NULL)
{
return -1;
}
CCopasiParameterGroup * pParent = static_cast< CCopasiParameterGroup * >(pNode->getObjectParent());
if (pParent == NULL)
{
return 0;
}
if (isTopLevelGroup(pParent))
{
QVector< CCopasiParameterGroup * >::const_iterator itTopLevelGroup = mTopLevelGroups.constBegin();
QVector< CCopasiParameterGroup * >::const_iterator endTopLevelGroup = mTopLevelGroups.constEnd();
int i = 0;
for (; itTopLevelGroup != endTopLevelGroup; ++itTopLevelGroup)
{
CCopasiParameterGroup::index_iterator it = pParent->beginIndex();
CCopasiParameterGroup::index_iterator end = pParent->endIndex();
for (; it != end; ++it)
if (!(*it)->isUnsupported() &&
(mAdvanced || (*it)->isBasic()))
{
if (*it == pNode) return i;
++i;
}
}
}
else
{
int i = 0;
CCopasiParameterGroup::index_iterator it = pParent->beginIndex();
CCopasiParameterGroup::index_iterator end = pParent->endIndex();
for (; it != end; ++it, ++i)
if (!(*it)->isUnsupported() &&
(mAdvanced || (*it)->isBasic()))
{
if (*it == pNode) return i;
++i;
}
}
return -1;
}
// static
QVariant CQParameterGroupDM::nameData(const CCopasiParameter * pNode, int role)
{
if (role == Qt::DisplayRole)
{
return QVariant(QString(FROM_UTF8(pNode->getObjectName())));
}
return QVariant();
}
// static
QVariant CQParameterGroupDM::typeData(const CCopasiParameter * pNode, int role)
{
return QVariant(static_cast< int >(pNode->getType()));
}
QVariant CQParameterGroupDM::valueData(const CCopasiParameter * pNode, int role)
{
switch (role)
{
case Qt::EditRole:
case Qt::DisplayRole:
switch (pNode->getType())
{
case CCopasiParameter::Type::DOUBLE:
case CCopasiParameter::Type::UDOUBLE:
return QVariant(convertToQString(pNode->getValue< C_FLOAT64 >()));
break;
case CCopasiParameter::Type::INT:
return QVariant(QString::number(pNode->getValue< C_INT32 >()));
break;
case CCopasiParameter::Type::UINT:
return QVariant(QString::number(pNode->getValue< unsigned C_INT32 >()));
break;
case CCopasiParameter::Type::BOOL:
if (role == Qt::DisplayRole)
return QVariant();
else
return QVariant(pNode->getValue< bool >());
break;
case CCopasiParameter::Type::GROUP:
if (static_cast< const CCopasiParameterGroup * >(pNode)->haveTemplate())
{
QVariant(QString("Add"));
}
return QVariant();
break;
case CCopasiParameter::Type::STRING:
case CCopasiParameter::Type::FILE:
case CCopasiParameter::Type::EXPRESSION:
case CCopasiParameter::Type::KEY:
return QVariant(FROM_UTF8(pNode->getValue< std::string >()));
case CCopasiParameter::Type::CN:
{
const CObjectInterface * pObject = pNode->getObjectFromCN(pNode->getValue< CRegisteredCommonName >());
if (pObject != NULL)
{
return QVariant(FROM_UTF8(pObject->getObjectDisplayName()));
}
return QVariant("Object not found");
}
break;
default:
return QVariant();
break;
}
break;
case Qt::CheckStateRole:
if (pNode->getType() == CCopasiParameter::Type::BOOL)
{
return pNode->getValue< bool >() ? Qt::Checked : Qt::Unchecked;
}
break;
case Qt::UserRole:
{
QList< QPair < QVariant, QVariant > > ValidValues = getParameterValidValues(pNode);
QList< QPair < QVariant, QVariant > >::const_iterator it = ValidValues.constBegin();
QList< QPair < QVariant, QVariant > >::const_iterator end = ValidValues.constEnd();
QStringList ValidValueList;
for (; it != end; ++it)
if (it->first == it->second) ValidValueList.append(it->first.toString());
return QVariant(ValidValueList);
}
break;
}
return QVariant();
}
<commit_msg>- issue 2797: workaround do not hide unknown entries, so that all supported entries can be displayed<commit_after>// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the
// University of Virginia, University of Heidelberg, and University
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
/*
* CQMethodParametersDM.cpp
*
* Created on: Oct 9, 2015
* Author: shoops
*/
#include "CQParameterGroupDM.h"
#include "qtUtilities.h"
#include "utilities/CCopasiParameterGroup.h"
#include "resourcesUI/CQIconResource.h"
#define COL_NAME 0
#define COL_VALUE 1
#define COL_TYPE 2
#define COLUMN_COUNT 2
CQParameterGroupDM::CQParameterGroupDM(QObject * pParent):
QAbstractItemModel(pParent),
mTopLevelGroups(),
mAdvanced(true)
{}
// virtual
CQParameterGroupDM::~CQParameterGroupDM()
{}
// virtual
int CQParameterGroupDM::columnCount(const QModelIndex & /* parent */) const
{
return COLUMN_COUNT;
}
// virtual
QVariant CQParameterGroupDM::data(const QModelIndex & index, int role) const
{
CCopasiParameter * pNode = nodeFromIndex(index);
if (pNode == NULL) return QVariant();
switch (role)
{
case Qt::UserRole + 1:
if (index.column() == COL_NAME)
return QString(pNode->isBasic() || !pNode->isDefault() ? "basic" : "advanced");
break;
case Qt::UserRole + 2:
if (index.column() == COL_NAME)
return QString(pNode->isBasic() ? "basic" : "advanced");
break;
default:
switch (index.column())
{
case COL_NAME:
return nameData(pNode, role);
break;
case COL_VALUE:
return valueData(pNode, role);
break;
case COL_TYPE:
return typeData(pNode, role);
break;
}
}
return QVariant();
}
// virtual
Qt::ItemFlags CQParameterGroupDM::flags(const QModelIndex &index) const
{
CCopasiParameter * pNode = nodeFromIndex(index);
if (pNode == NULL)
{
return Qt::ItemIsEnabled;
}
Qt::ItemFlags Flags = QAbstractItemModel::flags(index);
if (pNode->isEditable())
Flags |= Qt::ItemIsEditable;
else
Flags &= ~Qt::ItemIsEditable;
if (index.column() == COL_VALUE)
{
if (pNode->getType() == CCopasiParameter::Type::BOOL)
return Flags | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
if (pNode->hasValidValues())
{
emit signalCreateComboBox(index);
}
else if (pNode->getType() == CCopasiParameter::Type::GROUP &&
static_cast< CCopasiParameterGroup * >(pNode)->haveTemplate())
{
emit signalCreatePushButton(index);
}
else
{
emit signalCloseEditor(index);
}
if (pNode->getType() == CCopasiParameter::Type::CN)
{
return (Flags | Qt::ItemIsEnabled) & ~Qt::ItemIsEditable;
}
return Flags | Qt::ItemIsEnabled;
}
return QAbstractItemModel::flags(index) & ~Qt::ItemIsEditable;
}
// virtual
QVariant CQParameterGroupDM::headerData(int section, Qt::Orientation /* orientation */, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
switch (section)
{
case COL_NAME:
return QVariant("Name");
break;
case COL_TYPE:
return QVariant("Type");
break;
case COL_VALUE:
return QVariant("Value");
break;
}
return QVariant();
}
// virtual
QModelIndex CQParameterGroupDM::index(int row, int column, const QModelIndex & parent) const
{
CCopasiParameterGroup * pParent = static_cast< CCopasiParameterGroup * >(nodeFromIndex(parent));
int Row = row;
if (pParent == NULL &&
mTopLevelGroups.size() > 0)
{
QVector< CCopasiParameterGroup * >::const_iterator it = mTopLevelGroups.constBegin();
QVector< CCopasiParameterGroup * >::const_iterator end = mTopLevelGroups.constEnd();
for (; it != end; ++it)
if (Row < (int)(*it)->size())
{
if (mAdvanced)
{
return createIndex(row, column, *((*it)->beginIndex() + Row));
}
CCopasiParameterGroup::index_iterator itRow = (*it)->beginIndex();
CCopasiParameterGroup::index_iterator endRow = (*it)->endIndex();
for (; itRow != endRow; ++itRow)
{
if ((*itRow)->isBasic()) --Row;
if (Row == -1)
{
return createIndex(row, column, *(itRow));
}
}
return QModelIndex();
}
else
{
Row -= (int)(*it)->size();
}
return QModelIndex();
}
if (pParent != NULL && row < (int) pParent->size())
{
if (mAdvanced)
{
return createIndex(row, column, *(pParent->beginIndex() + row));
}
CCopasiParameterGroup::index_iterator itRow = pParent->beginIndex();
CCopasiParameterGroup::index_iterator endRow = pParent->endIndex();
for (; itRow != endRow; ++itRow)
{
if ((*itRow)->isBasic()) --Row;
if (Row == -1)
{
return createIndex(row, column, *(itRow));
}
}
}
return QModelIndex();
}
// virtual
QModelIndex CQParameterGroupDM::parent(const QModelIndex & index) const
{
CCopasiParameter * pNode = nodeFromIndex(index);
if (pNode == NULL || isTopLevelGroup(pNode))
{
return QModelIndex();
}
if (isTopLevelGroup(dynamic_cast<CCopasiParameter *>(pNode->getObjectParent())))
{
return QModelIndex();
}
CCopasiParameter * pParent = static_cast< CCopasiParameter * >(pNode->getObjectParent());
return createIndex(getRow(pParent), 0, pParent);
}
// virtual
int CQParameterGroupDM::rowCount(const QModelIndex & parent) const
{
CCopasiParameter::UserInterfaceFlag Exclude(CCopasiParameter::UserInterfaceFlag::None);
//CCopasiParameter::UserInterfaceFlag Exclude(CCopasiParameter::eUserInterfaceFlag::unsupported);
CCopasiParameter::UserInterfaceFlag Require(mAdvanced ? CCopasiParameter::UserInterfaceFlag::None : CCopasiParameter::eUserInterfaceFlag::basic);
if (!parent.isValid())
{
QVector< CCopasiParameterGroup * >::const_iterator it = mTopLevelGroups.constBegin();
QVector< CCopasiParameterGroup * >::const_iterator end = mTopLevelGroups.constEnd();
int size = 0;
for (; it != end; ++it)
{
size += (int)(*it)->size(Require, Exclude);
}
return size;
}
CCopasiParameter * pParent = nodeFromIndex(parent);
switch (pParent->getType())
{
case CCopasiParameter::Type::GROUP:
return (int) static_cast< CCopasiParameterGroup * >(pParent)->size(Require, Exclude);
break;
default:
break;
}
return 0;
}
// virtual
bool CQParameterGroupDM::setData(const QModelIndex &_index, const QVariant &value, int role)
{
CCopasiParameter * pNode = nodeFromIndex(_index);
if (pNode == NULL) return false;
bool success = false;
if (role == Qt::EditRole ||
role == Qt::CheckStateRole)
{
switch (_index.column())
{
case COL_VALUE:
success = setParameterValue(pNode, value);
break;
default:
success = true;
break;
}
}
return success;
}
void CQParameterGroupDM::setAdvanced(const bool & advanced)
{
mAdvanced = advanced;
}
void CQParameterGroupDM::pushGroup(CCopasiParameterGroup * pTopLevelGroup)
{
assert(pTopLevelGroup != NULL);
QVector< CCopasiParameterGroup * >::const_iterator it = mTopLevelGroups.constBegin();
QVector< CCopasiParameterGroup * >::const_iterator end = mTopLevelGroups.constEnd();
for (; it != end; ++it)
if (*it == pTopLevelGroup) return;
beginResetModel();
mTopLevelGroups.append(pTopLevelGroup);
endResetModel();
}
void CQParameterGroupDM::popGroup(CCopasiParameterGroup * pTopLevelGroup)
{
QVector< CCopasiParameterGroup * >::iterator it = mTopLevelGroups.begin();
QVector< CCopasiParameterGroup * >::iterator end = mTopLevelGroups.end();
for (; it != end; ++it)
if (*it == pTopLevelGroup)
{
beginResetModel();
mTopLevelGroups.erase(it);
endResetModel();
}
}
void CQParameterGroupDM::clearGroups()
{
beginResetModel();
mTopLevelGroups.clear();
endResetModel();
}
void CQParameterGroupDM::beginResetModel()
{
QAbstractItemModel::beginResetModel();
}
void CQParameterGroupDM::endResetModel()
{
QAbstractItemModel::endResetModel();
}
QModelIndex CQParameterGroupDM::index(CCopasiParameter * pNode) const
{
if (pNode == NULL)
{
return QModelIndex();
}
if (isTopLevelGroup(pNode))
{
return index(0, 0, QModelIndex());
}
QModelIndex Parent = index(static_cast< CCopasiParameter * >(pNode->getObjectParent()));
return index(getRow(pNode), 0, Parent);
}
bool CQParameterGroupDM::isTopLevelGroup(CCopasiParameter * pNode) const
{
QVector< CCopasiParameterGroup * >::const_iterator it = mTopLevelGroups.constBegin();
QVector< CCopasiParameterGroup * >::const_iterator end = mTopLevelGroups.constEnd();
for (; it != end; ++it)
if (*it == pNode) return true;
return false;
}
// static
CCopasiParameter * CQParameterGroupDM::nodeFromIndex(const QModelIndex & index)
{
if (!index.isValid()) return NULL;
QModelIndex Source = index;
while (Source.model()->inherits("QSortFilterProxyModel"))
{
Source = static_cast< const QSortFilterProxyModel *>(Source.model())->mapToSource(index);
}
return static_cast< CCopasiParameter * >(Source.internalPointer());
}
int CQParameterGroupDM::getRow(const CCopasiParameter * pNode) const
{
if (pNode == NULL)
{
return -1;
}
CCopasiParameterGroup * pParent = static_cast< CCopasiParameterGroup * >(pNode->getObjectParent());
if (pParent == NULL)
{
return 0;
}
if (isTopLevelGroup(pParent))
{
QVector< CCopasiParameterGroup * >::const_iterator itTopLevelGroup = mTopLevelGroups.constBegin();
QVector< CCopasiParameterGroup * >::const_iterator endTopLevelGroup = mTopLevelGroups.constEnd();
int i = 0;
for (; itTopLevelGroup != endTopLevelGroup; ++itTopLevelGroup)
{
CCopasiParameterGroup::index_iterator it = pParent->beginIndex();
CCopasiParameterGroup::index_iterator end = pParent->endIndex();
for (; it != end; ++it)
if (!(*it)->isUnsupported() &&
(mAdvanced || (*it)->isBasic()))
{
if (*it == pNode) return i;
++i;
}
}
}
else
{
int i = 0;
CCopasiParameterGroup::index_iterator it = pParent->beginIndex();
CCopasiParameterGroup::index_iterator end = pParent->endIndex();
for (; it != end; ++it, ++i)
if (!(*it)->isUnsupported() &&
(mAdvanced || (*it)->isBasic()))
{
if (*it == pNode) return i;
++i;
}
}
return -1;
}
// static
QVariant CQParameterGroupDM::nameData(const CCopasiParameter * pNode, int role)
{
if (role == Qt::DisplayRole)
{
return QVariant(QString(FROM_UTF8(pNode->getObjectName())));
}
return QVariant();
}
// static
QVariant CQParameterGroupDM::typeData(const CCopasiParameter * pNode, int role)
{
return QVariant(static_cast< int >(pNode->getType()));
}
QVariant CQParameterGroupDM::valueData(const CCopasiParameter * pNode, int role)
{
switch (role)
{
case Qt::EditRole:
case Qt::DisplayRole:
switch (pNode->getType())
{
case CCopasiParameter::Type::DOUBLE:
case CCopasiParameter::Type::UDOUBLE:
return QVariant(convertToQString(pNode->getValue< C_FLOAT64 >()));
break;
case CCopasiParameter::Type::INT:
return QVariant(QString::number(pNode->getValue< C_INT32 >()));
break;
case CCopasiParameter::Type::UINT:
return QVariant(QString::number(pNode->getValue< unsigned C_INT32 >()));
break;
case CCopasiParameter::Type::BOOL:
if (role == Qt::DisplayRole)
return QVariant();
else
return QVariant(pNode->getValue< bool >());
break;
case CCopasiParameter::Type::GROUP:
if (static_cast< const CCopasiParameterGroup * >(pNode)->haveTemplate())
{
QVariant(QString("Add"));
}
return QVariant();
break;
case CCopasiParameter::Type::STRING:
case CCopasiParameter::Type::FILE:
case CCopasiParameter::Type::EXPRESSION:
case CCopasiParameter::Type::KEY:
return QVariant(FROM_UTF8(pNode->getValue< std::string >()));
case CCopasiParameter::Type::CN:
{
const CObjectInterface * pObject = pNode->getObjectFromCN(pNode->getValue< CRegisteredCommonName >());
if (pObject != NULL)
{
return QVariant(FROM_UTF8(pObject->getObjectDisplayName()));
}
return QVariant("Object not found");
}
break;
default:
return QVariant();
break;
}
break;
case Qt::CheckStateRole:
if (pNode->getType() == CCopasiParameter::Type::BOOL)
{
return pNode->getValue< bool >() ? Qt::Checked : Qt::Unchecked;
}
break;
case Qt::UserRole:
{
QList< QPair < QVariant, QVariant > > ValidValues = getParameterValidValues(pNode);
QList< QPair < QVariant, QVariant > >::const_iterator it = ValidValues.constBegin();
QList< QPair < QVariant, QVariant > >::const_iterator end = ValidValues.constEnd();
QStringList ValidValueList;
for (; it != end; ++it)
if (it->first == it->second) ValidValueList.append(it->first.toString());
return QVariant(ValidValueList);
}
break;
}
return QVariant();
}
<|endoftext|>
|
<commit_before>#include <nds.h>
#include "dmafuncs.h"
#ifdef USING_SDL
void woopsiDmaCopy(const u16* source, u16* dest, u32 count) {
memcpy(dest, source, sizeof(u16) * count);
}
void woopsiDmaFill(u16 fill, u16* dest, u32 count) {
for (u32 i = 0; i < count; i++) {
*(dest + i) = fill;
}
}
#else
void woopsiDmaCopy(const u16* source, u16* dest, u32 count) {
// Get memory addresses of source and destination
u32 srca = (u32)source;
u32 dsta = (u32)dest;
// Precalculate the size of a single framebuffer for speed
u32 bmpSize = SCREEN_WIDTH * SCREEN_HEIGHT * 2;
// Precalculate boundaries of framebuffer VRAM
u32 bmp[4];
bmp[0] = 0x06000000;
bmp[1] = 0x06000000 + bmpSize;
bmp[2] = 0x06200000;
bmp[3] = 0x06200000 + bmpSize;
// Use DMA hardware if both source and destination are within VRAM
if (((dsta >= bmp[0]) && (dsta < bmp[1])) ||
((dsta >= bmp[2]) && (dsta < bmp[3]))) {
// libnds DMA functions work in bytes
count *= 2;
DC_FlushRange(source, count);
while (dmaBusy(3)) {}
// Choose fastest DMA copy mode
if((srca|dsta|count) & 3)
dmaCopyHalfWords(3, source, dest, count);
else
dmaCopyWords(3, source, dest, count);
return;
}
// Cannot use DMA as not working exclusively with VRAM
// Use for-loop instead
for (u32 i = 0; i < count; i++) {
*(dest + i) = *(source + i);
}
}
void woopsiDmaFill(u16 fill, u16* dest, u32 count) {
// Draw initial pixel
*dest = fill;
// Stop copying if there are no more pixels to draw
if (count > 1) {
u32 dsta = (u32)dest + 1;
// Precalculate the size of a single framebuffer for speed
u32 bmpSize = SCREEN_WIDTH * SCREEN_HEIGHT * 2;
// Precalculate boundaries of framebuffer VRAM
u32 bmp[4];
bmp[0] = 0x06000000;
bmp[1] = 0x06000000 + bmpSize;
bmp[2] = 0x06200000;
bmp[3] = 0x06200000 + bmpSize;
// Use DMA hardware if destination is within VRAM
if (((dsta >= bmp[0]) && (dsta < bmp[1])) ||
((dsta >= bmp[2]) && (dsta < bmp[3]))) {
// libnds DMA functions work in bytes
count *= 2;
while (dmaBusy(3)) {}
if((dsta|count) & 3)
dmaFillHalfWords(fill, dest, count);
else
dmaFillWords(fill, dest, count);
return;
}
}
// Cannot use DMA as not working exclusively with VRAM
// Use for-loop instead
for (u32 i = 0; i < count; i++) {
*(dest + i) = fill;
}
}
#endif
<commit_msg>More DMA fixes.<commit_after>#include <nds.h>
#include "dmafuncs.h"
#ifndef USING_SDL
static const u32 MEM_VRAM_START = 0x06000000;
static const u32 MEM_VRAM_END = 0x06400000;
#endif
void woopsiDmaCopy(const u16* source, u16* dest, u32 count) {
#ifdef USING_SDL
memcpy(dest, source, sizeof(u16) * count);
#else
// Get memory addresses of source and destination
u32 srca = (u32)source;
u32 dsta = (u32)dest;
// Use DMA hardware if both source and destination are within VRAM
if (0 && (dsta >= MEM_VRAM_START) && (dsta < MEM_VRAM_END) && (srca >= MEM_VRAM_START) && (srca < MEM_VRAM_END)) {
// libnds DMA functions work in bytes
count *= 2;
DC_FlushRange(source, count);
int channel = 0;
while (dmaBusy(channel)) {
++channel;
channel = channel % 4;
}
// Choose fastest DMA copy mode
if ((srca | dsta | count) & 3) {
dmaCopyHalfWordsAsynch(channel, source, dest, count);
} else {
dmaCopyWordsAsynch(channel, source, dest, count);
}
} else {
// Cannot use DMA as not working exclusively with VRAM
for (u32 i = 0; i < count; i++) {
*(dest + i) = *(source + i);
}
}
#endif
}
void woopsiDmaFill(u16 fill, u16* dest, u32 count) {
#ifdef USING_SDL
for (u32 i = 0; i < count; i++) {
*(dest + i) = fill;
}
#else
// Draw initial pixel
*dest = fill;
// Stop copying if there are no more pixels to draw
if (count > 1) {
u32 dsta = (u32)dest + 1;
// Use DMA hardware if destination is within VRAM
if ((dsta >= MEM_VRAM_START) && (dsta < MEM_VRAM_END)) {
// libnds DMA functions work in bytes
count *= 2;
if ((dsta | count) & 3) {
dmaFillHalfWords(fill, dest, count);
} else {
dmaFillWords(fill, dest, count);
}
return;
}
}
// Cannot use DMA as not working exclusively with VRAM
for (u32 i = 0; i < count; i++) {
*(dest + i) = fill;
}
#endif
}<|endoftext|>
|
<commit_before>/*
* drakeUtil.cpp
*
* Created on: Jun 19, 2013
* Author: russt
*/
#include "drakeUtil.h"
#include <string.h>
#include <string>
#include <math.h>
#include <limits>
#include <Eigen/Dense>
using namespace std;
bool isa(const mxArray* mxa, const char* class_str)
// mxIsClass seems to not be able to handle derived classes. so i'll implement what I need by calling back to matlab
{
mxArray* plhs;
mxArray* prhs[2];
prhs[0] = const_cast<mxArray*>(mxa);
prhs[1] = mxCreateString(class_str);
mexCallMATLAB(1,&plhs,2,prhs,"isa");
bool tf = *mxGetLogicals(plhs);
mxDestroyArray(plhs);
mxDestroyArray(prhs[1]);
return tf;
}
bool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename)
{
int i;
mxArray* ex = mexCallMATLABWithTrap(nlhs,plhs,nrhs,prhs,filename);
if (ex) {
mexPrintf("DrakeSystem S-Function: error when calling ''%s'' with the following arguments:\n",filename);
for (i=0; i<nrhs; i++)
mexCallMATLAB(0,NULL,1,&prhs[i],"disp");
mxArray *report;
mexCallMATLAB(1,&report,1,&ex,"getReport");
char *errmsg = mxArrayToString(report);
mexPrintf(errmsg);
mxFree(errmsg);
mxDestroyArray(report);
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:CallbackError", "Error in MATLAB callback.\nSee additional debugging information above");
mxDestroyArray(ex);
return true;
}
for (i=0; i<nlhs; i++)
if (!plhs[i]) {
mexPrintf("Drake mexCallMATLABsafe: error when calling ''%s'' with the following arguments:\n", filename);
for (i=0; i<nrhs; i++)
mexCallMATLAB(0,NULL,1,&prhs[i],"disp");
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:NotEnoughOutputs","Asked for %d outputs, but function only returned %d\n",nrhs,i);
return true;
}
return false;
}
/*
* @param subclass_name (optional) if you want to call a class that derives from
* DrakeMexPointer (e.g. so that you can refer to it as something more specific in
* your matlab code), then you can pass in the alternative name here. The constructor
* for this class must take the same inputs as the DrakeMexPointer constructor.
*/
mxArray* createDrakeMexPointer(void* ptr, const char* name, int num_additional_inputs, mxArray* delete_fcn_additional_inputs[], const char* subclass_name)
{
mxClassID cid;
if (sizeof(ptr)==4) cid = mxUINT32_CLASS;
else if (sizeof(ptr)==8) cid = mxUINT64_CLASS;
else mexErrMsgIdAndTxt("Drake:constructDrakeMexPointer:PointerSize","Are you on a 32-bit machine or 64-bit machine??");
int nrhs=3+num_additional_inputs;
mxArray *plhs[1];
mxArray **prhs; prhs = new mxArray*[nrhs];
prhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL);
memcpy(mxGetData(prhs[0]),&ptr,sizeof(ptr));
prhs[1] = mxCreateString(mexFunctionName());
prhs[2] = mxCreateString(name);
for (int i=0; i<num_additional_inputs; i++)
prhs[3+i] = delete_fcn_additional_inputs[i];
// mexPrintf("deleteMethod = %s\n name =%s\n", deleteMethod,name);
// call matlab to construct mex pointer object
if (subclass_name) {
mexCallMATLABsafe(1,plhs,nrhs,prhs,subclass_name);
if (!isa(plhs[0],"DrakeMexPointer")) {
mxDestroyArray(plhs[0]);
mexErrMsgIdAndTxt("Drake:createDrakeMexPointer:InvalidSubclass","subclass_name is not a valid subclass of DrakeMexPointer");
}
}
else
mexCallMATLABsafe(1,plhs,nrhs,prhs,"DrakeMexPointer");
mexLock();
// mexPrintf("incrementing lock count\n");
delete[] prhs;
return plhs[0];
}
void* getDrakeMexPointer(const mxArray* mx)
{
void* ptr = NULL;
// todo: optimize this by caching the pointer values, as described in
// http://groups.csail.mit.edu/locomotion/bugs/show_bug.cgi?id=1590
mxArray* ptrArray = mxGetProperty(mx,0,"ptr");
if (!ptrArray)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","cannot retrieve 'ptr' field from this mxArray. are you sure it's a valid DrakeMexPointer object?");
if (!mxIsNumeric(ptrArray) || mxGetNumberOfElements(ptrArray)!=1)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","the ptr property of this DrakeMexPointer does not appear to contain a valid pointer");
memcpy(&ptr,mxGetData(ptrArray),sizeof(ptr)); // note: could use a reinterpret_cast here instead
return ptr;
}
double angleAverage(double theta1, double theta2) {
// Computes the average between two angles by averaging points on the unit
// circle and taking the arctan of the result.
// see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities
// theta1 is a scalar or column vector of angles (rad)
// theta2 is a scalar or column vector of angles (rad)
double x_mean = 0.5*(cos(theta1)+cos(theta2));
double y_mean = 0.5*(sin(theta1)+sin(theta2));
double angle_mean = atan2(y_mean,x_mean);
return angle_mean;
}
std::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane)
{
// TODO: implement multi-column version
using namespace Eigen;
if (abs(normal.squaredNorm() - 1.0) > 1e-12) {
mexErrMsgIdAndTxt("Drake:resolveCenterOfPressure:BadInputs", "normal should be a unit vector");
}
Vector3d cop;
double normal_torque_at_cop;
double fz = normal.dot(force);
bool cop_exists = abs(fz) > 1e-12;
if (cop_exists) {
auto torque_at_point_on_contact_plane = torque - point_on_contact_plane.cross(force);
double normal_torque_at_point_on_contact_plane = normal.dot(torque_at_point_on_contact_plane);
auto tangential_torque = torque_at_point_on_contact_plane - normal * normal_torque_at_point_on_contact_plane;
cop = normal.cross(tangential_torque) / fz + point_on_contact_plane;
auto torque_at_cop = torque - cop.cross(force);
normal_torque_at_cop = normal.dot(torque_at_cop);
}
else {
cop.setConstant(std::numeric_limits<double>::quiet_NaN());
normal_torque_at_cop = std::numeric_limits<double>::quiet_NaN();
}
return std::pair<Vector3d, double>(cop, normal_torque_at_cop);
}
double * mxGetPrSafe(const mxArray *pobj) {
if (!mxIsDouble(pobj)) mexErrMsgIdAndTxt("Drake:mxGetPrSafe:BadInputs", "mxGetPr can only be called on arguments which correspond to Matlab doubles");
return mxGetPrSafe(pobj);
}
void sizecheck(const mxArray* mat, int M, int N) {
if (mxGetM(mat) != M) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of rows. Expected: %d but got: %d", M, mxGetM(mat));
}
if (mxGetN(mat) != N) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of columns. Expected: %d but got: %d", N, mxGetN(mat));
}
return;
}
<commit_msg>don't recurse<commit_after>/*
* drakeUtil.cpp
*
* Created on: Jun 19, 2013
* Author: russt
*/
#include "drakeUtil.h"
#include <string.h>
#include <string>
#include <math.h>
#include <limits>
#include <Eigen/Dense>
using namespace std;
bool isa(const mxArray* mxa, const char* class_str)
// mxIsClass seems to not be able to handle derived classes. so i'll implement what I need by calling back to matlab
{
mxArray* plhs;
mxArray* prhs[2];
prhs[0] = const_cast<mxArray*>(mxa);
prhs[1] = mxCreateString(class_str);
mexCallMATLAB(1,&plhs,2,prhs,"isa");
bool tf = *mxGetLogicals(plhs);
mxDestroyArray(plhs);
mxDestroyArray(prhs[1]);
return tf;
}
bool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename)
{
int i;
mxArray* ex = mexCallMATLABWithTrap(nlhs,plhs,nrhs,prhs,filename);
if (ex) {
mexPrintf("DrakeSystem S-Function: error when calling ''%s'' with the following arguments:\n",filename);
for (i=0; i<nrhs; i++)
mexCallMATLAB(0,NULL,1,&prhs[i],"disp");
mxArray *report;
mexCallMATLAB(1,&report,1,&ex,"getReport");
char *errmsg = mxArrayToString(report);
mexPrintf(errmsg);
mxFree(errmsg);
mxDestroyArray(report);
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:CallbackError", "Error in MATLAB callback.\nSee additional debugging information above");
mxDestroyArray(ex);
return true;
}
for (i=0; i<nlhs; i++)
if (!plhs[i]) {
mexPrintf("Drake mexCallMATLABsafe: error when calling ''%s'' with the following arguments:\n", filename);
for (i=0; i<nrhs; i++)
mexCallMATLAB(0,NULL,1,&prhs[i],"disp");
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:NotEnoughOutputs","Asked for %d outputs, but function only returned %d\n",nrhs,i);
return true;
}
return false;
}
/*
* @param subclass_name (optional) if you want to call a class that derives from
* DrakeMexPointer (e.g. so that you can refer to it as something more specific in
* your matlab code), then you can pass in the alternative name here. The constructor
* for this class must take the same inputs as the DrakeMexPointer constructor.
*/
mxArray* createDrakeMexPointer(void* ptr, const char* name, int num_additional_inputs, mxArray* delete_fcn_additional_inputs[], const char* subclass_name)
{
mxClassID cid;
if (sizeof(ptr)==4) cid = mxUINT32_CLASS;
else if (sizeof(ptr)==8) cid = mxUINT64_CLASS;
else mexErrMsgIdAndTxt("Drake:constructDrakeMexPointer:PointerSize","Are you on a 32-bit machine or 64-bit machine??");
int nrhs=3+num_additional_inputs;
mxArray *plhs[1];
mxArray **prhs; prhs = new mxArray*[nrhs];
prhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL);
memcpy(mxGetData(prhs[0]),&ptr,sizeof(ptr));
prhs[1] = mxCreateString(mexFunctionName());
prhs[2] = mxCreateString(name);
for (int i=0; i<num_additional_inputs; i++)
prhs[3+i] = delete_fcn_additional_inputs[i];
// mexPrintf("deleteMethod = %s\n name =%s\n", deleteMethod,name);
// call matlab to construct mex pointer object
if (subclass_name) {
mexCallMATLABsafe(1,plhs,nrhs,prhs,subclass_name);
if (!isa(plhs[0],"DrakeMexPointer")) {
mxDestroyArray(plhs[0]);
mexErrMsgIdAndTxt("Drake:createDrakeMexPointer:InvalidSubclass","subclass_name is not a valid subclass of DrakeMexPointer");
}
}
else
mexCallMATLABsafe(1,plhs,nrhs,prhs,"DrakeMexPointer");
mexLock();
// mexPrintf("incrementing lock count\n");
delete[] prhs;
return plhs[0];
}
void* getDrakeMexPointer(const mxArray* mx)
{
void* ptr = NULL;
// todo: optimize this by caching the pointer values, as described in
// http://groups.csail.mit.edu/locomotion/bugs/show_bug.cgi?id=1590
mxArray* ptrArray = mxGetProperty(mx,0,"ptr");
if (!ptrArray)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","cannot retrieve 'ptr' field from this mxArray. are you sure it's a valid DrakeMexPointer object?");
if (!mxIsNumeric(ptrArray) || mxGetNumberOfElements(ptrArray)!=1)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","the ptr property of this DrakeMexPointer does not appear to contain a valid pointer");
memcpy(&ptr,mxGetData(ptrArray),sizeof(ptr)); // note: could use a reinterpret_cast here instead
return ptr;
}
double angleAverage(double theta1, double theta2) {
// Computes the average between two angles by averaging points on the unit
// circle and taking the arctan of the result.
// see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities
// theta1 is a scalar or column vector of angles (rad)
// theta2 is a scalar or column vector of angles (rad)
double x_mean = 0.5*(cos(theta1)+cos(theta2));
double y_mean = 0.5*(sin(theta1)+sin(theta2));
double angle_mean = atan2(y_mean,x_mean);
return angle_mean;
}
std::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane)
{
// TODO: implement multi-column version
using namespace Eigen;
if (abs(normal.squaredNorm() - 1.0) > 1e-12) {
mexErrMsgIdAndTxt("Drake:resolveCenterOfPressure:BadInputs", "normal should be a unit vector");
}
Vector3d cop;
double normal_torque_at_cop;
double fz = normal.dot(force);
bool cop_exists = abs(fz) > 1e-12;
if (cop_exists) {
auto torque_at_point_on_contact_plane = torque - point_on_contact_plane.cross(force);
double normal_torque_at_point_on_contact_plane = normal.dot(torque_at_point_on_contact_plane);
auto tangential_torque = torque_at_point_on_contact_plane - normal * normal_torque_at_point_on_contact_plane;
cop = normal.cross(tangential_torque) / fz + point_on_contact_plane;
auto torque_at_cop = torque - cop.cross(force);
normal_torque_at_cop = normal.dot(torque_at_cop);
}
else {
cop.setConstant(std::numeric_limits<double>::quiet_NaN());
normal_torque_at_cop = std::numeric_limits<double>::quiet_NaN();
}
return std::pair<Vector3d, double>(cop, normal_torque_at_cop);
}
double * mxGetPrSafe(const mxArray *pobj) {
if (!mxIsDouble(pobj)) mexErrMsgIdAndTxt("Drake:mxGetPrSafe:BadInputs", "mxGetPr can only be called on arguments which correspond to Matlab doubles");
return mxGetPr(pobj);
}
void sizecheck(const mxArray* mat, int M, int N) {
if (mxGetM(mat) != M) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of rows. Expected: %d but got: %d", M, mxGetM(mat));
}
if (mxGetN(mat) != N) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of columns. Expected: %d but got: %d", N, mxGetN(mat));
}
return;
}
<|endoftext|>
|
<commit_before>#define S_FUNCTION_NAME lcmLogger
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
#include <lcm/lcm.h>
#define UNUSED(x) (void)(x)
static double simtime = -1.0;
static lcm_t* lcm = NULL;
#define MDL_INITIAL_SIZES
static void mdlInitializeSizes(SimStruct *S)
{
ssSetNumSFcnParams(S, 2); // lcm channel regex,
// workspace variable name to write log into
ssSetNumContStates(S, 0);
ssSetNumDiscStates(S, 0);
ssSetNumInputPorts(S, 0);
ssSetNumOutputPorts(S, 0);
ssSetNumSampleTimes(S, 1);
}
#define MDL_INITIALIZE_SAMPLE_TIMES
static void mdlInitializeSampleTimes(SimStruct *S)
{
ssSetSampleTime(S, 0, mxGetScalar(ssGetSFcnParam(S, 0)));
}
#define MDL_CHECK_PARAMETERS
#if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)
static void mdlCheckParameters(SimStruct *S)
{
UNUSED(S);
// todo: verify dialog parameters here
}
#endif /* MDL_CHECK_PARAMETERS */
static void message_handler (const lcm_recv_buf_t *rbuf, const char *channel, void *u)
{
mexPrintf("got message at simtime %f\n",simtime);
}
#define MDL_START
static void mdlStart(SimStruct *S)
{
if (lcm)
ssSetErrorStatus(S, "LCM already exists. I've assumed that only one of these is used at a time (though it might not be catastrophic if there were more).");
lcm = lcm_create(NULL);
if (!lcm)
ssSetErrorStatus(S, "Failed to create LCM object in lcmLog block.");
char* channel_regex = mxArrayToString(ssGetSFcnParam(S, 0));
mexPrintf("Logging LCM channels '%s'\n",channel_regex);
lcm_subscribe(lcm, channel_regex, message_handler, NULL);
mxFree(channel_regex);
}
#define MDL_UPDATE
static void mdlUpdate(SimStruct *S, int_T tid)
{
UNUSED(tid);
simtime = ssGetT(S);
if (lcm)
lcm_handle(lcm);
}
#define MDL_OUTPUTS
static void mdlOutputs(SimStruct *S, int_T tid)
{
UNUSED(S);
UNUSED(tid);
}
static void mdlTerminate(SimStruct *S)
{
UNUSED(S);
if (lcm)
lcm_destroy(lcm);
char* log_variable_name = mxArrayToString(ssGetSFcnParam(S, 1));
mexPrintf("Writing LCM log to %s\n",log_variable_name);
// todo: write log to mxArray named in S
mxFree(log_variable_name);
}
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a
MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration
function */
#endif
<commit_msg>asynchronous poll seems to be working well<commit_after>#define S_FUNCTION_NAME lcmLogger
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
#include <inttypes.h>
#include <sys/select.h>
#include <lcm/lcm.h>
#define UNUSED(x) (void)(x)
static double simtime = -1.0;
static lcm_t* lcm = NULL;
#define MDL_INITIAL_SIZES
static void mdlInitializeSizes(SimStruct *S)
{
ssSetNumSFcnParams(S, 2); // lcm channel regex,
// workspace variable name to write log into
ssSetNumContStates(S, 0);
ssSetNumDiscStates(S, 0);
ssSetNumInputPorts(S, 0);
ssSetNumOutputPorts(S, 0);
ssSetNumSampleTimes(S, 1);
}
#define MDL_INITIALIZE_SAMPLE_TIMES
static void mdlInitializeSampleTimes(SimStruct *S)
{
ssSetSampleTime(S, 0, mxGetScalar(ssGetSFcnParam(S, 0)));
}
#define MDL_CHECK_PARAMETERS
#if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)
static void mdlCheckParameters(SimStruct *S)
{
UNUSED(S);
// todo: verify dialog parameters here
}
#endif /* MDL_CHECK_PARAMETERS */
static void message_handler (const lcm_recv_buf_t *rbuf, const char *channel, void *u)
{
mexPrintf("got message at simtime %f\n",simtime);
}
#define MDL_START
static void mdlStart(SimStruct *S)
{
if (lcm) ssSetErrorStatus(S, "LCM already exists. I've assumed that only one of these is used at a time (though it might not be catastrophic if there were more).");
lcm = lcm_create(NULL);
if (!lcm) ssSetErrorStatus(S, "Failed to create LCM object in lcmLog block.");
char* channel_regex = mxArrayToString(ssGetSFcnParam(S, 0));
mexPrintf("Logging LCM channels '%s'\n",channel_regex);
lcm_subscribe(lcm, channel_regex, message_handler, NULL);
mxFree(channel_regex);
}
#define MDL_OUTPUTS
static void mdlOutputs(SimStruct *S, int_T tid)
{
UNUSED(tid);
if (!lcm) ssSetErrorStatus(S, "Invalid LCM object.");
simtime = ssGetT(S);
// setup the LCM file descriptor for waiting.
int lcm_fd = lcm_get_fileno(lcm);
fd_set fds;
FD_ZERO(&fds);
FD_SET(lcm_fd, &fds);
// wait a limited amount of time for an incoming message
struct timeval timeout = {
0, // seconds
0 // microseconds
};
int status = select(lcm_fd + 1, &fds, 0, 0, &timeout);
if(status!=0 && FD_ISSET(lcm_fd, &fds)) {
// LCM has events ready to be processed.
mexPrintf("lcm_handle\n");
lcm_handle(lcm);
}
}
static void mdlTerminate(SimStruct *S)
{
UNUSED(S);
if (!lcm) ssSetErrorStatus(S, "Invalid LCM object.");
lcm_destroy(lcm);
lcm = NULL;
char* log_variable_name = mxArrayToString(ssGetSFcnParam(S, 1));
mexPrintf("Writing LCM log to %s\n",log_variable_name);
// todo: write log to mxArray named in S
mxFree(log_variable_name);
}
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a
MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration
function */
#endif
<|endoftext|>
|
<commit_before>// @(#)root/cont:$Id$
// Author: Fons Rademakers 04/08/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TSeqCollection //
// //
// Sequenceable collection abstract base class. TSeqCollection's have //
// an ordering relation, i.e. there is a first and last element. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TSeqCollection.h"
#include "TCollection.h"
#include "TVirtualMutex.h"
#include "TClass.h"
#include "TMethodCall.h"
ClassImp(TSeqCollection)
//______________________________________________________________________________
Int_t TSeqCollection::IndexOf(const TObject *obj) const
{
// Return index of object in collection. Returns -1 when object not found.
// Uses member IsEqual() to find object.
Int_t idx = 0;
TIter next(this);
TObject *ob;
while ((ob = next())) {
if (ob->IsEqual(obj)) return idx;
idx++;
}
return -1;
}
//______________________________________________________________________________
Int_t TSeqCollection::ObjCompare(TObject *a, TObject *b)
{
// Compare to objects in the collection. Use member Compare() of object a.
if (a == 0 && b == 0) return 0;
if (a == 0) return 1;
if (b == 0) return -1;
return a->Compare(b);
}
//______________________________________________________________________________
void TSeqCollection::QSort(TObject **a, Int_t first, Int_t last)
{
// Sort array of TObject pointers using a quicksort algorithm.
// Uses ObjCompare() to compare objects.
R__LOCKGUARD2(gCollectionMutex);
static TObject *tmp;
static int i; // "static" to save stack space
int j;
while (last - first > 1) {
i = first;
j = last;
for (;;) {
while (++i < last && ObjCompare(a[i], a[first]) < 0)
;
while (--j > first && ObjCompare(a[j], a[first]) > 0)
;
if (i >= j)
break;
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
if (j == first) {
++first;
continue;
}
tmp = a[first];
a[first] = a[j];
a[j] = tmp;
if (j - first < last - (j + 1)) {
QSort(a, first, j);
first = j + 1; // QSort(j + 1, last);
} else {
QSort(a, j + 1, last);
last = j; // QSort(first, j);
}
}
}
//______________________________________________________________________________
void TSeqCollection::QSort(TObject **a, Int_t nBs, TObject ***b, Int_t first, Int_t last)
{
// Sort array a of TObject pointers using a quicksort algorithm.
// Arrays b will be sorted just like a (a determines the sort).
// nBs is the number of TObject** arrays in b.
// Uses ObjCompare() to compare objects.
R__LOCKGUARD2(gCollectionMutex);
static TObject *tmp1, **tmp2;
static int i; // "static" to save stack space
int j,k;
static int depth = 0;
if(depth == 0 && nBs > 0) tmp2 = new TObject*[nBs];
depth++;
while (last - first > 1) {
i = first;
j = last;
for (;;) {
while (++i < last && ObjCompare(a[i], a[first]) < 0) {}
while (--j > first && ObjCompare(a[j], a[first]) > 0) {}
if (i >= j) break;
tmp1 = a[i]; for(k=0;k<nBs;k++) tmp2[k] = b[k][i];
a[i] = a[j]; for(k=0;k<nBs;k++) b[k][i] = b[k][j];
a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k];
}
if (j == first) {
++first;
continue;
}
tmp1 = a[first]; for(k=0;k<nBs;k++) tmp2[k] = b[k][first];
a[first] = a[j]; for(k=0;k<nBs;k++) b[k][first] = b[k][j];
a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k];
if (j - first < last - (j + 1)) {
QSort(a, nBs, b, first, j);
first = j + 1; // QSort(j + 1, last);
} else {
QSort(a, nBs, b, j + 1, last);
last = j; // QSort(first, j);
}
}
depth--;
if(depth == 0 && nBs > 0) delete [] tmp2;
}
//______________________________________________________________________________
Long64_t TSeqCollection::Merge(TCollection *list)
{
// Merge this collection with all collections coming in the input list. The
// input list must contain other collections of objects compatible with the
// ones in this collection and ordered in the same manner. For example, if this
// collection contains a TH1 object and a tree, all collections in the input
// list have to contain a histogram and a tree. In case the list contains
// collections, the objects in the input lists must also be collections with
// the same structure and number of objects.
//
// Example
// =========
// this list
// ____________ ---------------------|
// | A (TH1F) | __________ | L1 (TSeqCollection)|- [A1, B1(C1,D1,E1)]
// | B (TList)|-| C (TTree)| | L1 (TSeqCollection)|- [A2, B2(C2,D2,E2)]
// |__________| | D (TH1F) | | ... |- [...]
// | E (TH1F) | |____________________|
// |__________|
Long64_t nmerged = 0;
if (IsEmpty() || !list) {
Warning("Merge", "list is empty - nothing to merge");
return 0;
}
if (list->IsEmpty()) {
Warning("Merge", "input list is empty - nothing to merge with");
return 0;
}
TIter nextobject(this);
TIter nextlist(list);
TObject *object;
TObject *objtomerge;
TObject *collcrt;
TSeqCollection *templist;
TMethodCall callEnv;
Int_t indobj = 0;
while ((object = nextobject())) { // loop objects in this collection
// If current object is not mergeable just skip it
if (!object->IsA()) {
indobj++; // current object non-mergeable, go to next object
continue;
}
callEnv.InitWithPrototype(object->IsA(), "Merge", "TCollection*");
if (!callEnv.IsValid()) {
indobj++; // no Merge() interface, go to next object
continue;
}
// Current object mergeable - get corresponding objects in input lists
templist = (TSeqCollection*)IsA()->New();
nextlist.Reset();
while ((collcrt = nextlist())) { // loop input lists
if (!collcrt->InheritsFrom(TSeqCollection::Class())) {
Error("Merge", "some objects in the input list are not collections - merging aborted");
delete templist;
return 0;
}
// The next object to be merged with is a collection
// the iterator skips the 'holes' the collections, we also need to do so.
objtomerge = ((TSeqCollection*)collcrt)->At(indobj);
while (objtomerge == 0
&& indobj < ((TSeqCollection*)collcrt)->LastIndex()
) {
++indobj;
objtomerge = ((TSeqCollection*)collcrt)->At(indobj);
}
if (object->IsA() != objtomerge->IsA()) {
Error("Merge", "object of type %s at index %d not matching object of type %s in input list",
object->ClassName(), indobj, objtomerge->ClassName());
delete templist;
return 0;
}
// Add object at index indobj in the temporary list
templist->Add(objtomerge);
nmerged++;
}
// Merge current object with objects in the temporary list
callEnv.SetParam((Long_t) templist);
callEnv.Execute(object);
delete templist;
indobj++;
}
return nmerged;
}
<commit_msg>From Andrei: Adds a protection in the Merge function when the object to merge is missing.<commit_after>// @(#)root/cont:$Id$
// Author: Fons Rademakers 04/08/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TSeqCollection //
// //
// Sequenceable collection abstract base class. TSeqCollection's have //
// an ordering relation, i.e. there is a first and last element. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TSeqCollection.h"
#include "TCollection.h"
#include "TVirtualMutex.h"
#include "TClass.h"
#include "TMethodCall.h"
ClassImp(TSeqCollection)
//______________________________________________________________________________
Int_t TSeqCollection::IndexOf(const TObject *obj) const
{
// Return index of object in collection. Returns -1 when object not found.
// Uses member IsEqual() to find object.
Int_t idx = 0;
TIter next(this);
TObject *ob;
while ((ob = next())) {
if (ob->IsEqual(obj)) return idx;
idx++;
}
return -1;
}
//______________________________________________________________________________
Int_t TSeqCollection::ObjCompare(TObject *a, TObject *b)
{
// Compare to objects in the collection. Use member Compare() of object a.
if (a == 0 && b == 0) return 0;
if (a == 0) return 1;
if (b == 0) return -1;
return a->Compare(b);
}
//______________________________________________________________________________
void TSeqCollection::QSort(TObject **a, Int_t first, Int_t last)
{
// Sort array of TObject pointers using a quicksort algorithm.
// Uses ObjCompare() to compare objects.
R__LOCKGUARD2(gCollectionMutex);
static TObject *tmp;
static int i; // "static" to save stack space
int j;
while (last - first > 1) {
i = first;
j = last;
for (;;) {
while (++i < last && ObjCompare(a[i], a[first]) < 0)
;
while (--j > first && ObjCompare(a[j], a[first]) > 0)
;
if (i >= j)
break;
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
if (j == first) {
++first;
continue;
}
tmp = a[first];
a[first] = a[j];
a[j] = tmp;
if (j - first < last - (j + 1)) {
QSort(a, first, j);
first = j + 1; // QSort(j + 1, last);
} else {
QSort(a, j + 1, last);
last = j; // QSort(first, j);
}
}
}
//______________________________________________________________________________
void TSeqCollection::QSort(TObject **a, Int_t nBs, TObject ***b, Int_t first, Int_t last)
{
// Sort array a of TObject pointers using a quicksort algorithm.
// Arrays b will be sorted just like a (a determines the sort).
// nBs is the number of TObject** arrays in b.
// Uses ObjCompare() to compare objects.
R__LOCKGUARD2(gCollectionMutex);
static TObject *tmp1, **tmp2;
static int i; // "static" to save stack space
int j,k;
static int depth = 0;
if(depth == 0 && nBs > 0) tmp2 = new TObject*[nBs];
depth++;
while (last - first > 1) {
i = first;
j = last;
for (;;) {
while (++i < last && ObjCompare(a[i], a[first]) < 0) {}
while (--j > first && ObjCompare(a[j], a[first]) > 0) {}
if (i >= j) break;
tmp1 = a[i]; for(k=0;k<nBs;k++) tmp2[k] = b[k][i];
a[i] = a[j]; for(k=0;k<nBs;k++) b[k][i] = b[k][j];
a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k];
}
if (j == first) {
++first;
continue;
}
tmp1 = a[first]; for(k=0;k<nBs;k++) tmp2[k] = b[k][first];
a[first] = a[j]; for(k=0;k<nBs;k++) b[k][first] = b[k][j];
a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k];
if (j - first < last - (j + 1)) {
QSort(a, nBs, b, first, j);
first = j + 1; // QSort(j + 1, last);
} else {
QSort(a, nBs, b, j + 1, last);
last = j; // QSort(first, j);
}
}
depth--;
if(depth == 0 && nBs > 0) delete [] tmp2;
}
//______________________________________________________________________________
Long64_t TSeqCollection::Merge(TCollection *list)
{
// Merge this collection with all collections coming in the input list. The
// input list must contain other collections of objects compatible with the
// ones in this collection and ordered in the same manner. For example, if this
// collection contains a TH1 object and a tree, all collections in the input
// list have to contain a histogram and a tree. In case the list contains
// collections, the objects in the input lists must also be collections with
// the same structure and number of objects.
//
// Example
// =========
// this list
// ____________ ---------------------|
// | A (TH1F) | __________ | L1 (TSeqCollection)|- [A1, B1(C1,D1,E1)]
// | B (TList)|-| C (TTree)| | L1 (TSeqCollection)|- [A2, B2(C2,D2,E2)]
// |__________| | D (TH1F) | | ... |- [...]
// | E (TH1F) | |____________________|
// |__________|
Long64_t nmerged = 0;
if (IsEmpty() || !list) {
Warning("Merge", "list is empty - nothing to merge");
return 0;
}
if (list->IsEmpty()) {
Warning("Merge", "input list is empty - nothing to merge with");
return 0;
}
TIter nextobject(this);
TIter nextlist(list);
TObject *object;
TObject *objtomerge;
TObject *collcrt;
TSeqCollection *templist;
TMethodCall callEnv;
Int_t indobj = 0;
while ((object = nextobject())) { // loop objects in this collection
// If current object is not mergeable just skip it
if (!object->IsA()) {
indobj++; // current object non-mergeable, go to next object
continue;
}
callEnv.InitWithPrototype(object->IsA(), "Merge", "TCollection*");
if (!callEnv.IsValid()) {
indobj++; // no Merge() interface, go to next object
continue;
}
// Current object mergeable - get corresponding objects in input lists
templist = (TSeqCollection*)IsA()->New();
nextlist.Reset();
Int_t indcoll = 0;
while ((collcrt = nextlist())) { // loop input lists
if (!collcrt->InheritsFrom(TSeqCollection::Class())) {
Error("Merge", "some objects in the input list are not collections - merging aborted");
delete templist;
return 0;
}
// The next object to be merged with is a collection
// the iterator skips the 'holes' the collections, we also need to do so.
objtomerge = ((TSeqCollection*)collcrt)->At(indobj);
if (!objtomerge) {
Warning("Merge", "Object of type %s (position %d in list) not found in list %d. Continuing...", object->ClassName(), indobj, indcoll);
continue;
}
/*
// Dangerous - may try to merge non-corresponding histograms (A.G)
while (objtomerge == 0
&& indobj < ((TSeqCollection*)collcrt)->LastIndex()
) {
++indobj;
objtomerge = ((TSeqCollection*)collcrt)->At(indobj);
}
*/
if (object->IsA() != objtomerge->IsA()) {
Error("Merge", "object of type %s at index %d not matching object of type %s in input list",
object->ClassName(), indobj, objtomerge->ClassName());
delete templist;
return 0;
}
// Add object at index indobj in the temporary list
templist->Add(objtomerge);
nmerged++;
}
// Merge current object with objects in the temporary list
callEnv.SetParam((Long_t) templist);
callEnv.Execute(object);
delete templist;
indobj++;
}
return nmerged;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: objectcontactofpageview.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2004-10-12 10:03:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SDR_CONTACT_OBJECTCONTACTOFPAGEVIEW_HXX
#define _SDR_CONTACT_OBJECTCONTACTOFPAGEVIEW_HXX
#ifndef _SDR_CONTACT_OBJECTCONTACT_HXX
#include <svx/sdr/contact/objectcontact.hxx>
#endif
#ifndef _SV_VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
// predeclarations
class SdrPageViewWindow;
class SdrPage;
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace contact
{
class ObjectContactOfPageView : public ObjectContact
{
protected:
// the owner of this ObjectContactOfPageView. Set from constructor and not
// to be changed in any way.
SdrPageViewWindow& mrPageViewWindow;
// The last remembered StartPoint of the hierarchy
SdrPage* mpRememberedStartPage;
// The VirtualDevice for PreRendering
VirtualDevice maPreRenderDevice;
// Create and set the ExpandPaintClipRegion. This needs to be done before
// any of the objects gets really painted because it relies on the invalidated
// and not painted state of the single objects.
void ExpandPaintClipRegion(DisplayInfo& rDisplayInfo);
// Process the whole displaying, the real version
void DoProcessDisplay(DisplayInfo& rDisplayInfo);
// Decide if to PreRender
sal_Bool DoPreRender(DisplayInfo& rDisplayInfo) const;
// The PreRenderer itself which creates the PreRenderedBitmap
// using the PreRenderDevice.
void PreRender(DisplayInfo& rDisplayInfo);
// Update Draw Hierarchy data
virtual void EnsureValidDrawHierarchy(DisplayInfo& rDisplayInfo);
public:
// basic constructor, used from SdrPageViewWindow.
ObjectContactOfPageView(SdrPageViewWindow& rPageViewWindow);
// The destructor. When PrepareDelete() was not called before (see there)
// warnings will be generated in debug version if there are still contacts
// existing.
virtual ~ObjectContactOfPageView();
// A ViewObjectContact was deleted and shall be forgotten.
// #i29181# Overload to clear selection at associated view
virtual void RemoveViewObjectContact(ViewObjectContact& rVOContact);
// Pre-Process the whole displaying. The default implementation
// calls EnsureValidDrawHierarchy() to ensure a valid draw hierarchy.
virtual void PreProcessDisplay(DisplayInfo& rDisplayInfo);
// Process the whole displaying
virtual void ProcessDisplay(DisplayInfo& rDisplayInfo);
// test if visualizing of entered groups is switched on at all
virtual sal_Bool DoVisualizeEnteredGroup() const;
// Get the active group (the entered group). To get independent
// from the old object/view classes return values use the new
// classes.
virtual ViewContact* GetActiveGroupContact() const;
// Invalidate given rectangle at the window/output which is represented by
// this ObjectContact.
virtual void InvalidatePartOfView(const Rectangle& rRectangle) const;
// Get info about the need to visualize GluePoints. The default
// is that it is not necessary.
virtual sal_Bool AreGluePointsVisible() const;
// check if text animation is allowed.
virtual sal_Bool IsTextAnimationAllowed() const;
// check if graphic animation is allowed.
virtual sal_Bool IsGraphicAnimationAllowed() const;
// check if asynchronious graphis loading is allowed. Default is sal_False.
virtual sal_Bool IsAsynchronGraphicsLoadingAllowed() const;
// check if buffering of MasterPages is allowed. Default is sal_False.
virtual sal_Bool IsMasterPageBufferingAllowed() const;
public:
// internal access to SdrPageViewWindow
SdrPageViewWindow& GetPageViewWindow() const;
// internal access to SdrPage of PageView
SdrPage* GetSdrPage() const;
};
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
#endif //_SDR_CONTACT_OBJECTCONTACTOFPAGEVIEW_HXX
// eof
<commit_msg>INTEGRATION: CWS aw022 (1.6.118); FILE MERGED 2004/11/19 11:32:07 aw 1.6.118.1: #i37934#<commit_after>/*************************************************************************
*
* $RCSfile: objectcontactofpageview.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2004-12-13 08:53:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SDR_CONTACT_OBJECTCONTACTOFPAGEVIEW_HXX
#define _SDR_CONTACT_OBJECTCONTACTOFPAGEVIEW_HXX
#ifndef _SDR_CONTACT_OBJECTCONTACT_HXX
#include <svx/sdr/contact/objectcontact.hxx>
#endif
#ifndef _SV_VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
// predeclarations
class SdrPageViewWindow;
class SdrPage;
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace contact
{
class ObjectContactOfPageView : public ObjectContact
{
protected:
// the owner of this ObjectContactOfPageView. Set from constructor and not
// to be changed in any way.
SdrPageViewWindow& mrPageViewWindow;
// The last remembered StartPoint of the hierarchy
SdrPage* mpRememberedStartPage;
// The VirtualDevice for PreRendering
VirtualDevice maPreRenderDevice;
// Create and set the ExpandPaintClipRegion. This needs to be done before
// any of the objects gets really painted because it relies on the invalidated
// and not painted state of the single objects.
void ExpandPaintClipRegion(DisplayInfo& rDisplayInfo);
// Process the whole displaying, the real version
void DoProcessDisplay(DisplayInfo& rDisplayInfo);
// Decide if to PreRender
sal_Bool DoPreRender(DisplayInfo& rDisplayInfo) const;
// The PreRenderer itself which creates the PreRenderedBitmap
// using the PreRenderDevice.
void PreRender(DisplayInfo& rDisplayInfo);
// Update Draw Hierarchy data
virtual void EnsureValidDrawHierarchy(DisplayInfo& rDisplayInfo);
public:
// basic constructor, used from SdrPageViewWindow.
ObjectContactOfPageView(SdrPageViewWindow& rPageViewWindow);
// The destructor. When PrepareDelete() was not called before (see there)
// warnings will be generated in debug version if there are still contacts
// existing.
virtual ~ObjectContactOfPageView();
// A ViewObjectContact was deleted and shall be forgotten.
// #i29181# Overload to clear selection at associated view
virtual void RemoveViewObjectContact(ViewObjectContact& rVOContact);
// Pre-Process the whole displaying. The default implementation
// calls EnsureValidDrawHierarchy() to ensure a valid draw hierarchy.
virtual void PreProcessDisplay(DisplayInfo& rDisplayInfo);
// Process the whole displaying
virtual void ProcessDisplay(DisplayInfo& rDisplayInfo);
// test if visualizing of entered groups is switched on at all
virtual sal_Bool DoVisualizeEnteredGroup() const;
// Get the active group (the entered group). To get independent
// from the old object/view classes return values use the new
// classes.
virtual ViewContact* GetActiveGroupContact() const;
// Invalidate given rectangle at the window/output which is represented by
// this ObjectContact.
virtual void InvalidatePartOfView(const Rectangle& rRectangle) const;
// #i37394# Non-painted object was changed. Test for potentially
// getting visible
virtual void ObjectGettingPotentiallyVisible(const ViewObjectContact& rVOC) const;
// Get info about the need to visualize GluePoints. The default
// is that it is not necessary.
virtual sal_Bool AreGluePointsVisible() const;
// check if text animation is allowed.
virtual sal_Bool IsTextAnimationAllowed() const;
// check if graphic animation is allowed.
virtual sal_Bool IsGraphicAnimationAllowed() const;
// check if asynchronious graphis loading is allowed. Default is sal_False.
virtual sal_Bool IsAsynchronGraphicsLoadingAllowed() const;
// check if buffering of MasterPages is allowed. Default is sal_False.
virtual sal_Bool IsMasterPageBufferingAllowed() const;
public:
// internal access to SdrPageViewWindow
SdrPageViewWindow& GetPageViewWindow() const;
// internal access to SdrPage of PageView
SdrPage* GetSdrPage() const;
};
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
#endif //_SDR_CONTACT_OBJECTCONTACTOFPAGEVIEW_HXX
// eof
<|endoftext|>
|
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3148
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3148 to 3149<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3149
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>/* *********************************************************************************
* File : AddTaskNetParticle.C
* Authors : Jochen Thaeder <jochen@thaeder.de>
* Michael Weber <m.weber@cern.ch>
* *********************************************************************************
* Configuring NetParticle Task:
* - ARGUMENTS :
* name -> Name of the task, containing particle type :
* Currently : Proton, Pion, Kaon, Charge
* isModeDist -> Fill Distributions
* isModeEff -> Fill Efficiency/Contamination ThnSparse
* isModeDCA -> Fill DCA ThnSparse
* isModeQA -> Fill QA ThnSparse
* isModeAOD -> Use AOD input
* isCreateCSC -> Prepare for CrossSectionCorrection
* - requires isModeEff to be set
* - Proton only
* isSetExt -> 1 if want to set pt, nSigma from arguments
* 0 takes default values
*
* modeCSC -> Use differnt Pt cut for
* 0 : TPC+TOF
* 1 : TPC
* modeCuts -> Different Cut scenarios
* 0 : Standard cuts
* 1 : LF cuts
* modePID -> PID Strategy
* -1 : Default -> 7 (modeCuts=0) and 5 (modeCuts=1)
* 0 : TPC(TPClow+TPCHigh)
* 1 : ITS
* 2 : TOF
* 3 : ITS+TPC(TPClow+TPCHigh)
* 4 : TPC(TPClow+TPCHigh)+TOF
* 5 : TPC(TPClow+TPCHigh)+TOF for pT >= fMinPtForTOFRequired TOF is required, below, only used if there
* 6 : TPC(TPClow+TPCHigh)+ITS+TOF with TOF only for those tracks which have TOF information
* 7 : TPC(TPClow+TPCHigh)+ITS+TOF for pT >= fMinPtForTOFRequired TOF is required, below, only used if there
* 8 : TPC(TPClow+TPCHigh)+ITS+TOF
*
* *********************************************************************************
* - PID Strategy
*
* *********************************************************************************
* - OUTPUT CONTAINER : #N = 5
* (1) - Standard Output, Distributions
* (2) - Efficiency ThnSparse
* (3) - Contamination ThnSparse
* (4) - DCA ThnSparse
* (5) - QA ThnSparse
*
********************************************************************************* */
AliAnalysisTask *AddTaskNetParticle(const Char_t *name = "ITS_NetProton",
Bool_t isModeDist = kTRUE,
Bool_t isModeEff = kFALSE,
Bool_t isModeDCA = kFALSE,
Bool_t isModeQA = kFALSE,
Bool_t isCreateCSC = kFALSE,
Bool_t isModeAOD = kFALSE,
Bool_t isSetExt = kFALSE,
Int_t aodFilterBit = 1024, /* 1024 = RAA cuts */
Int_t modeCSC = 0,
Int_t modeCuts = 0,
Int_t modePID =-1,
Float_t gMinPt = 0.3,
Float_t gMaxPt = 2.5,
Float_t gMinPtForTof = 0.21,
Float_t gMaxPtForTPClow = 0.69,
Float_t gMinPtEff = 0.3,
Float_t gMaxPtEff = 2.5,
Float_t gSigmaITS = 4.0,
Float_t gSigmaTPC = 4.0,
Float_t gSigmaTPClow = 3.0,
Float_t gSigmaTOF = 4.0) {
TString sName(name);
if (isCreateCSC && !isModeEff) {
Error("AddTaskNetParticle", "Creating CrossSectionCorrection needs 'isModeEff' to be set.");
return NULL;
}
// ----------------------------------------------
// -- Get the current analysis manager
// ----------------------------------------------
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskNetParticle", "No analysis manager found.");
return NULL;
}
// ----------------------------------------------
// -- Check for MC
// ----------------------------------------------
Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL);
if (isMC)
Info("AddTaskNetParticle", "This task has MC.");
// ----------------------------------------------
// -- Create task
// ----------------------------------------------
AliAnalysisTaskNetParticle *task = new AliAnalysisTaskNetParticle("AliAnalysisTaskNetParticle");
if (!task) {
Error("AddTaskNetParticle", "Task could not be created.");
return NULL;
}
// ----------------------------------------------
// -- Configure flags
// ----------------------------------------------
if (isMC)
task->SetIsMC();
if (isModeEff)
task->SetModeEffCreation(1); // => 1 = on | 0 = off (default)
if (isModeDCA)
task->SetModeDCACreation(1); // => 1 = on | 0 = off (default)
if (isModeDist)
task->SetModeDistCreation(1); // => 1 = on | 0 = off (default)
if (isModeAOD) {
task->SetIsAOD(1); // => 1 = AOD | 0 = ESD (default)
task->SetTrackFilterBit(aodFilterBit);
}
if (isModeQA)
task->SetModeQACreation(1); // => 1 = on | 0 = off (default)
// ----------------------------------------------
// -- Create helper class
// ----------------------------------------------
AliAnalysisNetParticleHelper *helper = new AliAnalysisNetParticleHelper;
if (!helper) {
Error("AddTaskNetParticle", "Helper could not be created.");
delete task;
return NULL;
}
task->SetNetParticleHelper(helper);
// ----------------------------------------------
// -- Set particle type
// ----------------------------------------------
Float_t minPt, maxPt, minPtEff, maxPtEff, minPtForTOF, etaMax, etaMaxEff, nSigmaITS, nSigmaTPC, nSigmaTPClow, nSigmaTOF, maxPtForTPClow;
Int_t pidStrategy;
if (sName.Contains("Proton")) {
helper->SetParticleSpecies(AliPID::kProton);
minPtForTOF = 0.69; // minPtForTOF = 0.21;
maxPtForTPClow = 0.69;
minPt = 0.5; maxPt = 2.0; // minPt = 0.22; maxPt = 4.5;
minPtEff = 0.3; maxPtEff = 2.5; // minPtEff = 0.22; maxPtEff = 4.5;
etaMax = 0.8;
etaMaxEff = 0.8;
nSigmaITS = 4.0; nSigmaTPC = 4.0; nSigmaTPClow = 3.0; nSigmaTOF = 4.0;
// For TPC only case
if (isCreateCSC && modeCSC == 1)
minPtForTOF = maxPtEff;
}
else if (sName.Contains("Pion")) {
helper->SetParticleSpecies(AliPID::kPion);
minPtForTOF = 0.3;
maxPtForTPClow = 0.69;
minPt = 0.3; maxPt = 1.5;
minPtEff = 0.3; maxPtEff = 2.5;
etaMax = 8.8;
etaMaxEff = 8.8;
nSigmaITS = 4.0; nSigmaTPC = 4.0; nSigmaTPClow = 3.0; nSigmaTOF = 4.0;
pidStrategy = 1;
}
else if (sName.Contains("Kaon")) {
helper->SetParticleSpecies(AliPID::kKaon);
minPtForTOF = 0.3;
maxPtForTPClow = 0.69;
minPt = 0.3; maxPt = 1.5;
minPtEff = 0.3; maxPtEff = 2.5;
etaMax = 0.8;
etaMaxEff = 0.8;
nSigmaITS = 4.0; nSigmaTPC = 4.0; nSigmaTPClow = 3.0; nSigmaTOF = 4.0;
pidStrategy = 1;
}
else if (sName.Contains("Charge")) {
helper->SetUsePID(kFALSE);
minPtForTOF = 0.1;
maxPtForTPClow = 0.1;
minPt = 0.1; maxPt = 2.5;
minPtEff = 0.1; maxPtEff = 3.0;
etaMax = 0.8;
etaMaxEff = 0.8;
nSigmaITS = -1.; nSigmaTPC = -1.; nSigmaTOF = -1.;
pidStrategy = 1;
}
else {
Error("AddTaskNetParticle", "Unknown Particle type.");
delete task;
return NULL;
}
// ----------------------------------------------
// -- use value arguments --
// ----------------------------------------------
if (isSetExt) {
minPt = gMinPt;
maxPt = gMaxPt;
minPtForTOF = gMinPtForTof;
maxPtForTPClow = gMaxPtForTPClow;
minPtEff = gMinPtEff;
maxPtEff = gMaxPtEff;
nSigmaITS = gSigmaITS;
nSigmaTPC = gSigmaTPC;
nSigmaTPClow = gSigmaTPClow;
nSigmaTOF = gSigmaTOF;
}
// ----------------------------------------------
// -- PID Strategy
// ----------------------------------------------
if (modePID == -1) { // default
pidStrategy = 7; // 7: ITS + TPC + TOF (using minPtForTOF)
if (modeCuts == 1)
pidStrategy = 5; // 5: TPC + TOF (using minPtForTOF)
}
else
pidStrategy = modePID;
// ----------------------------------------------
// -- Read Environment Variables
// ----------------------------------------------
ifstream in;
in.open("setRunENV.txt");
TString current;
while(in.good()) {
in >> current;
TObjArray *arr = current.Tokenize('=');
if (!arr)
continue;
TObjString* oKey = dynamic_cast<TObjString*>(arr->At(0));
TObjString* oValue = dynamic_cast<TObjString*>(arr->At(1));
if (!oKey)
continue;
TString key(oKey->GetString());
TString value(oValue->GetString());
if (!key.CompareTo("NETPARTICLE_PID_STRATEGY")) {
pidStrategy = value.Atoi();
printf(">>>> USE NETPARTICLE_PID_STRATEGY %d\n", pidStrategy);
}
if (!key.CompareTo("NETPARTICLE_NSIGMAMAX_ITS")) {
nSigmaITS = value.Atof();
printf(">>>> USE NETPARTICLE_NSIGMAMAX_ITS %.2f\n", nSigmaITS);
}
if (!key.CompareTo("NETPARTICLE_NSIGMAMAX_TPC")) {
nSigmaTPC = value.Atof();
printf(">>>> USE NETPARTICLE_NSIGMAMAX_TPC %.2f\n", nSigmaTPC);
}
if (!key.CompareTo("NETPARTICLE_NSIGMAMAX_TOF")) {
nSigmaTOF = value.Atof();
printf(">>>> USE NETPARTICLE_NSIGMAMAX_TOF %.2f\n", nSigmaTOF);
}
arr->Clear();
delete arr;
}
in.close();
// ----------------------------------------------
// -- Configure cuts
// ----------------------------------------------
// -- Set cut flags
task->SetESDTrackCutMode(modeCuts); // => 0 = normal | 1 = LF
// -- Set analysis ranges
task->SetEtaMax(etaMax); // eta cut
task->SetEtaMaxEff(etaMaxEff); // eta cut for efficiency
task->SetPtRange(minPt, maxPt); // pt cut range for the analysis
task->SetPtRangeEff(minPtEff, maxPtEff); // pt cut range for the correction / efficiency / contamination creation
// ----------------------------------------------
// -- Configure cuts - helper class
// ----------------------------------------------
// -- Set standard event cuts
helper->SetVertexZMax(10.);
helper->SetCentralityBinMax(7);
// -- Set track event cuts
helper->SetRapidityMax(0.5);
// helper->SetRapidityMax(0.2);
helper->SetMinTrackLengthMC(70.);
helper->SetNSigmaMaxCdd(0.); // 3. || ->> Turn off sigmaDCA cuts for now
helper->SetNSigmaMaxCzz(0.); // 3. || ->> Turn off sigmaDCA cuts for now
helper->SetPhiRange(0., 3.88); // Only used if requested in task - default is TwoPi
// -- Set pid cuts
helper->SetPIDStrategy(pidStrategy);
helper->SetNSigmaMaxITS(nSigmaITS);
helper->SetNSigmaMaxTPC(nSigmaTPC);
helper->SetNSigmaMaxTPClow(nSigmaTPClow);
helper->SetNSigmaMaxTOF(nSigmaTOF);
helper->SetMinPtForTOFRequired(minPtForTOF);
helper->SetMaxPtForTPClow(maxPtForTPClow);
// -- Set N sub samples
helper->SetNSubSamples(20);
// ----------------------------------------------
// -- Add task to the ANALYSIS manager
// ----------------------------------------------
mgr->AddTask(task);
// ----------------------------------------------
// -- data containers - input
// ----------------------------------------------
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
// ----------------------------------------------
// -- data containers - output
// ----------------------------------------------
TString outputFileName = Form("%s:%s", AliAnalysisManager::GetCommonFileName(), name);
TString outputQAFileName = Form("%s:%s", AliAnalysisManager::GetCommonFileName(), name);
AliAnalysisDataContainer *coutput = mgr->CreateContainer(name, TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
AliAnalysisDataContainer *coutputEff = mgr->CreateContainer(Form("%s_eff", name), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
AliAnalysisDataContainer *coutputCont = mgr->CreateContainer(Form("%s_cont", name), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
AliAnalysisDataContainer *coutputDca = mgr->CreateContainer(Form("%s_dca", name), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
AliAnalysisDataContainer *coutputQA = mgr->CreateContainer(Form("%sQA", name), TList::Class(), AliAnalysisManager::kOutputContainer, outputQAFileName);
mgr->ConnectInput (task, 0, cinput );
mgr->ConnectOutput (task, 1, coutput);
mgr->ConnectOutput (task, 2, coutputEff);
mgr->ConnectOutput (task, 3, coutputCont);
mgr->ConnectOutput (task, 4, coutputDca);
mgr->ConnectOutput (task, 5, coutputQA);
return task;
}
<commit_msg>Update NetParticle: sjena<commit_after>/* *********************************************************************************
* File : AddTaskNetParticle.C
* Authors : Jochen Thaeder <jochen@thaeder.de>
* Michael Weber <m.weber@cern.ch>
* *********************************************************************************
* Configuring NetParticle Task:
* - ARGUMENTS :
* name -> Name of the task, containing particle type :
* Currently : Proton, Pion, Kaon, Charge
* isModeDist -> Fill Distributions
* isModeEff -> Fill Efficiency/Contamination ThnSparse
* isModeDCA -> Fill DCA ThnSparse
* isModeQA -> Fill QA ThnSparse
* isModeAOD -> Use AOD input
* isCreateCSC -> Prepare for CrossSectionCorrection
* - requires isModeEff to be set
* - Proton only
* isSetExt -> 1 if want to set pt, nSigma from arguments
* 0 takes default values
*
* modeCSC -> Use differnt Pt cut for
* 0 : TPC+TOF
* 1 : TPC
* modeCuts -> Different Cut scenarios
* 0 : Standard cuts
* 1 : LF cuts
* modePID -> PID Strategy
* -1 : Default -> 7 (modeCuts=0) and 5 (modeCuts=1)
* 0 : TPC(TPClow+TPCHigh)
* 1 : ITS
* 2 : TOF
* 3 : ITS+TPC(TPClow+TPCHigh)
* 4 : TPC(TPClow+TPCHigh)+TOF
* 5 : TPC(TPClow+TPCHigh)+TOF for pT >= fMinPtForTOFRequired TOF is required, below, only used if there
* 6 : TPC(TPClow+TPCHigh)+ITS+TOF with TOF only for those tracks which have TOF information
* 7 : TPC(TPClow+TPCHigh)+ITS+TOF for pT >= fMinPtForTOFRequired TOF is required, below, only used if there
* 8 : TPC(TPClow+TPCHigh)+ITS+TOF
*
* *********************************************************************************
* - PID Strategy
*
* *********************************************************************************
* - OUTPUT CONTAINER : #N = 5
* (1) - Standard Output, Distributions
* (2) - Efficiency ThnSparse
* (3) - Contamination ThnSparse
* (4) - DCA ThnSparse
* (5) - QA ThnSparse
*
********************************************************************************* */
AliAnalysisTask *AddTaskNetParticle(const Char_t *name = "ITS_NetProton",
Bool_t isModeDist = kTRUE,
Bool_t isModeEff = kFALSE,
Bool_t isModeDCA = kFALSE,
Bool_t isModeQA = kFALSE,
Bool_t isCreateCSC = kFALSE,
Bool_t isModeAOD = kFALSE,
Bool_t isSetExt = kFALSE,
Int_t aodFilterBit = 1024, /* 1024 = RAA cuts */
Int_t modeCSC = 0,
Int_t modeCuts = 0,
Int_t modePID =-1,
Float_t gMinPt = 0.3,
Float_t gMaxPt = 2.5,
Float_t gMinPtForTof = 0.21,
Float_t gMaxPtForTPClow = 0.69,
Float_t gMinPtEff = 0.3,
Float_t gMaxPtEff = 2.5,
Float_t gSigmaITS = 4.0,
Float_t gSigmaTPC = 4.0,
Float_t gSigmaTPClow = 3.0,
Float_t gSigmaTOF = 4.0) {
TString sName(name);
if (isCreateCSC && !isModeEff) {
Error("AddTaskNetParticle", "Creating CrossSectionCorrection needs 'isModeEff' to be set.");
return NULL;
}
// ----------------------------------------------
// -- Get the current analysis manager
// ----------------------------------------------
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskNetParticle", "No analysis manager found.");
return NULL;
}
// ----------------------------------------------
// -- Check for MC
// ----------------------------------------------
Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL);
if (isMC)
Info("AddTaskNetParticle", "This task has MC.");
// ----------------------------------------------
// -- Create task
// ----------------------------------------------
AliAnalysisTaskNetParticle *task = new AliAnalysisTaskNetParticle("AliAnalysisTaskNetParticle");
if (!task) {
Error("AddTaskNetParticle", "Task could not be created.");
return NULL;
}
// ----------------------------------------------
// -- Configure flags
// ----------------------------------------------
if (isMC)
task->SetIsMC();
if (isModeEff)
task->SetModeEffCreation(1); // => 1 = on | 0 = off (default)
if (isModeDCA)
task->SetModeDCACreation(1); // => 1 = on | 0 = off (default)
if (isModeDist)
task->SetModeDistCreation(1); // => 1 = on | 0 = off (default)
if (isModeAOD) {
task->SetIsAOD(1); // => 1 = AOD | 0 = ESD (default)
task->SetTrackFilterBit(aodFilterBit);
}
if (isModeQA)
task->SetModeQACreation(1); // => 1 = on | 0 = off (default)
// ----------------------------------------------
// -- Create helper class
// ----------------------------------------------
AliAnalysisNetParticleHelper *helper = new AliAnalysisNetParticleHelper;
if (!helper) {
Error("AddTaskNetParticle", "Helper could not be created.");
delete task;
return NULL;
}
task->SetNetParticleHelper(helper);
// ----------------------------------------------
// -- Set particle type
// ----------------------------------------------
Float_t minPt, maxPt, minPtEff, maxPtEff, minPtForTOF, etaMax, etaMaxEff, nSigmaITS, nSigmaTPC, nSigmaTPClow, nSigmaTOF, maxPtForTPClow;
Int_t pidStrategy;
if (sName.Contains("Proton")) {
helper->SetParticleSpecies(AliPID::kProton);
minPtForTOF = 0.69; // minPtForTOF = 0.21;
maxPtForTPClow = 0.69;
minPt = 0.5; maxPt = 2.0; // minPt = 0.22; maxPt = 4.5;
minPtEff = 0.3; maxPtEff = 2.5; // minPtEff = 0.22; maxPtEff = 4.5;
etaMax = 0.8;
etaMaxEff = 0.8;
nSigmaITS = 4.0; nSigmaTPC = 4.0; nSigmaTPClow = 3.0; nSigmaTOF = 4.0;
// For TPC only case
if (isCreateCSC && modeCSC == 1)
minPtForTOF = maxPtEff;
}
else if (sName.Contains("Pion")) {
helper->SetParticleSpecies(AliPID::kPion);
minPtForTOF = 0.3;
maxPtForTPClow = 0.69;
minPt = 0.3; maxPt = 1.5;
minPtEff = 0.3; maxPtEff = 2.5;
etaMax = 8.8;
etaMaxEff = 8.8;
nSigmaITS = 4.0; nSigmaTPC = 4.0; nSigmaTPClow = 3.0; nSigmaTOF = 4.0;
pidStrategy = 1;
}
else if (sName.Contains("Kaon")) {
helper->SetParticleSpecies(AliPID::kKaon);
minPtForTOF = 0.3;
maxPtForTPClow = 0.69;
minPt = 0.3; maxPt = 1.5;
minPtEff = 0.3; maxPtEff = 2.5;
etaMax = 0.8;
etaMaxEff = 0.8;
nSigmaITS = 4.0; nSigmaTPC = 4.0; nSigmaTPClow = 3.0; nSigmaTOF = 4.0;
pidStrategy = 1;
}
else if (sName.Contains("Charge")) {
helper->SetUsePID(kFALSE);
minPtForTOF = 0.1;
maxPtForTPClow = 0.1;
minPt = 0.1; maxPt = 2.5;
minPtEff = 0.1; maxPtEff = 3.0;
etaMax = 0.8;
etaMaxEff = 0.8;
nSigmaITS = -1.; nSigmaTPC = -1.; nSigmaTOF = -1.;
pidStrategy = 1;
}
else {
Error("AddTaskNetParticle", "Unknown Particle type.");
delete task;
return NULL;
}
// ----------------------------------------------
// -- use value arguments --
// ----------------------------------------------
if (isSetExt) {
minPt = gMinPt;
maxPt = gMaxPt;
minPtForTOF = gMinPtForTof;
maxPtForTPClow = gMaxPtForTPClow;
minPtEff = gMinPtEff;
maxPtEff = gMaxPtEff;
nSigmaITS = gSigmaITS;
nSigmaTPC = gSigmaTPC;
nSigmaTPClow = gSigmaTPClow;
nSigmaTOF = gSigmaTOF;
}
// ----------------------------------------------
// -- PID Strategy
// ----------------------------------------------
if (modePID == -1) { // default
pidStrategy = 7; // 7: ITS + TPC + TOF (using minPtForTOF)
if (modeCuts == 1)
pidStrategy = 5; // 5: TPC + TOF (using minPtForTOF)
}
else
pidStrategy = modePID;
// ----------------------------------------------
// -- Read Environment Variables
// ----------------------------------------------
ifstream in;
in.open("setRunENV.txt");
TString current;
while(in.good()) {
in >> current;
TObjArray *arr = current.Tokenize('=');
if (!arr)
continue;
TObjString* oKey = dynamic_cast<TObjString*>(arr->At(0));
TObjString* oValue = dynamic_cast<TObjString*>(arr->At(1));
if (!oKey)
continue;
TString key(oKey->GetString());
TString value(oValue->GetString());
if (!key.CompareTo("NETPARTICLE_PID_STRATEGY")) {
pidStrategy = value.Atoi();
printf(">>>> USE NETPARTICLE_PID_STRATEGY %d\n", pidStrategy);
}
if (!key.CompareTo("NETPARTICLE_NSIGMAMAX_ITS")) {
nSigmaITS = value.Atof();
printf(">>>> USE NETPARTICLE_NSIGMAMAX_ITS %.2f\n", nSigmaITS);
}
if (!key.CompareTo("NETPARTICLE_NSIGMAMAX_TPC")) {
nSigmaTPC = value.Atof();
printf(">>>> USE NETPARTICLE_NSIGMAMAX_TPC %.2f\n", nSigmaTPC);
}
if (!key.CompareTo("NETPARTICLE_NSIGMAMAX_TOF")) {
nSigmaTOF = value.Atof();
printf(">>>> USE NETPARTICLE_NSIGMAMAX_TOF %.2f\n", nSigmaTOF);
}
arr->Clear();
delete arr;
}
in.close();
// ----------------------------------------------
// -- Configure cuts
// ----------------------------------------------
// -- Set cut flags
task->SetESDTrackCutMode(modeCuts); // => 0 = normal | 1 = LF
// -- Set analysis ranges
task->SetEtaMax(etaMax); // eta cut
task->SetEtaMaxEff(etaMaxEff); // eta cut for efficiency
task->SetPtRange(minPt, maxPt); // pt cut range for the analysis
task->SetPtRangeEff(minPtEff, maxPtEff); // pt cut range for the correction / efficiency / contamination creation
// ----------------------------------------------
// -- Configure cuts - helper class
// ----------------------------------------------
// -- Set standard event cuts
helper->SetVertexZMax(10.);
helper->SetCentralityBinMax(7);
// -- Set track event cuts
helper->SetRapidityMax(0.5);
// helper->SetRapidityMax(0.2);
helper->SetMinTrackLengthMC(70.);
helper->SetNSigmaMaxCdd(0.); // 3. || ->> Turn off sigmaDCA cuts for now
helper->SetNSigmaMaxCzz(0.); // 3. || ->> Turn off sigmaDCA cuts for now
helper->SetPhiRange(0., 3.88); // Only used if requested in task - default is TwoPi
// -- Set pid cuts
helper->SetPIDStrategy(pidStrategy);
helper->SetNSigmaMaxITS(nSigmaITS);
helper->SetNSigmaMaxTPC(nSigmaTPC);
helper->SetNSigmaMaxTPClow(nSigmaTPClow);
helper->SetNSigmaMaxTOF(nSigmaTOF);
helper->SetMinPtForTOFRequired(minPtForTOF);
helper->SetMaxPtForTPClow(maxPtForTPClow);
// -- Set N sub samples
helper->SetNSubSamples(20);
// ----------------------------------------------
// -- Add task to the ANALYSIS manager
// ----------------------------------------------
mgr->AddTask(task);
// ----------------------------------------------
// -- data containers - input
// ----------------------------------------------
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
// ----------------------------------------------
// -- data containers - output
// ----------------------------------------------
TString outputFileName = Form("%s:%s", AliAnalysisManager::GetCommonFileName(), name);
TString outputQAFileName = Form("%s:%s", AliAnalysisManager::GetCommonFileName(), name);
AliAnalysisDataContainer *coutput = mgr->CreateContainer(name, TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
AliAnalysisDataContainer *coutputEff = mgr->CreateContainer(Form("%s_eff", name), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
AliAnalysisDataContainer *coutputCont = mgr->CreateContainer(Form("%s_cont", name), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
AliAnalysisDataContainer *coutputDca = mgr->CreateContainer(Form("%s_dca", name), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
AliAnalysisDataContainer *coutputQA = mgr->CreateContainer(Form("%sQA", name), TList::Class(), AliAnalysisManager::kOutputContainer, outputQAFileName);
mgr->ConnectInput (task, 0, cinput );
mgr->ConnectOutput (task, 1, coutput);
mgr->ConnectOutput (task, 2, coutputEff);
mgr->ConnectOutput (task, 3, coutputCont);
mgr->ConnectOutput (task, 4, coutputDca);
mgr->ConnectOutput (task, 5, coutputQA);
return task;
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3314
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3314 to 3315<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3315
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3252
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3252 to 3253<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3253
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/optimize_dataset_op.h"
// On mobile we do not provide optimize dataset op because not all of its
// dependencies are available there. The op is replaced with a no-op.
#if !defined(IS_MOBILE_PLATFORM)
#include <map>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset_utils.h"
#include "tensorflow/core/kernels/data/rewrite_utils.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
namespace tensorflow {
namespace data {
/* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType;
/* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsEnabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDisabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDefault;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationConfigs;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2;
constexpr char kOptimizerName[] = "tf_data_meta_optimizer";
constexpr char kOptimizers[] = "optimizers";
constexpr char kOptimizerConfigs[] = "optimizer_configs";
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {
auto& op_name = ctx->def().op();
if (op_name == kOptimizeDatasetV1) {
op_version_ = 1;
} else if (op_name == kOptimizeDatasetV2) {
op_version_ = 2;
}
OP_REQUIRES_OK(ctx,
ctx->GetAttr(kOptimizationConfigs, &optimization_configs_));
}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
std::vector<tstring> optimizations;
if (op_version_ == 1) {
OP_REQUIRES_OK(
ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations));
} else if (op_version_ == 2) {
std::vector<tstring> optimizations_enabled, optimizations_disabled,
optimizations_default;
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled,
&optimizations_enabled));
OP_REQUIRES_OK(ctx,
ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled,
&optimizations_disabled));
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault,
&optimizations_default));
string job_name = port::JobName();
// The map that stores the live experiment names and for how much percentage
// of the Borg jobs, the experiments will be randomly turned on.
// clang-format off
absl::flat_hash_map<string, uint64> live_experiments = {
{"enable_gradient_descent", 0},
{"map_parallelization", 20}
};
// clang-format on
auto hash_func = [](const string& str) { return Hash64(str); };
optimizations = SelectOptimizations(
job_name, live_experiments, optimizations_enabled,
optimizations_disabled, optimizations_default, hash_func);
// Log and record the live experiments that will be applied.
if (!job_name.empty() && !live_experiments.empty()) {
VLOG(1) << "The input pipeline is subject to tf.data experiment. "
"Please see `go/tf-data-experiments` for more details.";
for (auto& pair : live_experiments) {
string experiment = pair.first;
if (std::find(optimizations.begin(), optimizations.end(), experiment) !=
optimizations.end()) {
VLOG(1) << "The live experiment \"" << experiment << "\" is applied.";
metrics::RecordTFDataExperiment(experiment);
}
}
}
}
// The vector stores the graduated experiment names which will be turned on
// for all input pipelines.
// clang-format off
std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"};
// clang-format on
// Add the graduated experiments to the optimization list and log them.
for (auto& experiment : graduated_experiments) {
if (std::find(optimizations.begin(), optimizations.end(), experiment) ==
optimizations.end()) {
optimizations.push_back(experiment);
}
VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied.";
}
// If there are no optimizations to be applied, directly return the input.
if (optimizations.empty()) {
*output = input;
input->Ref();
return;
}
auto config_factory = [this, &optimizations]() {
return CreateConfig(optimizations, optimization_configs_);
};
Status s = RewriteDataset(ctx, input, std::move(config_factory),
/*record_fingerprint=*/true, output);
if (errors::IsDeadlineExceeded(s)) {
// Ignore DeadlineExceeded as it implies that the attempted rewrite took too
// long which should not prevent further computation.
LOG(WARNING) << s.ToString();
*output = input;
input->Ref();
return;
}
OP_REQUIRES_OK(ctx, s);
}
RewriterConfig OptimizeDatasetOp::CreateConfig(
std::vector<tstring> optimizations,
std::vector<string> optimizations_configs) {
RewriterConfig rewriter_config;
rewriter_config.add_optimizers(kOptimizerName);
rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE);
rewriter_config.set_fail_on_optimizer_errors(true);
auto custom_optimizer = rewriter_config.add_custom_optimizers();
custom_optimizer->set_name(kOptimizerName);
auto* custom_optimizations_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list();
for (const auto& opt : optimizations) {
custom_optimizations_list->add_s(opt.data(), opt.size());
}
auto* config_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs]
.mutable_list();
for (const auto& config : optimizations_configs) {
config_list->add_s(config.data(), config.size());
}
return rewriter_config;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#else // !IS_MOBILE_PLATFORM
namespace tensorflow {
namespace data {
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
input->Ref();
*output = input;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#endif // !IS_MOBILE_PLATFORM
<commit_msg>[tf.data] Rolls out the optimization `map_parallelization` as experiment to 50% of Borg jobs.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/optimize_dataset_op.h"
// On mobile we do not provide optimize dataset op because not all of its
// dependencies are available there. The op is replaced with a no-op.
#if !defined(IS_MOBILE_PLATFORM)
#include <map>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset_utils.h"
#include "tensorflow/core/kernels/data/rewrite_utils.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
namespace tensorflow {
namespace data {
/* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType;
/* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsEnabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDisabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDefault;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationConfigs;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2;
constexpr char kOptimizerName[] = "tf_data_meta_optimizer";
constexpr char kOptimizers[] = "optimizers";
constexpr char kOptimizerConfigs[] = "optimizer_configs";
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {
auto& op_name = ctx->def().op();
if (op_name == kOptimizeDatasetV1) {
op_version_ = 1;
} else if (op_name == kOptimizeDatasetV2) {
op_version_ = 2;
}
OP_REQUIRES_OK(ctx,
ctx->GetAttr(kOptimizationConfigs, &optimization_configs_));
}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
std::vector<tstring> optimizations;
if (op_version_ == 1) {
OP_REQUIRES_OK(
ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations));
} else if (op_version_ == 2) {
std::vector<tstring> optimizations_enabled, optimizations_disabled,
optimizations_default;
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled,
&optimizations_enabled));
OP_REQUIRES_OK(ctx,
ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled,
&optimizations_disabled));
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault,
&optimizations_default));
string job_name = port::JobName();
// The map that stores the live experiment names and for how much percentage
// of the Borg jobs, the experiments will be randomly turned on.
// clang-format off
absl::flat_hash_map<string, uint64> live_experiments = {
{"enable_gradient_descent", 0},
{"map_parallelization", 50}
};
// clang-format on
auto hash_func = [](const string& str) { return Hash64(str); };
optimizations = SelectOptimizations(
job_name, live_experiments, optimizations_enabled,
optimizations_disabled, optimizations_default, hash_func);
// Log and record the live experiments that will be applied.
if (!job_name.empty() && !live_experiments.empty()) {
VLOG(1) << "The input pipeline is subject to tf.data experiment. "
"Please see `go/tf-data-experiments` for more details.";
for (auto& pair : live_experiments) {
string experiment = pair.first;
if (std::find(optimizations.begin(), optimizations.end(), experiment) !=
optimizations.end()) {
VLOG(1) << "The live experiment \"" << experiment << "\" is applied.";
metrics::RecordTFDataExperiment(experiment);
}
}
}
}
// The vector stores the graduated experiment names which will be turned on
// for all input pipelines.
// clang-format off
std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"};
// clang-format on
// Add the graduated experiments to the optimization list and log them.
for (auto& experiment : graduated_experiments) {
if (std::find(optimizations.begin(), optimizations.end(), experiment) ==
optimizations.end()) {
optimizations.push_back(experiment);
}
VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied.";
}
// If there are no optimizations to be applied, directly return the input.
if (optimizations.empty()) {
*output = input;
input->Ref();
return;
}
auto config_factory = [this, &optimizations]() {
return CreateConfig(optimizations, optimization_configs_);
};
Status s = RewriteDataset(ctx, input, std::move(config_factory),
/*record_fingerprint=*/true, output);
if (errors::IsDeadlineExceeded(s)) {
// Ignore DeadlineExceeded as it implies that the attempted rewrite took too
// long which should not prevent further computation.
LOG(WARNING) << s.ToString();
*output = input;
input->Ref();
return;
}
OP_REQUIRES_OK(ctx, s);
}
RewriterConfig OptimizeDatasetOp::CreateConfig(
std::vector<tstring> optimizations,
std::vector<string> optimizations_configs) {
RewriterConfig rewriter_config;
rewriter_config.add_optimizers(kOptimizerName);
rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE);
rewriter_config.set_fail_on_optimizer_errors(true);
auto custom_optimizer = rewriter_config.add_custom_optimizers();
custom_optimizer->set_name(kOptimizerName);
auto* custom_optimizations_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list();
for (const auto& opt : optimizations) {
custom_optimizations_list->add_s(opt.data(), opt.size());
}
auto* config_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs]
.mutable_list();
for (const auto& config : optimizations_configs) {
config_list->add_s(config.data(), config.size());
}
return rewriter_config;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#else // !IS_MOBILE_PLATFORM
namespace tensorflow {
namespace data {
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
input->Ref();
*output = input;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#endif // !IS_MOBILE_PLATFORM
<|endoftext|>
|
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3101
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3101 to 3102<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3102
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>/* NOISE - make noise
p0 = output start time
p1 = duration
p2 = amplitude
p3 = percent of signal to left output channel [optional, default is .5]
p2 (amplitude) and p3 (pan) can receive dynamic updates from a table or
real-time control source.
If an old-style gen table 1 is present, its values will be multiplied
by the p3 amplitude multiplier, even if the latter is dynamic.
The series of random numbers that makes the noise
JGG <johgibso at indiana dot edu>, 24 Dec 2002, rev. 7/9/04
*/
#include <stdio.h>
#include <stdlib.h>
#include <ugens.h>
#include <math.h>
#include <mixerr.h>
#include <Instrument.h>
#include "NOISE.h"
#include <rt.h>
#include <rtdefs.h>
NOISE :: NOISE() : Instrument()
{
branch = 0;
}
NOISE :: ~NOISE()
{
}
int NOISE :: init(double p[], int n_args)
{
nargs = n_args;
float outskip = p[0];
float dur = p[1];
if (rtsetoutput(outskip, dur, this) == -1)
return DONT_SCHEDULE;
amparray = floc(1);
if (amparray) {
int lenamp = fsize(1);
tableset(SR, dur, lenamp, amptabs);
}
skip = (int) (SR / (float) resetval);
return nSamps();
}
int NOISE :: run()
{
for (int i = 0; i < framesToRun(); i++) {
if (--branch <= 0) {
double p[nargs];
update(p, nargs);
amp = p[2];
if (amparray)
amp *= tablei(currentFrame(), amparray, amptabs);
pctleft = nargs > 3 ? p[3] : 0.5; // default is .5
branch = skip;
}
float out[2];
out[0] = rrand() * amp;
if (outputChannels() == 2) {
out[1] = out[0] * (1.0 - pctleft);
out[0] *= pctleft;
}
rtaddout(out);
increment();
}
return framesToRun();
}
Instrument *makeNOISE()
{
NOISE *inst;
inst = new NOISE();
inst->set_bus_config("NOISE");
return inst;
}
void rtprofile()
{
RT_INTRO("NOISE", makeNOISE);
}
<commit_msg>Add to usage comment.<commit_after>/* NOISE - make noise
p0 = output start time
p1 = duration
p2 = amplitude
p3 = percent of signal to left output channel [optional, default is .5]
p2 (amplitude) and p3 (pan) can receive dynamic updates from a table or
real-time control source.
If an old-style gen table 1 is present, its values will be multiplied
by the p3 amplitude multiplier, even if the latter is dynamic.
The series of random numbers that makes the noise is affected by any
calls to srand given in the script. If there are no such calls, the
random seed is 1.
JGG <johgibso at indiana dot edu>, 24 Dec 2002, rev. 7/9/04
*/
#include <stdio.h>
#include <stdlib.h>
#include <ugens.h>
#include <math.h>
#include <mixerr.h>
#include <Instrument.h>
#include "NOISE.h"
#include <rt.h>
#include <rtdefs.h>
NOISE :: NOISE() : Instrument()
{
branch = 0;
}
NOISE :: ~NOISE()
{
}
int NOISE :: init(double p[], int n_args)
{
nargs = n_args;
float outskip = p[0];
float dur = p[1];
if (rtsetoutput(outskip, dur, this) == -1)
return DONT_SCHEDULE;
amparray = floc(1);
if (amparray) {
int lenamp = fsize(1);
tableset(SR, dur, lenamp, amptabs);
}
skip = (int) (SR / (float) resetval);
return nSamps();
}
int NOISE :: run()
{
for (int i = 0; i < framesToRun(); i++) {
if (--branch <= 0) {
double p[nargs];
update(p, nargs);
amp = p[2];
if (amparray)
amp *= tablei(currentFrame(), amparray, amptabs);
pctleft = nargs > 3 ? p[3] : 0.5; // default is .5
branch = skip;
}
float out[2];
out[0] = rrand() * amp;
if (outputChannels() == 2) {
out[1] = out[0] * (1.0 - pctleft);
out[0] *= pctleft;
}
rtaddout(out);
increment();
}
return framesToRun();
}
Instrument *makeNOISE()
{
NOISE *inst;
inst = new NOISE();
inst->set_bus_config("NOISE");
return inst;
}
void rtprofile()
{
RT_INTRO("NOISE", makeNOISE);
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// <atomic>
// #define ATOMIC_CHAR_LOCK_FREE unspecified
// #define ATOMIC_CHAR16_T_LOCK_FREE unspecified
// #define ATOMIC_CHAR32_T_LOCK_FREE unspecified
// #define ATOMIC_WCHAR_T_LOCK_FREE unspecified
// #define ATOMIC_SHORT_LOCK_FREE unspecified
// #define ATOMIC_INT_LOCK_FREE unspecified
// #define ATOMIC_LONG_LOCK_FREE unspecified
// #define ATOMIC_LLONG_LOCK_FREE unspecified
#include <atomic>
#include <cassert>
int main()
{
assert(ATOMIC_CHAR_LOCK_FREE == 0 ||
ATOMIC_CHAR_LOCK_FREE == 1 ||
ATOMIC_CHAR_LOCK_FREE == 2);
assert(ATOMIC_CHAR16_T_LOCK_FREE == 0 ||
ATOMIC_CHAR16_T_LOCK_FREE == 1 ||
ATOMIC_CHAR16_T_LOCK_FREE == 2);
assert(ATOMIC_CHAR32_T_LOCK_FREE == 0 ||
ATOMIC_CHAR32_T_LOCK_FREE == 1 ||
ATOMIC_CHAR32_T_LOCK_FREE == 2);
assert(ATOMIC_WCHAR_T_LOCK_FREE == 0 ||
ATOMIC_WCHAR_T_LOCK_FREE == 1 ||
ATOMIC_WCHAR_T_LOCK_FREE == 2);
assert(ATOMIC_SHORT_LOCK_FREE == 0 ||
ATOMIC_SHORT_LOCK_FREE == 1 ||
ATOMIC_SHORT_LOCK_FREE == 2);
assert(ATOMIC_INT_LOCK_FREE == 0 ||
ATOMIC_INT_LOCK_FREE == 1 ||
ATOMIC_INT_LOCK_FREE == 2);
assert(ATOMIC_LONG_LOCK_FREE == 0 ||
ATOMIC_LONG_LOCK_FREE == 1 ||
ATOMIC_LONG_LOCK_FREE == 2);
assert(ATOMIC_LLONG_LOCK_FREE == 0 ||
ATOMIC_LLONG_LOCK_FREE == 1 ||
ATOMIC_LLONG_LOCK_FREE == 2);
}
<commit_msg>Missing ATOMIC_*_LOCK_FREE tests<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// <atomic>
// #define ATOMIC_BOOL_LOCK_FREE unspecified
// #define ATOMIC_CHAR_LOCK_FREE unspecified
// #define ATOMIC_CHAR16_T_LOCK_FREE unspecified
// #define ATOMIC_CHAR32_T_LOCK_FREE unspecified
// #define ATOMIC_WCHAR_T_LOCK_FREE unspecified
// #define ATOMIC_SHORT_LOCK_FREE unspecified
// #define ATOMIC_INT_LOCK_FREE unspecified
// #define ATOMIC_LONG_LOCK_FREE unspecified
// #define ATOMIC_LLONG_LOCK_FREE unspecified
// #define ATOMIC_POINTER_LOCK_FREE unspecified
#include <atomic>
#include <cassert>
int main()
{
assert(ATOMIC_BOOL_LOCK_FREE == 0 ||
ATOMIC_BOOL_LOCK_FREE == 1 ||
ATOMIC_BOOL_LOCK_FREE == 2);
assert(ATOMIC_CHAR_LOCK_FREE == 0 ||
ATOMIC_CHAR_LOCK_FREE == 1 ||
ATOMIC_CHAR_LOCK_FREE == 2);
assert(ATOMIC_CHAR16_T_LOCK_FREE == 0 ||
ATOMIC_CHAR16_T_LOCK_FREE == 1 ||
ATOMIC_CHAR16_T_LOCK_FREE == 2);
assert(ATOMIC_CHAR32_T_LOCK_FREE == 0 ||
ATOMIC_CHAR32_T_LOCK_FREE == 1 ||
ATOMIC_CHAR32_T_LOCK_FREE == 2);
assert(ATOMIC_WCHAR_T_LOCK_FREE == 0 ||
ATOMIC_WCHAR_T_LOCK_FREE == 1 ||
ATOMIC_WCHAR_T_LOCK_FREE == 2);
assert(ATOMIC_SHORT_LOCK_FREE == 0 ||
ATOMIC_SHORT_LOCK_FREE == 1 ||
ATOMIC_SHORT_LOCK_FREE == 2);
assert(ATOMIC_INT_LOCK_FREE == 0 ||
ATOMIC_INT_LOCK_FREE == 1 ||
ATOMIC_INT_LOCK_FREE == 2);
assert(ATOMIC_LONG_LOCK_FREE == 0 ||
ATOMIC_LONG_LOCK_FREE == 1 ||
ATOMIC_LONG_LOCK_FREE == 2);
assert(ATOMIC_LLONG_LOCK_FREE == 0 ||
ATOMIC_LLONG_LOCK_FREE == 1 ||
ATOMIC_LLONG_LOCK_FREE == 2);
assert(ATOMIC_POINTER_LOCK_FREE == 0 ||
ATOMIC_POINTER_LOCK_FREE == 1 ||
ATOMIC_POINTER_LOCK_FREE == 2);
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include <iostream>
#include <cmath>
#include <iostream>
#include <fstream>
#include <future>
#include <signal.h>
#include <QVBoxLayout>
#include <QMouseEvent>
#include <QPushButton>
#include <QGridLayout>
#include "window.hpp"
#include "settings.hpp"
#include "paint.hpp"
#include "common/util.h"
volatile sig_atomic_t do_exit = 0;
MainWindow::MainWindow(QWidget *parent) : QWidget(parent) {
main_layout = new QStackedLayout;
#ifdef QCOM2
set_core_affinity(7);
#endif
GLWindow * glWindow = new GLWindow(this);
main_layout->addWidget(glWindow);
SettingsWindow * settingsWindow = new SettingsWindow(this);
main_layout->addWidget(settingsWindow);
main_layout->setMargin(0);
setLayout(main_layout);
QObject::connect(glWindow, SIGNAL(openSettings()), this, SLOT(openSettings()));
QObject::connect(settingsWindow, SIGNAL(closeSettings()), this, SLOT(closeSettings()));
setStyleSheet(R"(
* {
color: white;
background-color: #072339;
}
)");
}
void MainWindow::openSettings() {
main_layout->setCurrentIndex(1);
}
void MainWindow::closeSettings() {
main_layout->setCurrentIndex(0);
}
GLWindow::GLWindow(QWidget *parent) : QOpenGLWidget(parent) {
timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
int result = read_param(&brightness_b, "BRIGHTNESS_B", true);
result += read_param(&brightness_m, "BRIGHTNESS_M", true);
if(result != 0) {
brightness_b = 0.0;
brightness_m = 5.0;
}
smooth_brightness = 512;
}
GLWindow::~GLWindow() {
makeCurrent();
doneCurrent();
}
void GLWindow::initializeGL() {
initializeOpenGLFunctions();
std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl;
std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
ui_state = new UIState();
ui_state->sound = &sound;
ui_state->fb_w = vwp_w;
ui_state->fb_h = vwp_h;
ui_init(ui_state);
timer->start(50);
}
void GLWindow::timerUpdate(){
// Update brightness
float clipped_brightness = std::min(1023.0f, (ui_state->light_sensor*brightness_m) + brightness_b);
smooth_brightness = clipped_brightness * 0.01f + smooth_brightness * 0.99f;
int brightness = smooth_brightness;
#ifdef QCOM2
if (ui_state->started != onroad){
onroad = ui_state->started;
timer->setInterval(onroad ? 50 : 1000);
}
if (!ui_state->started){
brightness = 0;
}
#endif
std::async(std::launch::async,
[brightness]{
std::ofstream brightness_control("/sys/class/backlight/panel0-backlight/brightness");
if (brightness_control.is_open()){
brightness_control << brightness << "\n";
brightness_control.close();
}
});
ui_update(ui_state);
update();
}
void GLWindow::resizeGL(int w, int h) {
std::cout << "resize " << w << "x" << h << std::endl;
}
void GLWindow::paintGL() {
ui_draw(ui_state);
}
void GLWindow::mousePressEvent(QMouseEvent *e) {
// Settings button click
if (!ui_state->scene.uilayout_sidebarcollapsed && settings_btn.ptInRect(e->x(), e->y())) {
emit openSettings();
}
// Vision click
if (ui_state->started && (e->x() >= ui_state->scene.viz_rect.x - bdr_s)){
ui_state->scene.uilayout_sidebarcollapsed = !ui_state->scene.uilayout_sidebarcollapsed;
}
}
GLuint visionimg_to_gl(const VisionImg *img, EGLImageKHR *pkhr, void **pph) {
unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img->width, img->height, 0, GL_RGB, GL_UNSIGNED_BYTE, *pph);
glGenerateMipmap(GL_TEXTURE_2D);
*pkhr = (EGLImageKHR)1; // not NULL
return texture;
}
void visionimg_destroy_gl(EGLImageKHR khr, void *ph) {
// empty
}
FramebufferState* framebuffer_init(const char* name, int32_t layer, int alpha,
int *out_w, int *out_h) {
return (FramebufferState*)1; // not null
}
<commit_msg>std::async has nodiscard in 20.04, i believe that function won't return until the async completes<commit_after>#include <cassert>
#include <iostream>
#include <cmath>
#include <iostream>
#include <fstream>
#include <future>
#include <signal.h>
#include <QVBoxLayout>
#include <QMouseEvent>
#include <QPushButton>
#include <QGridLayout>
#include "window.hpp"
#include "settings.hpp"
#include "paint.hpp"
#include "common/util.h"
volatile sig_atomic_t do_exit = 0;
MainWindow::MainWindow(QWidget *parent) : QWidget(parent) {
main_layout = new QStackedLayout;
#ifdef QCOM2
set_core_affinity(7);
#endif
GLWindow * glWindow = new GLWindow(this);
main_layout->addWidget(glWindow);
SettingsWindow * settingsWindow = new SettingsWindow(this);
main_layout->addWidget(settingsWindow);
main_layout->setMargin(0);
setLayout(main_layout);
QObject::connect(glWindow, SIGNAL(openSettings()), this, SLOT(openSettings()));
QObject::connect(settingsWindow, SIGNAL(closeSettings()), this, SLOT(closeSettings()));
setStyleSheet(R"(
* {
color: white;
background-color: #072339;
}
)");
}
void MainWindow::openSettings() {
main_layout->setCurrentIndex(1);
}
void MainWindow::closeSettings() {
main_layout->setCurrentIndex(0);
}
GLWindow::GLWindow(QWidget *parent) : QOpenGLWidget(parent) {
timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
int result = read_param(&brightness_b, "BRIGHTNESS_B", true);
result += read_param(&brightness_m, "BRIGHTNESS_M", true);
if(result != 0) {
brightness_b = 0.0;
brightness_m = 5.0;
}
smooth_brightness = 512;
}
GLWindow::~GLWindow() {
makeCurrent();
doneCurrent();
}
void GLWindow::initializeGL() {
initializeOpenGLFunctions();
std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl;
std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
ui_state = new UIState();
ui_state->sound = &sound;
ui_state->fb_w = vwp_w;
ui_state->fb_h = vwp_h;
ui_init(ui_state);
timer->start(50);
}
void GLWindow::timerUpdate(){
// Update brightness
float clipped_brightness = std::min(1023.0f, (ui_state->light_sensor*brightness_m) + brightness_b);
smooth_brightness = clipped_brightness * 0.01f + smooth_brightness * 0.99f;
int brightness = smooth_brightness;
#ifdef QCOM2
if (ui_state->started != onroad){
onroad = ui_state->started;
timer->setInterval(onroad ? 50 : 1000);
}
if (!ui_state->started){
brightness = 0;
}
#endif
auto f = std::async(std::launch::async,
[brightness]{
std::ofstream brightness_control("/sys/class/backlight/panel0-backlight/brightness");
if (brightness_control.is_open()){
brightness_control << brightness << "\n";
brightness_control.close();
}
});
ui_update(ui_state);
update();
}
void GLWindow::resizeGL(int w, int h) {
std::cout << "resize " << w << "x" << h << std::endl;
}
void GLWindow::paintGL() {
ui_draw(ui_state);
}
void GLWindow::mousePressEvent(QMouseEvent *e) {
// Settings button click
if (!ui_state->scene.uilayout_sidebarcollapsed && settings_btn.ptInRect(e->x(), e->y())) {
emit openSettings();
}
// Vision click
if (ui_state->started && (e->x() >= ui_state->scene.viz_rect.x - bdr_s)){
ui_state->scene.uilayout_sidebarcollapsed = !ui_state->scene.uilayout_sidebarcollapsed;
}
}
GLuint visionimg_to_gl(const VisionImg *img, EGLImageKHR *pkhr, void **pph) {
unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img->width, img->height, 0, GL_RGB, GL_UNSIGNED_BYTE, *pph);
glGenerateMipmap(GL_TEXTURE_2D);
*pkhr = (EGLImageKHR)1; // not NULL
return texture;
}
void visionimg_destroy_gl(EGLImageKHR khr, void *ph) {
// empty
}
FramebufferState* framebuffer_init(const char* name, int32_t layer, int alpha,
int *out_w, int *out_h) {
return (FramebufferState*)1; // not null
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2014-2020 Real Logic Limited.
*
* 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
*
* https://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 <cstdint>
#include <cstdio>
#include <thread>
#include <csignal>
#define __STDC_FORMAT_MACROS
extern "C"
{
#include <hdr_histogram.h>
}
#include "Configuration.h"
#include "concurrent/BusySpinIdleStrategy.h"
#include "util/CommandOptionParser.h"
#include "FragmentAssembler.h"
#include "Aeron.h"
using namespace std::chrono;
using namespace aeron::util;
using namespace aeron;
std::atomic<bool> running(true);
void sigIntHandler(int param)
{
running = false;
}
static const char optHelp = 'h';
static const char optPrefix = 'p';
static const char optPingChannel = 'c';
static const char optPongChannel = 'C';
static const char optPingStreamId = 's';
static const char optPongStreamId = 'S';
static const char optFrags = 'f';
static const char optMessages = 'm';
static const char optLength = 'L';
static const char optWarmupMessages = 'w';
struct Settings
{
std::string dirPrefix = "";
std::string pingChannel = samples::configuration::DEFAULT_PING_CHANNEL;
std::string pongChannel = samples::configuration::DEFAULT_PONG_CHANNEL;
std::int32_t pingStreamId = samples::configuration::DEFAULT_PING_STREAM_ID;
std::int32_t pongStreamId = samples::configuration::DEFAULT_PONG_STREAM_ID;
long numberOfWarmupMessages = samples::configuration::DEFAULT_NUMBER_OF_WARM_UP_MESSAGES;
long numberOfMessages = samples::configuration::DEFAULT_NUMBER_OF_MESSAGES;
int messageLength = samples::configuration::DEFAULT_MESSAGE_LENGTH;
int fragmentCountLimit = samples::configuration::DEFAULT_FRAGMENT_COUNT_LIMIT;
};
Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv)
{
cp.parse(argc, argv);
if (cp.getOption(optHelp).isPresent())
{
cp.displayOptionsHelp(std::cout);
exit(0);
}
Settings s;
s.dirPrefix = cp.getOption(optPrefix).getParam(0, s.dirPrefix);
s.pingChannel = cp.getOption(optPingChannel).getParam(0, s.pingChannel);
s.pongChannel = cp.getOption(optPongChannel).getParam(0, s.pongChannel);
s.pingStreamId = cp.getOption(optPingStreamId).getParamAsInt(0, 1, INT32_MAX, s.pingStreamId);
s.pongStreamId = cp.getOption(optPongStreamId).getParamAsInt(0, 1, INT32_MAX, s.pongStreamId);
s.numberOfMessages = cp.getOption(optMessages).getParamAsLong(0, 0, LONG_MAX, s.numberOfMessages);
s.messageLength = cp.getOption(optLength).getParamAsInt(0, sizeof(std::int64_t), INT32_MAX, s.messageLength);
s.fragmentCountLimit = cp.getOption(optFrags).getParamAsInt(0, 1, INT32_MAX, s.fragmentCountLimit);
s.numberOfWarmupMessages = cp.getOption(optWarmupMessages).getParamAsLong(0, 0, LONG_MAX, s.numberOfWarmupMessages);
return s;
}
void sendPingAndReceivePong(
const fragment_handler_t& fragmentHandler,
Publication& publication,
Subscription& subscription,
const Settings& settings)
{
std::unique_ptr<std::uint8_t[]> buffer(new std::uint8_t[settings.messageLength]);
concurrent::AtomicBuffer srcBuffer(buffer.get(), static_cast<size_t>(settings.messageLength));
BusySpinIdleStrategy idleStrategy;
while (!subscription.isConnected())
{
std::this_thread::yield();
}
std::shared_ptr<Image> imageSharedPtr = subscription.imageByIndex(0);
Image& image = *imageSharedPtr;
for (long i = 0; i < settings.numberOfMessages; i++)
{
std::int64_t position;
do
{
// timestamps in the message are relative to this app, so just send the timepoint directly.
steady_clock::time_point start = steady_clock::now();
srcBuffer.putBytes(0, (std::uint8_t*)&start, sizeof(steady_clock::time_point));
}
while ((position = publication.offer(srcBuffer, 0, settings.messageLength)) < 0L);
do
{
while (image.poll(fragmentHandler, settings.fragmentCountLimit) <= 0)
{
idleStrategy.idle();
}
}
while (image.position() < position);
}
}
std::shared_ptr<Subscription> findSubscription(std::shared_ptr<Aeron> aeron, std::int64_t id)
{
std::shared_ptr<Subscription> subscription = aeron->findSubscription(id);
while (!subscription)
{
std::this_thread::yield();
subscription = aeron->findSubscription(id);
}
return subscription;
}
std::shared_ptr<Publication> findPublication(std::shared_ptr<Aeron> aeron, std::int64_t id)
{
std::shared_ptr<Publication> publication = aeron->findPublication(id);
while (!publication)
{
std::this_thread::yield();
publication = aeron->findPublication(id);
}
return publication;
}
int main(int argc, char **argv)
{
CommandOptionParser cp;
cp.addOption(CommandOption(optHelp, 0, 0, " Displays help information."));
cp.addOption(CommandOption(optPrefix, 1, 1, "dir Prefix directory for aeron driver."));
cp.addOption(CommandOption(optPingChannel, 1, 1, "channel Ping Channel."));
cp.addOption(CommandOption(optPongChannel, 1, 1, "channel Pong Channel."));
cp.addOption(CommandOption(optPingStreamId, 1, 1, "streamId Ping Stream ID."));
cp.addOption(CommandOption(optPongStreamId, 1, 1, "streamId Pong Stream ID."));
cp.addOption(CommandOption(optMessages, 1, 1, "number Number of Messages."));
cp.addOption(CommandOption(optLength, 1, 1, "length Length of Messages."));
cp.addOption(CommandOption(optFrags, 1, 1, "limit Fragment Count Limit."));
cp.addOption(CommandOption(optWarmupMessages, 1, 1, "number Number of Messages for warmup."));
signal(SIGINT, sigIntHandler);
try
{
Settings settings = parseCmdLine(cp, argc, argv);
std::cout << "Pong at " << settings.pongChannel << " on Stream ID " << settings.pongStreamId << std::endl;
std::cout << "Ping at " << settings.pingChannel << " on Stream ID " << settings.pingStreamId << std::endl;
aeron::Context context;
std::atomic<int> countDown(1);
std::int64_t pongSubscriptionId, pingPublicationId, pingSubscriptionId, pongPublicationId;
if (!settings.dirPrefix.empty())
{
context.aeronDir(settings.dirPrefix);
}
context.newSubscriptionHandler(
[](const std::string& channel, std::int32_t streamId, std::int64_t correlationId)
{
std::cout << "Subscription: " << channel << " " << correlationId << ":" << streamId << std::endl;
});
context.newPublicationHandler(
[](const std::string& channel, std::int32_t streamId, std::int32_t sessionId, std::int64_t correlationId)
{
std::cout << "Publication: " << channel << " " << correlationId << ":" << streamId << ":" << sessionId << std::endl;
});
context.availableImageHandler(
[&](Image &image)
{
std::cout << "Available image correlationId=" << image.correlationId() << " sessionId=" << image.sessionId();
std::cout << " at position=" << image.position() << " from " << image.sourceIdentity() << std::endl;
if (image.subscriptionRegistrationId() == pongSubscriptionId)
{
countDown--;
}
});
context.unavailableImageHandler([](Image &image)
{
std::cout << "Unavailable image on correlationId=" << image.correlationId() << " sessionId=" << image.sessionId();
std::cout << " at position=" << image.position() << " from " << image.sourceIdentity() << std::endl;
});
context.preTouchMappedMemory(true);
std::shared_ptr<Aeron> aeron = Aeron::connect(context);
pongSubscriptionId = aeron->addSubscription(settings.pongChannel, settings.pongStreamId);
pingPublicationId = aeron->addPublication(settings.pingChannel, settings.pingStreamId);
pingSubscriptionId = aeron->addSubscription(settings.pingChannel, settings.pingStreamId);
pongPublicationId = aeron->addPublication(settings.pongChannel, settings.pongStreamId);
std::shared_ptr<Subscription> pongSubscription, pingSubscription;
std::shared_ptr<Publication> pingPublication, pongPublication;
pongSubscription = findSubscription(aeron, pongSubscriptionId);
pingSubscription = findSubscription(aeron, pingSubscriptionId);
pingPublication = findPublication(aeron, pingPublicationId);
pongPublication = findPublication(aeron, pongPublicationId);
while (countDown > 0)
{
std::this_thread::yield();
}
Publication& pongPublicationRef = *pongPublication;
Subscription& pingSubscriptionRef = *pingSubscription;
BusySpinIdleStrategy idleStrategy;
BusySpinIdleStrategy pingHandlerIdleStrategy;
FragmentAssembler pingFragmentAssembler(
[&](AtomicBuffer& buffer, index_t offset, index_t length, const Header& header)
{
if (pongPublicationRef.offer(buffer, offset, length) > 0L)
{
return;
}
while (pongPublicationRef.offer(buffer, offset, length) < 0L)
{
pingHandlerIdleStrategy.idle();
}
});
fragment_handler_t ping_handler = pingFragmentAssembler.handler();
std::thread pongThread(
[&]()
{
while (!pingSubscriptionRef.isConnected())
{
std::this_thread::yield();
}
std::shared_ptr<Image> imageSharedPtr = pingSubscriptionRef.imageByIndex(0);
Image& image = *imageSharedPtr;
while (running)
{
idleStrategy.idle(image.poll(ping_handler, settings.fragmentCountLimit));
}
});
if (settings.numberOfWarmupMessages > 0)
{
Settings warmupSettings = settings;
warmupSettings.numberOfMessages = warmupSettings.numberOfWarmupMessages;
const steady_clock::time_point start = steady_clock::now();
std::cout << "Warming up the media driver with "
<< toStringWithCommas(warmupSettings.numberOfWarmupMessages) << " messages of length "
<< toStringWithCommas(warmupSettings.messageLength) << std::endl;
sendPingAndReceivePong(
[](AtomicBuffer&, index_t, index_t, Header&){}, *pingPublication, *pongSubscription, warmupSettings);
std::int64_t nanoDuration = duration<std::int64_t, std::nano>(steady_clock::now() - start).count();
std::cout << "Warmed up the media driver in " << nanoDuration << " [ns]" << std::endl;
}
hdr_histogram* histogram;
hdr_init(1, 10 * 1000 * 1000 * 1000LL, 3, &histogram);
do
{
hdr_reset(histogram);
FragmentAssembler fragmentAssembler(
[&](const AtomicBuffer& buffer, index_t offset, index_t length, const Header& header)
{
steady_clock::time_point end = steady_clock::now();
steady_clock::time_point start;
buffer.getBytes(offset, (std::uint8_t*)&start, sizeof(steady_clock::time_point));
std::int64_t nanoRtt = duration<std::int64_t, std::nano>(end - start).count();
hdr_record_value(histogram, nanoRtt);
});
std::cout << "Pinging "
<< toStringWithCommas(settings.numberOfMessages) << " messages of length "
<< toStringWithCommas(settings.messageLength) << " bytes" << std::endl;
steady_clock::time_point startRun = steady_clock::now();
sendPingAndReceivePong(fragmentAssembler.handler(), *pingPublication, *pongSubscription, settings);
steady_clock::time_point endRun = steady_clock::now();
hdr_percentiles_print(histogram, stdout, 5, 1000.0, CLASSIC);
fflush(stdout);
double runDuration = duration<double>(endRun - startRun).count();
std::cout << "Throughput of "
<< toStringWithCommas(settings.numberOfMessages / runDuration)
<< " RTTs/sec" << std::endl;
}
while (running && continuationBarrier("Execute again?"));
running = false;
pongThread.join();
}
catch (const CommandOptionException& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
cp.displayOptionsHelp(std::cerr);
return -1;
}
catch (const SourcedException& e)
{
std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl;
return -1;
}
catch (const std::exception& e)
{
std::cerr << "FAILED: " << e.what() << " : " << std::endl;
return -1;
}
return 0;
}
<commit_msg>[C++] Naming.<commit_after>/*
* Copyright 2014-2020 Real Logic Limited.
*
* 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
*
* https://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 <cstdint>
#include <cstdio>
#include <thread>
#include <csignal>
#define __STDC_FORMAT_MACROS
extern "C"
{
#include <hdr_histogram.h>
}
#include "Configuration.h"
#include "concurrent/BusySpinIdleStrategy.h"
#include "util/CommandOptionParser.h"
#include "FragmentAssembler.h"
#include "Aeron.h"
using namespace std::chrono;
using namespace aeron::util;
using namespace aeron;
std::atomic<bool> running(true);
void sigIntHandler(int param)
{
running = false;
}
static const char optHelp = 'h';
static const char optPrefix = 'p';
static const char optPingChannel = 'c';
static const char optPongChannel = 'C';
static const char optPingStreamId = 's';
static const char optPongStreamId = 'S';
static const char optFrags = 'f';
static const char optMessages = 'm';
static const char optLength = 'L';
static const char optWarmupMessages = 'w';
struct Settings
{
std::string dirPrefix = "";
std::string pingChannel = samples::configuration::DEFAULT_PING_CHANNEL;
std::string pongChannel = samples::configuration::DEFAULT_PONG_CHANNEL;
std::int32_t pingStreamId = samples::configuration::DEFAULT_PING_STREAM_ID;
std::int32_t pongStreamId = samples::configuration::DEFAULT_PONG_STREAM_ID;
long numberOfWarmupMessages = samples::configuration::DEFAULT_NUMBER_OF_WARM_UP_MESSAGES;
long numberOfMessages = samples::configuration::DEFAULT_NUMBER_OF_MESSAGES;
int messageLength = samples::configuration::DEFAULT_MESSAGE_LENGTH;
int fragmentCountLimit = samples::configuration::DEFAULT_FRAGMENT_COUNT_LIMIT;
};
Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv)
{
cp.parse(argc, argv);
if (cp.getOption(optHelp).isPresent())
{
cp.displayOptionsHelp(std::cout);
exit(0);
}
Settings s;
s.dirPrefix = cp.getOption(optPrefix).getParam(0, s.dirPrefix);
s.pingChannel = cp.getOption(optPingChannel).getParam(0, s.pingChannel);
s.pongChannel = cp.getOption(optPongChannel).getParam(0, s.pongChannel);
s.pingStreamId = cp.getOption(optPingStreamId).getParamAsInt(0, 1, INT32_MAX, s.pingStreamId);
s.pongStreamId = cp.getOption(optPongStreamId).getParamAsInt(0, 1, INT32_MAX, s.pongStreamId);
s.numberOfMessages = cp.getOption(optMessages).getParamAsLong(0, 0, LONG_MAX, s.numberOfMessages);
s.messageLength = cp.getOption(optLength).getParamAsInt(0, sizeof(std::int64_t), INT32_MAX, s.messageLength);
s.fragmentCountLimit = cp.getOption(optFrags).getParamAsInt(0, 1, INT32_MAX, s.fragmentCountLimit);
s.numberOfWarmupMessages = cp.getOption(optWarmupMessages).getParamAsLong(0, 0, LONG_MAX, s.numberOfWarmupMessages);
return s;
}
void sendPingAndReceivePong(
const fragment_handler_t& fragmentHandler,
Publication& publication,
Subscription& subscription,
const Settings& settings)
{
std::unique_ptr<std::uint8_t[]> buffer(new std::uint8_t[settings.messageLength]);
concurrent::AtomicBuffer srcBuffer(buffer.get(), static_cast<size_t>(settings.messageLength));
BusySpinIdleStrategy idleStrategy;
while (!subscription.isConnected())
{
std::this_thread::yield();
}
std::shared_ptr<Image> imageSharedPtr = subscription.imageByIndex(0);
Image& image = *imageSharedPtr;
for (long i = 0; i < settings.numberOfMessages; i++)
{
std::int64_t position;
do
{
// timestamps in the message are relative to this app, so just send the timestamp directly.
steady_clock::time_point start = steady_clock::now();
srcBuffer.putBytes(0, (std::uint8_t*)&start, sizeof(steady_clock::time_point));
}
while ((position = publication.offer(srcBuffer, 0, settings.messageLength)) < 0L);
do
{
while (image.poll(fragmentHandler, settings.fragmentCountLimit) <= 0)
{
idleStrategy.idle();
}
}
while (image.position() < position);
}
}
std::shared_ptr<Subscription> findSubscription(std::shared_ptr<Aeron> aeron, std::int64_t id)
{
std::shared_ptr<Subscription> subscription = aeron->findSubscription(id);
while (!subscription)
{
std::this_thread::yield();
subscription = aeron->findSubscription(id);
}
return subscription;
}
std::shared_ptr<Publication> findPublication(std::shared_ptr<Aeron> aeron, std::int64_t id)
{
std::shared_ptr<Publication> publication = aeron->findPublication(id);
while (!publication)
{
std::this_thread::yield();
publication = aeron->findPublication(id);
}
return publication;
}
int main(int argc, char **argv)
{
CommandOptionParser cp;
cp.addOption(CommandOption(optHelp, 0, 0, " Displays help information."));
cp.addOption(CommandOption(optPrefix, 1, 1, "dir Prefix directory for aeron driver."));
cp.addOption(CommandOption(optPingChannel, 1, 1, "channel Ping Channel."));
cp.addOption(CommandOption(optPongChannel, 1, 1, "channel Pong Channel."));
cp.addOption(CommandOption(optPingStreamId, 1, 1, "streamId Ping Stream ID."));
cp.addOption(CommandOption(optPongStreamId, 1, 1, "streamId Pong Stream ID."));
cp.addOption(CommandOption(optMessages, 1, 1, "number Number of Messages."));
cp.addOption(CommandOption(optLength, 1, 1, "length Length of Messages."));
cp.addOption(CommandOption(optFrags, 1, 1, "limit Fragment Count Limit."));
cp.addOption(CommandOption(optWarmupMessages, 1, 1, "number Number of Messages for warmup."));
signal(SIGINT, sigIntHandler);
try
{
Settings settings = parseCmdLine(cp, argc, argv);
std::cout << "Pong at " << settings.pongChannel << " on Stream ID " << settings.pongStreamId << std::endl;
std::cout << "Ping at " << settings.pingChannel << " on Stream ID " << settings.pingStreamId << std::endl;
aeron::Context context;
std::atomic<int> countDown(1);
std::int64_t pongSubscriptionId, pingPublicationId, pingSubscriptionId, pongPublicationId;
if (!settings.dirPrefix.empty())
{
context.aeronDir(settings.dirPrefix);
}
context.newSubscriptionHandler(
[](const std::string& channel, std::int32_t streamId, std::int64_t correlationId)
{
std::cout << "Subscription: " << channel << " " << correlationId << ":" << streamId << std::endl;
});
context.newPublicationHandler(
[](const std::string& channel, std::int32_t streamId, std::int32_t sessionId, std::int64_t correlationId)
{
std::cout << "Publication: " << channel << " " << correlationId << ":" << streamId << ":" << sessionId << std::endl;
});
context.availableImageHandler(
[&](Image &image)
{
std::cout << "Available image correlationId=" << image.correlationId() << " sessionId=" << image.sessionId();
std::cout << " at position=" << image.position() << " from " << image.sourceIdentity() << std::endl;
if (image.subscriptionRegistrationId() == pongSubscriptionId)
{
countDown--;
}
});
context.unavailableImageHandler([](Image &image)
{
std::cout << "Unavailable image on correlationId=" << image.correlationId() << " sessionId=" << image.sessionId();
std::cout << " at position=" << image.position() << " from " << image.sourceIdentity() << std::endl;
});
context.preTouchMappedMemory(true);
std::shared_ptr<Aeron> aeron = Aeron::connect(context);
pongSubscriptionId = aeron->addSubscription(settings.pongChannel, settings.pongStreamId);
pingPublicationId = aeron->addPublication(settings.pingChannel, settings.pingStreamId);
pingSubscriptionId = aeron->addSubscription(settings.pingChannel, settings.pingStreamId);
pongPublicationId = aeron->addPublication(settings.pongChannel, settings.pongStreamId);
std::shared_ptr<Subscription> pongSubscription, pingSubscription;
std::shared_ptr<Publication> pingPublication, pongPublication;
pongSubscription = findSubscription(aeron, pongSubscriptionId);
pingSubscription = findSubscription(aeron, pingSubscriptionId);
pingPublication = findPublication(aeron, pingPublicationId);
pongPublication = findPublication(aeron, pongPublicationId);
while (countDown > 0)
{
std::this_thread::yield();
}
Publication& pongPublicationRef = *pongPublication;
Subscription& pingSubscriptionRef = *pingSubscription;
BusySpinIdleStrategy idleStrategy;
BusySpinIdleStrategy pingHandlerIdleStrategy;
FragmentAssembler pingFragmentAssembler(
[&](AtomicBuffer& buffer, index_t offset, index_t length, const Header& header)
{
if (pongPublicationRef.offer(buffer, offset, length) > 0L)
{
return;
}
while (pongPublicationRef.offer(buffer, offset, length) < 0L)
{
pingHandlerIdleStrategy.idle();
}
});
fragment_handler_t ping_handler = pingFragmentAssembler.handler();
std::thread pongThread(
[&]()
{
while (!pingSubscriptionRef.isConnected())
{
std::this_thread::yield();
}
std::shared_ptr<Image> imageSharedPtr = pingSubscriptionRef.imageByIndex(0);
Image& image = *imageSharedPtr;
while (running)
{
idleStrategy.idle(image.poll(ping_handler, settings.fragmentCountLimit));
}
});
if (settings.numberOfWarmupMessages > 0)
{
Settings warmupSettings = settings;
warmupSettings.numberOfMessages = warmupSettings.numberOfWarmupMessages;
const steady_clock::time_point start = steady_clock::now();
std::cout << "Warming up the media driver with "
<< toStringWithCommas(warmupSettings.numberOfWarmupMessages) << " messages of length "
<< toStringWithCommas(warmupSettings.messageLength) << std::endl;
sendPingAndReceivePong(
[](AtomicBuffer&, index_t, index_t, Header&){}, *pingPublication, *pongSubscription, warmupSettings);
std::int64_t nanoDuration = duration<std::int64_t, std::nano>(steady_clock::now() - start).count();
std::cout << "Warmed up the media driver in " << nanoDuration << " [ns]" << std::endl;
}
hdr_histogram* histogram;
hdr_init(1, 10 * 1000 * 1000 * 1000LL, 3, &histogram);
do
{
hdr_reset(histogram);
FragmentAssembler fragmentAssembler(
[&](const AtomicBuffer& buffer, index_t offset, index_t length, const Header& header)
{
steady_clock::time_point end = steady_clock::now();
steady_clock::time_point start;
buffer.getBytes(offset, (std::uint8_t*)&start, sizeof(steady_clock::time_point));
std::int64_t nanoRtt = duration<std::int64_t, std::nano>(end - start).count();
hdr_record_value(histogram, nanoRtt);
});
std::cout << "Pinging "
<< toStringWithCommas(settings.numberOfMessages) << " messages of length "
<< toStringWithCommas(settings.messageLength) << " bytes" << std::endl;
steady_clock::time_point startRun = steady_clock::now();
sendPingAndReceivePong(fragmentAssembler.handler(), *pingPublication, *pongSubscription, settings);
steady_clock::time_point endRun = steady_clock::now();
hdr_percentiles_print(histogram, stdout, 5, 1000.0, CLASSIC);
fflush(stdout);
double runDuration = duration<double>(endRun - startRun).count();
std::cout << "Throughput of "
<< toStringWithCommas(settings.numberOfMessages / runDuration)
<< " RTTs/sec" << std::endl;
}
while (running && continuationBarrier("Execute again?"));
running = false;
pongThread.join();
}
catch (const CommandOptionException& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
cp.displayOptionsHelp(std::cerr);
return -1;
}
catch (const SourcedException& e)
{
std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl;
return -1;
}
catch (const std::exception& e)
{
std::cerr << "FAILED: " << e.what() << " : " << std::endl;
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "ServerRpcLayer.hpp"
#include "Debug_p.hpp"
#include "FunctionStreamOperators.hpp"
#include "IgnoredMessageNotification.hpp"
#include "MTProto/MessageHeader.hpp"
#include "MTProto/Stream.hpp"
#include "MTProto/StreamExtraOperators.hpp"
#include "RemoteClientConnectionHelper.hpp"
#include "RpcError.hpp"
#include "RpcOperationFactory.hpp"
#include "RpcProcessingContext.hpp"
#include "SendPackageHelper.hpp"
#include "ServerApi.hpp"
#include "ServerRpcOperation.hpp"
#include "Session.hpp"
#include "TelegramServerUser.hpp"
#include "Utils.hpp"
#ifdef DEVELOPER_BUILD
#include "MTProto/TLTypesDebug.hpp"
#endif
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(c_serverRpcLayerCategory, "telegram.server.rpclayer", QtWarningMsg)
Q_LOGGING_CATEGORY(c_serverRpcDumpPackageCategory, "telegram.server.rpclayer.dump", QtWarningMsg)
template <typename T>
class StackValue
{
public:
StackValue(QStack<T> *stack, const T value) :
m_stack(stack)
{
m_stack->push(value);
}
~StackValue()
{
m_stack->pop();
}
private:
QStack<T> *m_stack;
};
namespace Telegram {
namespace Server {
static const QVector<TLValue> c_unregisteredUserAllowedRpcList =
{
TLValue::HelpGetConfig,
TLValue::AuthSendCode,
TLValue::AuthCheckPassword,
TLValue::AuthSignIn,
TLValue::AuthSignUp,
TLValue::AccountGetPassword,
};
RpcLayer::RpcLayer(QObject *parent) :
BaseRpcLayer(parent)
{
}
LocalServerApi *RpcLayer::api()
{
return m_api;
}
void RpcLayer::setServerApi(LocalServerApi *api)
{
m_api = api;
}
LocalUser *RpcLayer::getUser() const
{
if (!m_session) {
return nullptr;
}
if (!m_session->userId()) {
return nullptr;
}
return m_api->getUser(m_session->userId());
}
quint64 RpcLayer::serverSalt() const
{
return m_session ? m_session->getServerSalt() : 0;
}
quint64 RpcLayer::sessionId() const
{
return m_session ? m_session->id() : 0;
}
Session *RpcLayer::session() const
{
return m_session;
}
void RpcLayer::setSession(Session *session)
{
m_session = session;
}
void RpcLayer::setRpcFactories(const QVector<RpcOperationFactory *> &rpcFactories)
{
m_operationFactories = rpcFactories;
}
bool RpcLayer::processMTProtoMessage(const MTProto::Message &message)
{
TLValue requestValue = message.firstValue();
qCInfo(c_serverRpcLayerCategory) << this << __func__ << requestValue.toString();
switch (requestValue) {
case TLValue::InitConnection:
return processInitConnection(message.skipTLValue());
case TLValue::InvokeWithLayer:
return processInvokeWithLayer(message.skipTLValue());
case TLValue::MsgContainer:
return processMsgContainer(message.skipTLValue());
case TLValue::Ping:
case TLValue::PingDelayDisconnect:
{
MTProto::Stream stream(message.data);
TLFunctions::TLPing ping;
stream >> ping;
MTProto::Stream output(MTProto::Stream::WriteOnly);
output << TLValue::Pong;
output << message.messageId;
output << ping.pingId;
sendPacket(output.getData(), SendMode::ServerReply);
}
return true;
case TLValue::MsgsAck:
return true;
default:
break;
}
MTProto::Stream stream(message.data);
RpcProcessingContext context(stream, message.messageId);
context.inputStream() >> requestValue;
context.setReadCode(requestValue);
if (!getUser() && !c_unregisteredUserAllowedRpcList.contains(requestValue)) {
RpcError error(RpcError::Reason::AuthKeyUnregistered);
return sendRpcError(error, context.requestId());
}
RpcOperation *op = nullptr;
for (RpcOperationFactory *f : m_operationFactories) {
op = f->processRpcCall(this, context);
if (op) {
break;
}
}
if (!op) {
qCWarning(c_serverRpcLayerCategory) << Q_FUNC_INFO << requestValue.toString() << "is not processed!";
return false;
}
if (!op->isFinished()) {
op->startLater();
}
return true;
}
void RpcLayer::sendUpdates(const TLUpdates &updates)
{
qCDebug(c_serverRpcLayerCategory) << CALL_INFO << "Send update to"
<< session()->userId()
<< "session:" << sessionId()
<< "IP:" << session()->ip;
#ifdef DEVELOPER_BUILD
qCDebug(c_serverRpcLayerCategory) << updates;
#endif
MTProto::Stream stream(MTProto::Stream::WriteOnly);
stream << updates;
sendRpcMessage(stream.getData());
}
bool RpcLayer::processInitConnection(const MTProto::Message &message)
{
MTProto::Stream stream(message.data);
quint32 appId;
QString deviceInfo;
QString osInfo;
QString appVersion;
#if TELEGRAMQT_LAYER >= 67
QString systemLanguage;
QString languagePack;
#endif
QString languageCode;
stream >> appId;
stream >> deviceInfo;
stream >> osInfo;
stream >> appVersion;
#if TELEGRAMQT_LAYER >= 67
if (activeLayer() >= 67) {
stream >> systemLanguage;
// If the pack is not registered on server, raise CONNECTION_LANG_PACK_INVALID RPC Error
stream >> languagePack;
}
#endif
stream >> languageCode;
qCDebug(c_serverRpcLayerCategory) << Q_FUNC_INFO << deviceInfo << osInfo << appId << appVersion << languageCode;
if (stream.error()) {
qCWarning(c_serverRpcLayerCategory) << Q_FUNC_INFO << "Invalid read!";
return false;
}
session()->setLayer(activeLayer());
session()->appId = appId;
session()->appVersion = appVersion;
session()->languageCode = languageCode;
session()->deviceInfo = deviceInfo;
session()->osInfo = osInfo;
MTProto::Message innerMessage = message;
innerMessage.data = stream.readAll();
return processMTProtoMessage(innerMessage);
}
bool RpcLayer::processInvokeWithLayer(const MTProto::Message &message)
{
MTProto::Stream stream(message.data);
quint32 layer = 0;
stream >> layer;
qCDebug(c_serverRpcLayerCategory) << Q_FUNC_INFO << "InvokeWithLayer" << layer;
StackValue<quint32> layerValue(&m_invokeWithLayer, layer);
MTProto::Message innerMessage = message;
innerMessage.data = stream.readAll();
return processMTProtoMessage(innerMessage);
}
void RpcLayer::sendIgnoredMessageNotification(quint32 errorCode, const MTProto::FullMessageHeader &header)
{
MTProto::IgnoredMessageNotification messageNotification;
if (errorCode == MTProto::IgnoredMessageNotification::IncorrectServerSalt) {
messageNotification.newServerSalt = m_session->getServerSalt();
}
messageNotification.errorCode = errorCode;
messageNotification.seqNo = header.sequenceNumber;
messageNotification.messageId = header.messageId;
qCDebug(c_serverRpcLayerCategory) << messageNotification.toString();
MTProto::Stream output(RawStream::WriteOnly);
TLBadMsgNotification tlNotification;
messageNotification.toTlNotification(&tlNotification);
output << tlNotification;
sendPacket(output.getData(), SendMode::ServerReply);
}
bool RpcLayer::sendRpcError(const RpcError &error, quint64 messageId)
{
RawStreamEx output(RawStreamEx::WriteOnly);
output << error;
return sendRpcReply(output.getData(), messageId);
}
bool RpcLayer::sendRpcReply(const QByteArray &reply, quint64 messageId)
{
#define DUMP_SERVER_RPC_PACKETS
#ifdef DUMP_SERVER_RPC_PACKETS
qCDebug(c_serverRpcDumpPackageCategory) << "Server: Answer for message" << messageId;
qCDebug(c_serverRpcDumpPackageCategory).noquote() << "Server: RPC Reply bytes:" << reply.size() << reply.toHex();
#endif
RawStream output(RawStream::WriteOnly);
output << TLValue::RpcResult;
output << messageId;
if (reply.size() > 128) { // Telegram spec says it should be 255, but we need to lower the limit to pack DcConfig
const QByteArray innerData = Utils::packGZip(reply);
if (innerData.size() + 8 < reply.size()) {
MTProto::Stream innerStream(RawStream::WriteOnly);
innerStream << TLValue::GzipPacked;
innerStream << innerData;
output.writeBytes(innerStream.getData());
qCDebug(c_serverRpcDumpPackageCategory) << gzipPackMessage() << messageId << TLValue::firstFromArray(reply).toString();
} else {
qCDebug(c_serverRpcDumpPackageCategory) << "Server: It makes no sense to gzip the answer for message" << messageId;
output.writeBytes(reply);
}
} else {
output.writeBytes(reply);
}
qCDebug(c_serverRpcDumpPackageCategory) << Q_FUNC_INFO << TLValue::firstFromArray(reply) << "for message id" << messageId;
return sendPacket(output.getData(), SendMode::ServerReply);
}
bool RpcLayer::sendRpcMessage(const QByteArray &message)
{
return sendPacket(message, SendMode::ServerInitiative);
}
const char *RpcLayer::gzipPackMessage()
{
return "Server: gzip the answer for message";
}
quint32 RpcLayer::activeLayer() const
{
if (m_invokeWithLayer.isEmpty()) {
if (m_session) {
return m_session->layer();
}
qCritical() << Q_FUNC_INFO << "Unable to get active layer (version)";
return 0;
}
return m_invokeWithLayer.top();
}
bool RpcLayer::processMessageHeader(const MTProto::FullMessageHeader &header)
{
if (!header.sessionId) {
qCWarning(c_serverRpcLayerCategory) << this << __func__ << "Unexpected RPC packet without sessionId";
return false;
}
if (!m_session) {
api()->bindClientSession(getHelper()->getRemoteClientConnection(), header.sessionId);
}
if (m_session->id() != header.sessionId) {
qCWarning(c_serverRpcLayerCategory) << this << __func__ << "Unexpected Session Id"
<< showbase << hex
<< m_session->id() << "(in session),"
<< header.sessionId << "(in package header)";
return false;
}
if (!m_session->checkSalt(header.serverSalt)) {
sendIgnoredMessageNotification(MTProto::IgnoredMessageNotification::IncorrectServerSalt, header);
return false;
}
// We can not check message header for too high sequence number because of Container packages
#if 0
if (header.sequenceNumber > (m_session->lastSequenceNumber + 2)) {
sendIgnoredMessageNotification(MTProto::IgnoredMessageNotification::SequenceNumberTooHigh, header);
return false;
}
#endif
if (header.sequenceNumber < m_session->lastSequenceNumber) {
sendIgnoredMessageNotification(MTProto::IgnoredMessageNotification::SequenceNumberTooLow, header);
return false;
}
if (header.messageId & 3ull) {
sendIgnoredMessageNotification(MTProto::IgnoredMessageNotification::IncorrectTwoLowerOrderMessageIdBits, header);
return false;
}
m_session->lastSequenceNumber = header.sequenceNumber;
m_session->lastMessageNumber = header.messageId;
return true;
}
QByteArray RpcLayer::getEncryptionKeyPart() const
{
return m_sendHelper->getServerKeyPart();
}
QByteArray RpcLayer::getVerificationKeyPart() const
{
return m_sendHelper->getClientKeyPart();
}
MTProtoSendHelper *RpcLayer::getHelper() const
{
return static_cast<MTProtoSendHelper *>(m_sendHelper);
}
} // Server namespace
} // Telegram namespace
<commit_msg>Server: Allow more methods for unauthorized users<commit_after>#include "ServerRpcLayer.hpp"
#include "Debug_p.hpp"
#include "FunctionStreamOperators.hpp"
#include "IgnoredMessageNotification.hpp"
#include "MTProto/MessageHeader.hpp"
#include "MTProto/Stream.hpp"
#include "MTProto/StreamExtraOperators.hpp"
#include "RemoteClientConnectionHelper.hpp"
#include "RpcError.hpp"
#include "RpcOperationFactory.hpp"
#include "RpcProcessingContext.hpp"
#include "SendPackageHelper.hpp"
#include "ServerApi.hpp"
#include "ServerRpcOperation.hpp"
#include "Session.hpp"
#include "TelegramServerUser.hpp"
#include "Utils.hpp"
#ifdef DEVELOPER_BUILD
#include "MTProto/TLTypesDebug.hpp"
#endif
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(c_serverRpcLayerCategory, "telegram.server.rpclayer", QtWarningMsg)
Q_LOGGING_CATEGORY(c_serverRpcDumpPackageCategory, "telegram.server.rpclayer.dump", QtWarningMsg)
template <typename T>
class StackValue
{
public:
StackValue(QStack<T> *stack, const T value) :
m_stack(stack)
{
m_stack->push(value);
}
~StackValue()
{
m_stack->pop();
}
private:
QStack<T> *m_stack;
};
namespace Telegram {
namespace Server {
static const QVector<TLValue> c_unregisteredUserAllowedRpcList =
{
TLValue::HelpGetConfig,
TLValue::HelpGetNearestDc,
TLValue::HelpGetAppUpdate,
TLValue::HelpGetCdnConfig,
TLValue::AuthSendCode,
TLValue::AuthCheckPassword,
TLValue::AuthCheckPhone,
TLValue::AuthSignIn,
TLValue::AuthSignUp,
TLValue::AccountGetPassword,
TLValue::LangpackGetLangPack,
TLValue::LangpackGetStrings,
TLValue::LangpackGetDifference,
TLValue::LangpackGetLanguages,
};
RpcLayer::RpcLayer(QObject *parent) :
BaseRpcLayer(parent)
{
}
LocalServerApi *RpcLayer::api()
{
return m_api;
}
void RpcLayer::setServerApi(LocalServerApi *api)
{
m_api = api;
}
LocalUser *RpcLayer::getUser() const
{
if (!m_session) {
return nullptr;
}
if (!m_session->userId()) {
return nullptr;
}
return m_api->getUser(m_session->userId());
}
quint64 RpcLayer::serverSalt() const
{
return m_session ? m_session->getServerSalt() : 0;
}
quint64 RpcLayer::sessionId() const
{
return m_session ? m_session->id() : 0;
}
Session *RpcLayer::session() const
{
return m_session;
}
void RpcLayer::setSession(Session *session)
{
m_session = session;
}
void RpcLayer::setRpcFactories(const QVector<RpcOperationFactory *> &rpcFactories)
{
m_operationFactories = rpcFactories;
}
bool RpcLayer::processMTProtoMessage(const MTProto::Message &message)
{
TLValue requestValue = message.firstValue();
qCInfo(c_serverRpcLayerCategory) << this << __func__ << requestValue.toString();
switch (requestValue) {
case TLValue::InitConnection:
return processInitConnection(message.skipTLValue());
case TLValue::InvokeWithLayer:
return processInvokeWithLayer(message.skipTLValue());
case TLValue::MsgContainer:
return processMsgContainer(message.skipTLValue());
case TLValue::Ping:
case TLValue::PingDelayDisconnect:
{
MTProto::Stream stream(message.data);
TLFunctions::TLPing ping;
stream >> ping;
MTProto::Stream output(MTProto::Stream::WriteOnly);
output << TLValue::Pong;
output << message.messageId;
output << ping.pingId;
sendPacket(output.getData(), SendMode::ServerReply);
}
return true;
case TLValue::MsgsAck:
return true;
default:
break;
}
MTProto::Stream stream(message.data);
RpcProcessingContext context(stream, message.messageId);
context.inputStream() >> requestValue;
context.setReadCode(requestValue);
if (!getUser() && !c_unregisteredUserAllowedRpcList.contains(requestValue)) {
RpcError error(RpcError::Reason::AuthKeyUnregistered);
return sendRpcError(error, context.requestId());
}
RpcOperation *op = nullptr;
for (RpcOperationFactory *f : m_operationFactories) {
op = f->processRpcCall(this, context);
if (op) {
break;
}
}
if (!op) {
qCWarning(c_serverRpcLayerCategory) << Q_FUNC_INFO << requestValue.toString() << "is not processed!";
return false;
}
if (!op->isFinished()) {
op->startLater();
}
return true;
}
void RpcLayer::sendUpdates(const TLUpdates &updates)
{
qCDebug(c_serverRpcLayerCategory) << CALL_INFO << "Send update to"
<< session()->userId()
<< "session:" << sessionId()
<< "IP:" << session()->ip;
#ifdef DEVELOPER_BUILD
qCDebug(c_serverRpcLayerCategory) << updates;
#endif
MTProto::Stream stream(MTProto::Stream::WriteOnly);
stream << updates;
sendRpcMessage(stream.getData());
}
bool RpcLayer::processInitConnection(const MTProto::Message &message)
{
MTProto::Stream stream(message.data);
quint32 appId;
QString deviceInfo;
QString osInfo;
QString appVersion;
#if TELEGRAMQT_LAYER >= 67
QString systemLanguage;
QString languagePack;
#endif
QString languageCode;
stream >> appId;
stream >> deviceInfo;
stream >> osInfo;
stream >> appVersion;
#if TELEGRAMQT_LAYER >= 67
if (activeLayer() >= 67) {
stream >> systemLanguage;
// If the pack is not registered on server, raise CONNECTION_LANG_PACK_INVALID RPC Error
stream >> languagePack;
}
#endif
stream >> languageCode;
qCDebug(c_serverRpcLayerCategory) << Q_FUNC_INFO << deviceInfo << osInfo << appId << appVersion << languageCode;
if (stream.error()) {
qCWarning(c_serverRpcLayerCategory) << Q_FUNC_INFO << "Invalid read!";
return false;
}
session()->setLayer(activeLayer());
session()->appId = appId;
session()->appVersion = appVersion;
session()->languageCode = languageCode;
session()->deviceInfo = deviceInfo;
session()->osInfo = osInfo;
MTProto::Message innerMessage = message;
innerMessage.data = stream.readAll();
return processMTProtoMessage(innerMessage);
}
bool RpcLayer::processInvokeWithLayer(const MTProto::Message &message)
{
MTProto::Stream stream(message.data);
quint32 layer = 0;
stream >> layer;
qCDebug(c_serverRpcLayerCategory) << Q_FUNC_INFO << "InvokeWithLayer" << layer;
StackValue<quint32> layerValue(&m_invokeWithLayer, layer);
MTProto::Message innerMessage = message;
innerMessage.data = stream.readAll();
return processMTProtoMessage(innerMessage);
}
void RpcLayer::sendIgnoredMessageNotification(quint32 errorCode, const MTProto::FullMessageHeader &header)
{
MTProto::IgnoredMessageNotification messageNotification;
if (errorCode == MTProto::IgnoredMessageNotification::IncorrectServerSalt) {
messageNotification.newServerSalt = m_session->getServerSalt();
}
messageNotification.errorCode = errorCode;
messageNotification.seqNo = header.sequenceNumber;
messageNotification.messageId = header.messageId;
qCDebug(c_serverRpcLayerCategory) << messageNotification.toString();
MTProto::Stream output(RawStream::WriteOnly);
TLBadMsgNotification tlNotification;
messageNotification.toTlNotification(&tlNotification);
output << tlNotification;
sendPacket(output.getData(), SendMode::ServerReply);
}
bool RpcLayer::sendRpcError(const RpcError &error, quint64 messageId)
{
RawStreamEx output(RawStreamEx::WriteOnly);
output << error;
return sendRpcReply(output.getData(), messageId);
}
bool RpcLayer::sendRpcReply(const QByteArray &reply, quint64 messageId)
{
#define DUMP_SERVER_RPC_PACKETS
#ifdef DUMP_SERVER_RPC_PACKETS
qCDebug(c_serverRpcDumpPackageCategory) << "Server: Answer for message" << messageId;
qCDebug(c_serverRpcDumpPackageCategory).noquote() << "Server: RPC Reply bytes:" << reply.size() << reply.toHex();
#endif
RawStream output(RawStream::WriteOnly);
output << TLValue::RpcResult;
output << messageId;
if (reply.size() > 128) { // Telegram spec says it should be 255, but we need to lower the limit to pack DcConfig
const QByteArray innerData = Utils::packGZip(reply);
if (innerData.size() + 8 < reply.size()) {
MTProto::Stream innerStream(RawStream::WriteOnly);
innerStream << TLValue::GzipPacked;
innerStream << innerData;
output.writeBytes(innerStream.getData());
qCDebug(c_serverRpcDumpPackageCategory) << gzipPackMessage() << messageId << TLValue::firstFromArray(reply).toString();
} else {
qCDebug(c_serverRpcDumpPackageCategory) << "Server: It makes no sense to gzip the answer for message" << messageId;
output.writeBytes(reply);
}
} else {
output.writeBytes(reply);
}
qCDebug(c_serverRpcDumpPackageCategory) << Q_FUNC_INFO << TLValue::firstFromArray(reply) << "for message id" << messageId;
return sendPacket(output.getData(), SendMode::ServerReply);
}
bool RpcLayer::sendRpcMessage(const QByteArray &message)
{
return sendPacket(message, SendMode::ServerInitiative);
}
const char *RpcLayer::gzipPackMessage()
{
return "Server: gzip the answer for message";
}
quint32 RpcLayer::activeLayer() const
{
if (m_invokeWithLayer.isEmpty()) {
if (m_session) {
return m_session->layer();
}
qCritical() << Q_FUNC_INFO << "Unable to get active layer (version)";
return 0;
}
return m_invokeWithLayer.top();
}
bool RpcLayer::processMessageHeader(const MTProto::FullMessageHeader &header)
{
if (!header.sessionId) {
qCWarning(c_serverRpcLayerCategory) << this << __func__ << "Unexpected RPC packet without sessionId";
return false;
}
if (!m_session) {
api()->bindClientSession(getHelper()->getRemoteClientConnection(), header.sessionId);
}
if (m_session->id() != header.sessionId) {
qCWarning(c_serverRpcLayerCategory) << this << __func__ << "Unexpected Session Id"
<< showbase << hex
<< m_session->id() << "(in session),"
<< header.sessionId << "(in package header)";
return false;
}
if (!m_session->checkSalt(header.serverSalt)) {
sendIgnoredMessageNotification(MTProto::IgnoredMessageNotification::IncorrectServerSalt, header);
return false;
}
// We can not check message header for too high sequence number because of Container packages
#if 0
if (header.sequenceNumber > (m_session->lastSequenceNumber + 2)) {
sendIgnoredMessageNotification(MTProto::IgnoredMessageNotification::SequenceNumberTooHigh, header);
return false;
}
#endif
if (header.sequenceNumber < m_session->lastSequenceNumber) {
sendIgnoredMessageNotification(MTProto::IgnoredMessageNotification::SequenceNumberTooLow, header);
return false;
}
if (header.messageId & 3ull) {
sendIgnoredMessageNotification(MTProto::IgnoredMessageNotification::IncorrectTwoLowerOrderMessageIdBits, header);
return false;
}
m_session->lastSequenceNumber = header.sequenceNumber;
m_session->lastMessageNumber = header.messageId;
return true;
}
QByteArray RpcLayer::getEncryptionKeyPart() const
{
return m_sendHelper->getServerKeyPart();
}
QByteArray RpcLayer::getVerificationKeyPart() const
{
return m_sendHelper->getClientKeyPart();
}
MTProtoSendHelper *RpcLayer::getHelper() const
{
return static_cast<MTProtoSendHelper *>(m_sendHelper);
}
} // Server namespace
} // Telegram namespace
<|endoftext|>
|
<commit_before>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.com */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* 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. */
/* */
/**************************************************************************************/
#ifndef IndexIterator_INCLUDE_ONCE
#define IndexIterator_INCLUDE_ONCE
#include <vl/Object.hpp>
namespace vl
{
//-----------------------------------------------------------------------------
// IndexIteratorAbstract
//-----------------------------------------------------------------------------
class IndexIteratorAbstract: public Object
{
public:
IndexIteratorAbstract(): mIndex(-1) {}
int index() const { return mIndex; }
virtual bool isEnd() const = 0;
virtual bool next() = 0;
protected:
int mIndex;
};
//-----------------------------------------------------------------------------
// IndexIterator
//-----------------------------------------------------------------------------
class IndexIterator: public Object
{
public:
void initialize(IndexIteratorAbstract* iterator) { mIterator = iterator; }
int index() { return mIterator->index(); }
bool isEnd() { return mIterator->isEnd(); }
bool next() { return mIterator->next(); }
protected:
ref<IndexIteratorAbstract> mIterator;
};
//-----------------------------------------------------------------------------
// IndexIteratorDrawArrays
//-----------------------------------------------------------------------------
class IndexIteratorDrawArrays: public IndexIteratorAbstract
{
public:
IndexIteratorDrawArrays()
{
initialize(0,0);
}
void initialize(int start, int count)
{
mStart = start;
mCount = count;
mCurPos = start;
mIndex = start;
}
virtual bool isEnd() const
{
return mCurPos == mStart + mCount;
}
virtual bool next()
{
++mCurPos;
mIndex = mCurPos;
return true;
}
protected:
int mStart;
int mCount;
int mCurPos;
};
//-----------------------------------------------------------------------------
// IndexIteratorElements
//-----------------------------------------------------------------------------
template<class TArray>
class IndexIteratorElements: public IndexIteratorAbstract
{
public:
IndexIteratorElements()
{
initialize( NULL, NULL, NULL, 0, false, 0 );
}
void initialize( TArray* idx_array, const std::vector<GLint>* p_base_vertices, const std::vector<GLsizei>* p_vert_counts,
int base_vert, bool prim_restart_on, unsigned int prim_restart_idx )
{
mArray = idx_array;
mBaseVert = base_vert;
mpBaseVertices = p_base_vertices;
mpVertCounts = p_vert_counts;
mBaseCount = 0;
mBaseIdx = 0;
mPrimRestartEnabled = prim_restart_on;
mPrimRestartIdx = prim_restart_idx;
mCurPos = 0;
if (mArray && mArray->size())
{
mIndex = mArray->at(0) + mBaseVert;
}
if (p_vert_counts)
{
VL_CHECK(p_base_vertices)
VL_CHECK( p_base_vertices->size() == p_vert_counts->size() )
mBaseCount = (*p_vert_counts)[mBaseIdx];
mIndex = (*mpBaseVertices)[mBaseIdx];
}
}
virtual bool isEnd() const
{
return mCurPos == (int)mArray->size();
}
virtual bool next()
{
++mCurPos;
while( mCurPos < (int)mArray->size() && mArray->at(mCurPos) == mPrimRestartIdx && mPrimRestartEnabled )
++mCurPos;
if ( mCurPos < (int)mArray->size() )
{
mIndex = mArray->at(mCurPos) + mBaseVert;
if (mpVertCounts)
{
VL_CHECK(mpBaseVertices)
mBaseCount--;
if (!mBaseCount)
{
mBaseIdx++;
mBaseCount = (*mpVertCounts)[mBaseIdx];
}
mIndex += (*mpBaseVertices)[mBaseIdx];
}
return true;
}
else
{
mIndex = -1;
mCurPos = mArray->size();
return false;
}
}
protected:
ref<TArray> mArray;
int mBaseVert;
int mCurPos;
bool mPrimRestartEnabled;
unsigned int mPrimRestartIdx;
const std::vector<GLint>* mpBaseVertices;
const std::vector<GLsizei>* mpVertCounts;
int mBaseCount;
int mBaseIdx;
};
//-----------------------------------------------------------------------------
}
#endif
<commit_msg>fixed small warning<commit_after>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.com */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* 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. */
/* */
/**************************************************************************************/
#ifndef IndexIterator_INCLUDE_ONCE
#define IndexIterator_INCLUDE_ONCE
#include <vl/Object.hpp>
namespace vl
{
//-----------------------------------------------------------------------------
// IndexIteratorAbstract
//-----------------------------------------------------------------------------
class IndexIteratorAbstract: public Object
{
public:
IndexIteratorAbstract(): mIndex(-1) {}
int index() const { return mIndex; }
virtual bool isEnd() const = 0;
virtual bool next() = 0;
protected:
int mIndex;
};
//-----------------------------------------------------------------------------
// IndexIterator
//-----------------------------------------------------------------------------
class IndexIterator: public Object
{
public:
void initialize(IndexIteratorAbstract* iterator) { mIterator = iterator; }
int index() { return mIterator->index(); }
bool isEnd() { return mIterator->isEnd(); }
bool next() { return mIterator->next(); }
protected:
ref<IndexIteratorAbstract> mIterator;
};
//-----------------------------------------------------------------------------
// IndexIteratorDrawArrays
//-----------------------------------------------------------------------------
class IndexIteratorDrawArrays: public IndexIteratorAbstract
{
public:
IndexIteratorDrawArrays()
{
initialize(0,0);
}
void initialize(int start, int count)
{
mStart = start;
mCount = count;
mCurPos = start;
mIndex = start;
}
virtual bool isEnd() const
{
return mCurPos == mStart + mCount;
}
virtual bool next()
{
++mCurPos;
mIndex = mCurPos;
return true;
}
protected:
int mStart;
int mCount;
int mCurPos;
};
//-----------------------------------------------------------------------------
// IndexIteratorElements
//-----------------------------------------------------------------------------
template<class TArray>
class IndexIteratorElements: public IndexIteratorAbstract
{
public:
IndexIteratorElements()
{
initialize( NULL, NULL, NULL, 0, false, 0 );
}
void initialize( TArray* idx_array, const std::vector<GLint>* p_base_vertices, const std::vector<GLsizei>* p_vert_counts,
int base_vert, bool prim_restart_on, unsigned int prim_restart_idx )
{
mArray = idx_array;
mBaseVert = base_vert;
mpBaseVertices = p_base_vertices;
mpVertCounts = p_vert_counts;
mBaseCount = 0;
mBaseIdx = 0;
mPrimRestartEnabled = prim_restart_on;
mPrimRestartIdx = prim_restart_idx;
mCurPos = 0;
if (mArray && mArray->size())
{
mIndex = mArray->at(0) + mBaseVert;
}
if (p_vert_counts)
{
VL_CHECK(p_base_vertices)
VL_CHECK( p_base_vertices->size() == p_vert_counts->size() )
mBaseCount = (*p_vert_counts)[mBaseIdx];
mIndex = (*mpBaseVertices)[mBaseIdx];
}
}
virtual bool isEnd() const
{
return mCurPos == (int)mArray->size();
}
virtual bool next()
{
++mCurPos;
while( mCurPos < (int)mArray->size() && mArray->at(mCurPos) == mPrimRestartIdx && mPrimRestartEnabled )
++mCurPos;
if ( mCurPos < (int)mArray->size() )
{
mIndex = mArray->at(mCurPos) + mBaseVert;
if (mpVertCounts)
{
VL_CHECK(mpBaseVertices)
mBaseCount--;
if (!mBaseCount)
{
mBaseIdx++;
mBaseCount = (*mpVertCounts)[mBaseIdx];
}
mIndex += (*mpBaseVertices)[mBaseIdx];
}
return true;
}
else
{
mIndex = -1;
mCurPos = (int)mArray->size();
return false;
}
}
protected:
ref<TArray> mArray;
int mBaseVert;
int mCurPos;
bool mPrimRestartEnabled;
unsigned int mPrimRestartIdx;
const std::vector<GLint>* mpBaseVertices;
const std::vector<GLsizei>* mpVertCounts;
int mBaseCount;
int mBaseIdx;
};
//-----------------------------------------------------------------------------
}
#endif
<|endoftext|>
|
<commit_before>#include "Runtime/Particle/CFlameWarp.hpp"
#include <algorithm>
#include "Runtime/CStateManager.hpp"
namespace urde {
void CFlameWarp::ModifyParticles(std::vector<CParticle>& particles) {
if (x9c_stateMgr == nullptr || particles.size() < 9) {
return;
}
std::vector<std::pair<float, u8>> vec;
vec.reserve(particles.size());
x90_minSize = FLT_MAX;
x94_maxSize = FLT_MIN;
float maxTransp = 0.f;
u8 idx = 0;
for (CParticle& particle : particles) {
float transp = 1.f - particle.x34_color.a();
if (transp > maxTransp) {
float distSq = (particle.x4_pos - x74_warpPoint).magSquared();
if (distSq > x8c_maxDistSq && distSq < x98_maxInfluenceDistSq) {
x8c_maxDistSq = distSq;
maxTransp = transp;
x80_floatingPoint = particle.x4_pos;
}
}
if (particle.x2c_lineLengthOrSize < x90_minSize)
x90_minSize = particle.x2c_lineLengthOrSize;
if (particle.x2c_lineLengthOrSize > x94_maxSize)
x94_maxSize = particle.x2c_lineLengthOrSize;
vec.emplace_back(transp, idx);
if (xa0_25_collisionWarp) {
zeus::CVector3f delta = particle.x4_pos - particle.x10_prevPos;
if (delta.magSquared() >= 0.0011920929f) {
zeus::CVector3f deltaNorm = delta.normalized();
zeus::CVector3f behindPos = particle.x10_prevPos - deltaNorm * 5.f;
zeus::CVector3f fullDelta = particle.x4_pos - behindPos;
CRayCastResult result = x9c_stateMgr->RayStaticIntersection(
behindPos, deltaNorm, fullDelta.magnitude(),
CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {EMaterialTypes::ProjectilePassthrough}));
if (result.IsValid()) {
float dist = result.GetPlane().pointToPlaneDist(particle.x4_pos);
if (dist <= 0.f) {
particle.x4_pos -= result.GetPlane().normal() * dist;
if (result.GetPlane().normal().dot(particle.x1c_vel) < 0.f) {
zeus::CVector3f prevStepPos = particle.x4_pos - particle.x1c_vel;
particle.x4_pos +=
(-result.GetPlane().pointToPlaneDist(prevStepPos) / particle.x1c_vel.dot(result.GetPlane().normal()) -
1.f) *
particle.x1c_vel;
particle.x1c_vel -= particle.x1c_vel * 0.001f;
}
}
}
}
}
++idx;
}
std::sort(vec.begin(), vec.end(), [](auto& a, auto& b) { return a.first < b.first; });
const size_t pitch = particles.size() / 9;
for (size_t i = 0; i < x4_collisionPoints.size(); ++i) {
const CParticle& part = particles[vec[i * pitch].second];
x4_collisionPoints[i] = part.x4_pos;
if (i > 0) {
const zeus::CVector3f delta = x4_collisionPoints[i] - x4_collisionPoints[i - 1];
if (delta.magnitude() < 0.0011920929f) {
x4_collisionPoints[i] += delta.normalized() * 0.0011920929f;
}
}
}
x4_collisionPoints[0] = x74_warpPoint;
x80_floatingPoint = x4_collisionPoints[8];
xa0_26_processed = true;
}
void CFlameWarp::ResetPosition(const zeus::CVector3f& pos) {
std::fill(x4_collisionPoints.begin(), x4_collisionPoints.end(), pos);
xa0_26_processed = false;
}
zeus::CAABox CFlameWarp::CalculateBounds() const {
zeus::CAABox ret;
for (const auto& v : x4_collisionPoints)
ret.accumulateBounds(v);
return ret;
}
} // namespace urde
<commit_msg>CFlameWarp: Make use of const where applicable<commit_after>#include "Runtime/Particle/CFlameWarp.hpp"
#include <algorithm>
#include "Runtime/CStateManager.hpp"
namespace urde {
void CFlameWarp::ModifyParticles(std::vector<CParticle>& particles) {
if (x9c_stateMgr == nullptr || particles.size() < 9) {
return;
}
std::vector<std::pair<float, u8>> vec;
vec.reserve(particles.size());
x90_minSize = FLT_MAX;
x94_maxSize = FLT_MIN;
float maxTransp = 0.f;
u8 idx = 0;
for (CParticle& particle : particles) {
const float transp = 1.f - particle.x34_color.a();
if (transp > maxTransp) {
const float distSq = (particle.x4_pos - x74_warpPoint).magSquared();
if (distSq > x8c_maxDistSq && distSq < x98_maxInfluenceDistSq) {
x8c_maxDistSq = distSq;
maxTransp = transp;
x80_floatingPoint = particle.x4_pos;
}
}
if (particle.x2c_lineLengthOrSize < x90_minSize) {
x90_minSize = particle.x2c_lineLengthOrSize;
}
if (particle.x2c_lineLengthOrSize > x94_maxSize) {
x94_maxSize = particle.x2c_lineLengthOrSize;
}
vec.emplace_back(transp, idx);
if (xa0_25_collisionWarp) {
const zeus::CVector3f delta = particle.x4_pos - particle.x10_prevPos;
if (delta.magSquared() >= 0.0011920929f) {
const zeus::CVector3f deltaNorm = delta.normalized();
const zeus::CVector3f behindPos = particle.x10_prevPos - deltaNorm * 5.f;
const zeus::CVector3f fullDelta = particle.x4_pos - behindPos;
const CRayCastResult result = x9c_stateMgr->RayStaticIntersection(
behindPos, deltaNorm, fullDelta.magnitude(),
CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {EMaterialTypes::ProjectilePassthrough}));
if (result.IsValid()) {
const float dist = result.GetPlane().pointToPlaneDist(particle.x4_pos);
if (dist <= 0.f) {
particle.x4_pos -= result.GetPlane().normal() * dist;
if (result.GetPlane().normal().dot(particle.x1c_vel) < 0.f) {
const zeus::CVector3f prevStepPos = particle.x4_pos - particle.x1c_vel;
particle.x4_pos +=
(-result.GetPlane().pointToPlaneDist(prevStepPos) / particle.x1c_vel.dot(result.GetPlane().normal()) -
1.f) *
particle.x1c_vel;
particle.x1c_vel -= particle.x1c_vel * 0.001f;
}
}
}
}
}
++idx;
}
std::sort(vec.begin(), vec.end(), [](auto& a, auto& b) { return a.first < b.first; });
const size_t pitch = particles.size() / 9;
for (size_t i = 0; i < x4_collisionPoints.size(); ++i) {
const CParticle& part = particles[vec[i * pitch].second];
x4_collisionPoints[i] = part.x4_pos;
if (i > 0) {
const zeus::CVector3f delta = x4_collisionPoints[i] - x4_collisionPoints[i - 1];
if (delta.magnitude() < 0.0011920929f) {
x4_collisionPoints[i] += delta.normalized() * 0.0011920929f;
}
}
}
x4_collisionPoints[0] = x74_warpPoint;
x80_floatingPoint = x4_collisionPoints[8];
xa0_26_processed = true;
}
void CFlameWarp::ResetPosition(const zeus::CVector3f& pos) {
std::fill(x4_collisionPoints.begin(), x4_collisionPoints.end(), pos);
xa0_26_processed = false;
}
zeus::CAABox CFlameWarp::CalculateBounds() const {
zeus::CAABox ret;
for (const auto& v : x4_collisionPoints) {
ret.accumulateBounds(v);
}
return ret;
}
} // namespace urde
<|endoftext|>
|
<commit_before>#include "core/textbox.h"
#include <cstdlib>
#include "core/assert.h"
#include "core/stringutils.h"
namespace
{
bool TerminalSupportUtf8()
{
const auto clang = std::getenv("LANG");
if(clang)
{
const auto lang = std::string(clang);
const auto lower = euphoria::core::ToLower(lang);
const auto ends = euphoria::core::EndsWith(lower, "utf-8");
return ends;
}
return false;
}
}
namespace euphoria::core
{
TextBoxStyle TerminalStyle()
{
if(TerminalSupportUtf8())
{
return Utf8Style();
}
else
{
return AsciiStyle();
}
}
TextBoxStyle Utf8Style()
{
TextBoxStyle style;
style.enable_vt100 = true;
return style;
}
TextBoxStyle AsciiStyle()
{
TextBoxStyle style;
style.enable_vt100 = false;
return style;
}
// bitmasks
constexpr unsigned char u=1;
constexpr unsigned char d=2;
constexpr unsigned char l=4;
constexpr unsigned char r=8;
constexpr unsigned char nonline = ~(u+d+l+r);
TextBox::TextBox()
{}
TextBox::TextBox(const std::vector<std::string>& a_data) : data(a_data)
{}
void TextBox::putchar(char c, std::size_t x, std::size_t y)
{
extend(x,y);
data[y][x] = c;
}
void TextBox::extend(std::size_t x, std::size_t y)
{
if(y >= data.size())
{
data.resize(y+1);
}
if(data[y].size() <= x)
{
data[y].resize(x+1, ' ');
}
}
void TextBox::putline(const std::string& s, std::size_t x_start, std::size_t y)
{
auto xx = s.empty() ? 0 : s.size()-1;
extend(x_start+xx, y);
for(std::size_t begin = 0; begin < s.size(); ++begin)
{
const auto x = x_start + begin;
const unsigned char c = s[begin];
ASSERT(x < data[y].size());
if(c==' ' || !c)
{
continue;
}
char &tgt = data[y][x];
if(tgt==' ' || !tgt || (c&nonline))
{
tgt = c;
}
else
{
if(tgt&nonline)
{
tgt=0; tgt|=c;
}
}
}
}
void TextBox::putbox(std::size_t x, std::size_t y, const TextBox& b)
{
for(std::size_t p = 0; p < b.data.size(); ++p)
{
putline(b.data[p], x, y+p);
}
}
TextBox TextBox::PutBoxCopy(std::size_t x, std::size_t y, const TextBox& b) const
{
TextBox self = *this;
self.putbox(x, y, b);
return self;
}
void TextBox::trim()
{
for(auto& s: data)
{
std::size_t end = s.size();
while(end > 0 && (s[end-1]==' ' || s[end-1]=='\0'))
{
--end;
}
s.erase(end);
}
while(!data.empty() && data.back().empty())
{
data.pop_back();
}
}
std::size_t TextBox::height() const
{
return data.size();
}
std::size_t TextBox::width() const
{
std::size_t result = 0;
for(const auto& s: data)
{
result = std::max(result, s.size());
}
return result;
}
std::pair<std::size_t, std::size_t> TextBox::Size() const
{
return {width(), height()};
}
void TextBox::hline(std::size_t x, std::size_t y, std::size_t width, bool bef, bool aft)
{
for(std::size_t p=0; p<width; ++p)
{
modchar(x+p, y, [&](char& c)
{
if(c&nonline)
{
c=0;
}
if(p>0||bef)
{
c |= l;
}
if(aft||(p+1)<width)
{
c |= r;
}
});
}
}
void TextBox::vline(std::size_t x, std::size_t y, std::size_t height, bool bef, bool aft)
{
for(std::size_t p=0; p<height; ++p)
{
modchar(x, y+p, [&](char& c)
{
if(c&nonline)
{
c=0;
}
if(p>0||bef)
{
c |= u;
}
if(aft||(p+1)<height)
{
c |= d;
}
});
}
}
std::size_t TextBox::horiz_append_position(std::size_t y, const TextBox& b) const
{
std::size_t mywidth = width(), theirheight = b.height();
std::size_t reduce = mywidth;
for(std::size_t p=0; p<theirheight; ++p)
{
std::size_t theirpadding = b.FindLeftPadding(p);
std::size_t mypadding = FindRightPadding(y+p);
reduce = std::min(reduce, mypadding + theirpadding);
}
return mywidth - reduce;
}
std::size_t TextBox::vert_append_position(std::size_t x, const TextBox& b) const
{
std::size_t myheight = height(), theirwidth = b.width();
std::size_t reduce = myheight;
for(std::size_t p=0; p<theirwidth; ++p)
{
std::size_t theirpadding = b.FindTopPadding(p);
std::size_t mypadding = FindBottomPadding(x+p);
reduce = std::min(reduce, mypadding + theirpadding);
}
return myheight - reduce;
}
std::vector<std::string> TextBox::to_string(const TextBoxStyle& style) const
{
std::vector<std::string> ret;
bool want_newline = true;
auto last_line = [&ret, &want_newline]() -> std::string& {
if(want_newline) {ret.emplace_back(""); want_newline = false;}
return ret[ret.size()-1];
};
bool drawing = false, quo = false, space = true, unstr = false;
std::string cur_attr;
const std::string_view linedraw = style.enable_vt100 ? "xxxqjkuqmltqvwn" : "|||-'.+-`,+-+++";
auto attr = [&](const char* s)
{
if (style.enable_vt100)
{
if(cur_attr!=s) { last_line() += "\33["; last_line() += s; last_line() += 'm'; cur_attr = s; }
}
};
auto append = [&](bool v, char c)
{
if (style.enable_vt100)
{
const char* a = nullptr;
bool num = false;
if(v&&!drawing) { a = "0;32"; last_line() += "\33)0\16"; drawing = v; }
else if(!v&&drawing) { a = ""; last_line() += "\33)B\17"; drawing = v; }
if(!v && c=='"') { quo = !quo; if(quo) a = "1;34"; }
if(!v && !quo && ((c>='0' && c<='9') || c=='-')) { a = space ? "1;38;5;165" : "0;38;5;246"; num=true; }
if(!v && !quo && ((c>='a' && c<='z') || c=='_')) { a = "1;37"; }
if(!v && !quo && c>='A' && c<='Z') { a = "0;38;5;246"; }
if(!v && !quo && c=='`') { unstr = true; c = ' '; }
if(c == '\n') unstr = false;
if(unstr) a = nullptr;
if(a) attr(a);
if(!num) space = (c==' ');
}
if(c == '\n')
{
want_newline = true;
}
else
{
last_line() += c;
}
};
for(std::size_t h = height(), y = 0; y < h; ++y)
{
const std::string& s = data[y];
for(std::size_t x = 0; x < s.size(); ++x)
{
unsigned char c = s[x];
if(c > 0 && c < 16) append(true, linedraw[c-1]);
else append(false, c);
}
attr("");
append(false, '\n');
}
return ret;
}
std::size_t TextBox::FindLeftPadding(std::size_t y) const
{
std::size_t max = width(), result = 0;
if(y >= data.size())
{
return max;
}
const std::string& line = data[y];
while(result < line.size() && (line[result] == ' ' || line[result] == '\0'))
{
++result;
}
return result;
}
std::size_t TextBox::FindRightPadding(std::size_t y) const
{
std::size_t max = width(), position = max, result = 0;
if(y >= data.size())
{
return max;
}
const std::string& line = data[y];
while(position-- > 0 && (position >= line.size() || line[position]==' ' || line[position]=='\0'))
{
++result;
}
return result;
}
std::size_t TextBox::FindTopPadding(std::size_t x) const
{
std::size_t result = 0, max = data.size();
while(result < max && (x >= data[result].size() || data[result][x] == ' ' || data[result][x] == '\0'))
{
++result;
}
return result;
}
std::size_t TextBox::FindBottomPadding(std::size_t x) const
{
std::size_t result = 0, max = data.size(), position = max;
while(position-- > 0 && (x >= data[position].size() || data[position][x] == ' ' || data[position][x] == '\0'))
{
++result;
}
return result;
}
namespace detail
{
void CreateTreeGraph(TextBox& result, size_t maxwidth, const std::vector<TextBox>& boxes, bool oneliner_test, bool simple_test, bool separate1st_test, std::string atom)
{
constexpr std::size_t margin = 4, firstx = 2;
std::size_t sum_width = 0;
for(const auto& b: boxes) sum_width += b.width()+margin;
bool oneliner = false;
if(oneliner_test && !separate1st_test)
{
std::size_t totalwidth = 0;
for(auto i = boxes.begin(); ; )
{
const auto& cur = *i;
if(++i == boxes.end()) { totalwidth += cur.width(); break; }
totalwidth += cur.width() + margin;
}
oneliner = (atom.size() + margin + totalwidth) < maxwidth;
}
bool simple = oneliner && boxes.size() == 1 && simple_test;
std::size_t y = simple ? 0 : 1;
for(auto i = boxes.begin(); i != boxes.end(); ++i)
{
auto next = std::next(i);
const TextBox& cur = *i;
unsigned width = cur.width();
std::size_t usemargin = (simple || oneliner) ? (margin/2) : margin;
std::size_t x = result.horiz_append_position(y, cur) + usemargin;
if(x==usemargin) x = oneliner ? atom.size()+usemargin : firstx;
if(!oneliner && (x + width > maxwidth || (separate1st_test && i == ++boxes.begin())))
{
// Start a new line if this item won't fit in the end of the current line
x = firstx;
simple = false;
oneliner = false;
}
// At the beginning of line, judge whether to add room for horizontal placement
bool horizontal = x > firstx;
if(!oneliner && !horizontal && next != boxes.end() && !(separate1st_test && i == boxes.begin()))
{
std::size_t nextwidth = next->width();
std::size_t combined_width = cur.horiz_append_position(0, *next) + margin + nextwidth;
if(combined_width <= maxwidth)
{
// Enact horizontal placement by giving 1 row of room for the connector
horizontal = true;
TextBox combined = cur;
combined.putbox(cur.horiz_append_position(0, *next) + margin, 0, *next);
y = std::max(result.vert_append_position(x, combined), std::size_t(1));
if(!oneliner) ++y;
}
}
if(!horizontal)
y = std::max(result.vert_append_position(x, cur), std::size_t(1));
if(horizontal && !simple && !oneliner)
for(;;)
{
// Check if there is room for a horizontal connector. If not, increase y
TextBox conn;
conn.putline(std::string(1+(x-0), '-'), 0, 0);
if(result.horiz_append_position(y-1, conn) > x) ++y; else break;
y = std::max(result.vert_append_position(x, cur), y);
}
if(simple)
{
if(x > atom.size())
result.hline(atom.size(), 0, 1+x-atom.size(), false,false);
}
else if(oneliner)
{
unsigned cx = x, cy = y-1;
if(x > atom.size())
result.hline(atom.size(), 0, 1+x-atom.size(), false,false);
result.vline(cx, cy, 1, false,true);
}
else if(horizontal)
{
unsigned cx = x, cy = y-1;
result.vline(0, 1, 1 + (cy-1), true,false);
result.hline(0, cy, 1 + (cx-0), false,false);
result.vline(cx, cy, 1, false,true);
}
else
{
unsigned cx = x-1, cy = y;
result.vline(0,1, 1 + (cy-1), true,false);
result.hline(0,cy, 1 + (cx-0), false,true);
}
result.putbox(x, y, cur);
}
}
}
}
<commit_msg>formatted textbox to_string<commit_after>#include "core/textbox.h"
#include <cstdlib>
#include "core/assert.h"
#include "core/stringutils.h"
namespace
{
bool TerminalSupportUtf8()
{
const auto clang = std::getenv("LANG");
if(clang)
{
const auto lang = std::string(clang);
const auto lower = euphoria::core::ToLower(lang);
const auto ends = euphoria::core::EndsWith(lower, "utf-8");
return ends;
}
return false;
}
}
namespace euphoria::core
{
TextBoxStyle TerminalStyle()
{
if(TerminalSupportUtf8())
{
return Utf8Style();
}
else
{
return AsciiStyle();
}
}
TextBoxStyle Utf8Style()
{
TextBoxStyle style;
style.enable_vt100 = true;
return style;
}
TextBoxStyle AsciiStyle()
{
TextBoxStyle style;
style.enable_vt100 = false;
return style;
}
// bitmasks
constexpr unsigned char u=1;
constexpr unsigned char d=2;
constexpr unsigned char l=4;
constexpr unsigned char r=8;
constexpr unsigned char nonline = ~(u+d+l+r);
TextBox::TextBox()
{}
TextBox::TextBox(const std::vector<std::string>& a_data) : data(a_data)
{}
void TextBox::putchar(char c, std::size_t x, std::size_t y)
{
extend(x,y);
data[y][x] = c;
}
void TextBox::extend(std::size_t x, std::size_t y)
{
if(y >= data.size())
{
data.resize(y+1);
}
if(data[y].size() <= x)
{
data[y].resize(x+1, ' ');
}
}
void TextBox::putline(const std::string& s, std::size_t x_start, std::size_t y)
{
auto xx = s.empty() ? 0 : s.size()-1;
extend(x_start+xx, y);
for(std::size_t begin = 0; begin < s.size(); ++begin)
{
const auto x = x_start + begin;
const unsigned char c = s[begin];
ASSERT(x < data[y].size());
if(c==' ' || !c)
{
continue;
}
char &tgt = data[y][x];
if(tgt==' ' || !tgt || (c&nonline))
{
tgt = c;
}
else
{
if(tgt&nonline)
{
tgt=0; tgt|=c;
}
}
}
}
void TextBox::putbox(std::size_t x, std::size_t y, const TextBox& b)
{
for(std::size_t p = 0; p < b.data.size(); ++p)
{
putline(b.data[p], x, y+p);
}
}
TextBox TextBox::PutBoxCopy(std::size_t x, std::size_t y, const TextBox& b) const
{
TextBox self = *this;
self.putbox(x, y, b);
return self;
}
void TextBox::trim()
{
for(auto& s: data)
{
std::size_t end = s.size();
while(end > 0 && (s[end-1]==' ' || s[end-1]=='\0'))
{
--end;
}
s.erase(end);
}
while(!data.empty() && data.back().empty())
{
data.pop_back();
}
}
std::size_t TextBox::height() const
{
return data.size();
}
std::size_t TextBox::width() const
{
std::size_t result = 0;
for(const auto& s: data)
{
result = std::max(result, s.size());
}
return result;
}
std::pair<std::size_t, std::size_t> TextBox::Size() const
{
return {width(), height()};
}
void TextBox::hline(std::size_t x, std::size_t y, std::size_t width, bool bef, bool aft)
{
for(std::size_t p=0; p<width; ++p)
{
modchar(x+p, y, [&](char& c)
{
if(c&nonline)
{
c=0;
}
if(p>0||bef)
{
c |= l;
}
if(aft||(p+1)<width)
{
c |= r;
}
});
}
}
void TextBox::vline(std::size_t x, std::size_t y, std::size_t height, bool bef, bool aft)
{
for(std::size_t p=0; p<height; ++p)
{
modchar(x, y+p, [&](char& c)
{
if(c&nonline)
{
c=0;
}
if(p>0||bef)
{
c |= u;
}
if(aft||(p+1)<height)
{
c |= d;
}
});
}
}
std::size_t TextBox::horiz_append_position(std::size_t y, const TextBox& b) const
{
std::size_t mywidth = width(), theirheight = b.height();
std::size_t reduce = mywidth;
for(std::size_t p=0; p<theirheight; ++p)
{
std::size_t theirpadding = b.FindLeftPadding(p);
std::size_t mypadding = FindRightPadding(y+p);
reduce = std::min(reduce, mypadding + theirpadding);
}
return mywidth - reduce;
}
std::size_t TextBox::vert_append_position(std::size_t x, const TextBox& b) const
{
std::size_t myheight = height(), theirwidth = b.width();
std::size_t reduce = myheight;
for(std::size_t p=0; p<theirwidth; ++p)
{
std::size_t theirpadding = b.FindTopPadding(p);
std::size_t mypadding = FindBottomPadding(x+p);
reduce = std::min(reduce, mypadding + theirpadding);
}
return myheight - reduce;
}
std::vector<std::string> TextBox::to_string(const TextBoxStyle& style) const
{
std::vector<std::string> ret;
bool want_newline = true;
auto last_line = [&ret, &want_newline]() -> std::string&
{
if(want_newline)
{
ret.emplace_back("");
want_newline = false;
}
return ret[ret.size()-1];
};
bool drawing = false, quo = false, space = true, unstr = false;
std::string cur_attr;
const std::string_view linedraw = style.enable_vt100 ? "xxxqjkuqmltqvwn" : "|||-'.+-`,+-+++";
auto attr = [&](const char* s)
{
if (style.enable_vt100)
{
// if(cur_attr!=s) { last_line() += "\33["; last_line() += s; last_line() += 'm'; cur_attr = s; }
}
};
auto append = [&](bool v, char c)
{
if (style.enable_vt100)
{
const char* a = nullptr;
bool num = false;
if(v&&!drawing)
{
a = "0;32";
last_line() += "\33)0\16";
drawing = v;
}
else if(!v&&drawing)
{
a = "";
last_line() += "\33)B\17";
drawing = v;
}
if(!v && c=='"')
{
quo = !quo;
if(quo)
{
a = "1;34";
}
}
if(!v && !quo && ((c>='0' && c<='9') || c=='-'))
{
a = space ? "1;38;5;165" : "0;38;5;246";
num=true;
}
if(!v && !quo && ((c>='a' && c<='z') || c=='_'))
{
a = "1;37";
}
if(!v && !quo && c>='A' && c<='Z')
{
a = "0;38;5;246";
}
if(!v && !quo && c=='`')
{
unstr = true;
c = ' ';
}
if(c == '\n')
{
unstr = false;
}
if(unstr)
{
a = nullptr;
}
if(a)
{
attr(a);
}
if(!num)
{
space = (c==' ');
}
}
if(c == '\n')
{
want_newline = true;
}
else
{
last_line() += c;
}
};
for(std::size_t h = height(), y = 0; y < h; ++y)
{
const std::string& s = data[y];
for(std::size_t x = 0; x < s.size(); ++x)
{
unsigned char c = s[x];
if(c > 0 && c < 16)
{
append(true, linedraw[c-1]);
}
else
{
append(false, c);
}
}
attr("");
append(false, '\n');
}
return ret;
}
std::size_t TextBox::FindLeftPadding(std::size_t y) const
{
std::size_t max = width(), result = 0;
if(y >= data.size())
{
return max;
}
const std::string& line = data[y];
while(result < line.size() && (line[result] == ' ' || line[result] == '\0'))
{
++result;
}
return result;
}
std::size_t TextBox::FindRightPadding(std::size_t y) const
{
std::size_t max = width(), position = max, result = 0;
if(y >= data.size())
{
return max;
}
const std::string& line = data[y];
while(position-- > 0 && (position >= line.size() || line[position]==' ' || line[position]=='\0'))
{
++result;
}
return result;
}
std::size_t TextBox::FindTopPadding(std::size_t x) const
{
std::size_t result = 0, max = data.size();
while(result < max && (x >= data[result].size() || data[result][x] == ' ' || data[result][x] == '\0'))
{
++result;
}
return result;
}
std::size_t TextBox::FindBottomPadding(std::size_t x) const
{
std::size_t result = 0, max = data.size(), position = max;
while(position-- > 0 && (x >= data[position].size() || data[position][x] == ' ' || data[position][x] == '\0'))
{
++result;
}
return result;
}
namespace detail
{
void CreateTreeGraph(TextBox& result, size_t maxwidth, const std::vector<TextBox>& boxes, bool oneliner_test, bool simple_test, bool separate1st_test, std::string atom)
{
constexpr std::size_t margin = 4, firstx = 2;
std::size_t sum_width = 0;
for(const auto& b: boxes) sum_width += b.width()+margin;
bool oneliner = false;
if(oneliner_test && !separate1st_test)
{
std::size_t totalwidth = 0;
for(auto i = boxes.begin(); ; )
{
const auto& cur = *i;
if(++i == boxes.end()) { totalwidth += cur.width(); break; }
totalwidth += cur.width() + margin;
}
oneliner = (atom.size() + margin + totalwidth) < maxwidth;
}
bool simple = oneliner && boxes.size() == 1 && simple_test;
std::size_t y = simple ? 0 : 1;
for(auto i = boxes.begin(); i != boxes.end(); ++i)
{
auto next = std::next(i);
const TextBox& cur = *i;
unsigned width = cur.width();
std::size_t usemargin = (simple || oneliner) ? (margin/2) : margin;
std::size_t x = result.horiz_append_position(y, cur) + usemargin;
if(x==usemargin) x = oneliner ? atom.size()+usemargin : firstx;
if(!oneliner && (x + width > maxwidth || (separate1st_test && i == ++boxes.begin())))
{
// Start a new line if this item won't fit in the end of the current line
x = firstx;
simple = false;
oneliner = false;
}
// At the beginning of line, judge whether to add room for horizontal placement
bool horizontal = x > firstx;
if(!oneliner && !horizontal && next != boxes.end() && !(separate1st_test && i == boxes.begin()))
{
std::size_t nextwidth = next->width();
std::size_t combined_width = cur.horiz_append_position(0, *next) + margin + nextwidth;
if(combined_width <= maxwidth)
{
// Enact horizontal placement by giving 1 row of room for the connector
horizontal = true;
TextBox combined = cur;
combined.putbox(cur.horiz_append_position(0, *next) + margin, 0, *next);
y = std::max(result.vert_append_position(x, combined), std::size_t(1));
if(!oneliner) ++y;
}
}
if(!horizontal)
y = std::max(result.vert_append_position(x, cur), std::size_t(1));
if(horizontal && !simple && !oneliner)
for(;;)
{
// Check if there is room for a horizontal connector. If not, increase y
TextBox conn;
conn.putline(std::string(1+(x-0), '-'), 0, 0);
if(result.horiz_append_position(y-1, conn) > x) ++y; else break;
y = std::max(result.vert_append_position(x, cur), y);
}
if(simple)
{
if(x > atom.size())
result.hline(atom.size(), 0, 1+x-atom.size(), false,false);
}
else if(oneliner)
{
unsigned cx = x, cy = y-1;
if(x > atom.size())
result.hline(atom.size(), 0, 1+x-atom.size(), false,false);
result.vline(cx, cy, 1, false,true);
}
else if(horizontal)
{
unsigned cx = x, cy = y-1;
result.vline(0, 1, 1 + (cy-1), true,false);
result.hline(0, cy, 1 + (cx-0), false,false);
result.vline(cx, cy, 1, false,true);
}
else
{
unsigned cx = x-1, cy = y;
result.vline(0,1, 1 + (cy-1), true,false);
result.hline(0,cy, 1 + (cx-0), false,true);
}
result.putbox(x, y, cur);
}
}
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef ELEM_CORE_RANDOM_DECL_HPP
#define ELEM_CORE_RANDOM_DECL_HPP
namespace elem {
const double Pi = 3.141592653589793;
bool BooleanCoinFlip();
Int CoinFlip();
template<typename T>
T UnitCell();
template<typename T=double>
T Uniform( T a=0, T b=UnitCell<T>() );
// The complex extension of the normal distribution can actually be quite
// technical, and so we will use the simplest case, where both the real and
// imaginary components are independently drawn with the same standard
// deviation, but different means.
template<typename T=double>
T Normal( T mean=0, BASE(T) stddev=1 );
// Generate a sample from a uniform PDF over the (closed) unit ball about the
// origin of the ring implied by the type T using the most natural metric.
template<typename T>
T SampleBall( T center=0, BASE(T) radius=1 );
} // namespace elem
#endif // ifndef ELEM_CORE_RANDOM_DECL_HPP
<commit_msg>Adding missing declaration for integer random number generation.<commit_after>/*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef ELEM_CORE_RANDOM_DECL_HPP
#define ELEM_CORE_RANDOM_DECL_HPP
namespace elem {
const double Pi = 3.141592653589793;
bool BooleanCoinFlip();
Int CoinFlip();
template<typename T>
T UnitCell();
template<typename T=double>
T Uniform( T a=0, T b=UnitCell<T>() );
Int Uniform( Int a, Int b );
// The complex extension of the normal distribution can actually be quite
// technical, and so we will use the simplest case, where both the real and
// imaginary components are independently drawn with the same standard
// deviation, but different means.
template<typename T=double>
T Normal( T mean=0, BASE(T) stddev=1 );
// Generate a sample from a uniform PDF over the (closed) unit ball about the
// origin of the ring implied by the type T using the most natural metric.
template<typename T>
T SampleBall( T center=0, BASE(T) radius=1 );
} // namespace elem
#endif // ifndef ELEM_CORE_RANDOM_DECL_HPP
<|endoftext|>
|
<commit_before>/*
* cpp-benches.cpp
*
* Benchmarks written in C++.
*
*/
#include "cpp-benches.hpp"
#include "hedley.h"
#include "opt-control.hpp"
#include "util.hpp"
#include <limits>
#include <cinttypes>
#include <vector>
#include <random>
#include <cstddef>
#include <sys/time.h>
using std::size_t;
using std::uint64_t;
typedef uint64_t (div_func)(uint64_t);
template <div_func F>
HEDLEY_NEVER_INLINE
uint64_t no_inline(uint64_t a) {
return F(a);
}
static inline uint64_t div32_64(uint64_t a) {
return 0x12345678u / a;
}
static inline uint64_t div64_64(uint64_t a) {
return 0x1234567812345678ull / a;
}
static inline uint64_t div128_64(uint64_t a) {
#if !UARCH_BENCH_PORTABLE
uint64_t high = 123, low = 2;
a |= 0xF234567890123456ull;
asm ("div %2" : "+d"(high), "+a"(low) : "r"(a) : );
return low;
#else
return 1;
#endif
}
template <div_func F, bool forcedep>
long div64_templ(uint64_t iters, void *arg) {
uint64_t sum = 0, zero = always_zero();
for (uint64_t k = 1; k <= iters; k++) {
uint64_t d = k;
if (forcedep) {
d += (sum & zero);
}
sum += F(d);
}
return (long)sum;
}
#define MAKE_DIV_BENCHES(suffix) \
long div_lat_inline ## suffix (uint64_t iters, void *arg) { \
return div64_templ<div ## suffix, true>(iters, arg); \
} \
\
long div_tput_inline ## suffix(uint64_t iters, void *arg) { \
return div64_templ<div ## suffix, false>(iters, arg); \
} \
\
long div_lat_noinline ## suffix(uint64_t iters, void *arg) { \
return div64_templ<no_inline<div ## suffix>, true>(iters, arg); \
} \
\
long div_tput_noinline ## suffix(uint64_t iters, void *arg) { \
return div64_templ<no_inline<div ## suffix>, false>(iters, arg); \
} \
DIV_SPEC_X(MAKE_DIV_BENCHES)
struct list_node {
int value;
list_node* next;
};
static_assert(offsetof(list_node, next) == 8, "double_load tests expect next to be a multiple of 8 offset");
struct list_head {
int size;
list_node *first;
};
list_head makeList(int size) {
list_head head = { size, nullptr };
if (size != 0) {
list_node* all_nodes = new list_node[size]();
head.first = new list_node{ 1, nullptr };
list_node* cur = head.first;
while (--size > 0) {
list_node* next = all_nodes++;
cur->next = next;
cur = next;
}
}
return head;
}
constexpr int NODE_COUNT = 5;
std::vector<list_head> makeLists() {
std::mt19937_64 engine;
std::uniform_int_distribution<int> dist(0, NODE_COUNT * 2);
std::vector<list_head> lists;
for (int i = 0; i < LIST_COUNT; i++) {
lists.push_back(makeList(NODE_COUNT));
}
return lists;
}
std::vector<list_head> listOfLists = makeLists();
typedef long (list_sum)(list_head head);
template <list_sum SUM_IMPL>
long linkedlist_sum(uint64_t iters) {
int sum = 0;
while (iters-- > 0) {
for (size_t list_index = 0; list_index < LIST_COUNT; list_index++) {
sum += SUM_IMPL(listOfLists[list_index]);
}
}
return sum;
}
long sum_counter(list_head list) {
int sum = 0;
list_node* cur = list.first;
for (int i = 0; i < list.size; cur = cur->next, i++) {
sum += cur->value;
}
return sum;
}
long sum_sentinel(list_head list) {
int sum = 0;
for (list_node* cur = list.first; cur; cur = cur->next) {
sum += cur->value;
}
return sum;
}
long linkedlist_counter(uint64_t iters, void *arg) {
return linkedlist_sum<sum_counter>(iters);
}
long linkedlist_sentinel(uint64_t iters, void *arg) {
return linkedlist_sum<sum_sentinel>(iters);
}
long sumlist(list_node *first) {
long sum = 0;
list_node *p = first;
do {
sum += p->value;
p = p->next;
} while (p != first);
return sum;
}
long shuffled_list_sum(uint64_t iters, void *arg) {
int sum = 0;
region* r = (region*)arg;
while (iters-- > 0) {
sum += sumlist((list_node*)r->start);
}
return sum;
}
long gettimeofday_bench(uint64_t iters, void *arg) {
struct timeval tv;
for (uint64_t i = 0; i < iters; i++) {
gettimeofday(&tv, nullptr);
}
return (long)tv.tv_usec;
}
static inline void sink_ptr(void *p) {
__asm__ volatile ("" :: "r"(p) : "memory");
}
long strided_stores(uint64_t iters, void *arg) {
mem_args args = *(mem_args *)arg;
for (uint64_t i = 0; i < iters; i += 4) {
uint64_t offset = i * args.stride & args.mask;
args.region[offset + args.stride * 0] = 0;
args.region[offset + args.stride * 1] = 0;
args.region[offset + args.stride * 2] = 0;
args.region[offset + args.stride * 3] = 0;
}
sink_ptr(args.region);
return (long)args.region[0];
}
long portable_add_chain(uint64_t itersu, void *arg) {
using opt_control::modify;
int64_t iters = itersu;
// we use the modify call to force the compiler to emit the separate
// decrements, otherwise it will simply combine consecutive subtractions
do {
modify(iters);
--iters;
modify(iters);
--iters;
// it is key that the last decrement before the check doesn't have a modify call
// after since this lets the compiler use the result of the flags set by the last
// decrement in the check (which will be fused)
} while (iters != 0);
return iters;
}
<commit_msg>unroll add calibration loop by 4<commit_after>/*
* cpp-benches.cpp
*
* Benchmarks written in C++.
*
*/
#include "cpp-benches.hpp"
#include "hedley.h"
#include "opt-control.hpp"
#include "util.hpp"
#include <limits>
#include <cinttypes>
#include <vector>
#include <random>
#include <cstddef>
#include <sys/time.h>
using std::size_t;
using std::uint64_t;
typedef uint64_t (div_func)(uint64_t);
template <div_func F>
HEDLEY_NEVER_INLINE
uint64_t no_inline(uint64_t a) {
return F(a);
}
static inline uint64_t div32_64(uint64_t a) {
return 0x12345678u / a;
}
static inline uint64_t div64_64(uint64_t a) {
return 0x1234567812345678ull / a;
}
static inline uint64_t div128_64(uint64_t a) {
#if !UARCH_BENCH_PORTABLE
uint64_t high = 123, low = 2;
a |= 0xF234567890123456ull;
asm ("div %2" : "+d"(high), "+a"(low) : "r"(a) : );
return low;
#else
return 1;
#endif
}
template <div_func F, bool forcedep>
long div64_templ(uint64_t iters, void *arg) {
uint64_t sum = 0, zero = always_zero();
for (uint64_t k = 1; k <= iters; k++) {
uint64_t d = k;
if (forcedep) {
d += (sum & zero);
}
sum += F(d);
}
return (long)sum;
}
#define MAKE_DIV_BENCHES(suffix) \
long div_lat_inline ## suffix (uint64_t iters, void *arg) { \
return div64_templ<div ## suffix, true>(iters, arg); \
} \
\
long div_tput_inline ## suffix(uint64_t iters, void *arg) { \
return div64_templ<div ## suffix, false>(iters, arg); \
} \
\
long div_lat_noinline ## suffix(uint64_t iters, void *arg) { \
return div64_templ<no_inline<div ## suffix>, true>(iters, arg); \
} \
\
long div_tput_noinline ## suffix(uint64_t iters, void *arg) { \
return div64_templ<no_inline<div ## suffix>, false>(iters, arg); \
} \
DIV_SPEC_X(MAKE_DIV_BENCHES)
struct list_node {
int value;
list_node* next;
};
static_assert(offsetof(list_node, next) == 8, "double_load tests expect next to be a multiple of 8 offset");
struct list_head {
int size;
list_node *first;
};
list_head makeList(int size) {
list_head head = { size, nullptr };
if (size != 0) {
list_node* all_nodes = new list_node[size]();
head.first = new list_node{ 1, nullptr };
list_node* cur = head.first;
while (--size > 0) {
list_node* next = all_nodes++;
cur->next = next;
cur = next;
}
}
return head;
}
constexpr int NODE_COUNT = 5;
std::vector<list_head> makeLists() {
std::mt19937_64 engine;
std::uniform_int_distribution<int> dist(0, NODE_COUNT * 2);
std::vector<list_head> lists;
for (int i = 0; i < LIST_COUNT; i++) {
lists.push_back(makeList(NODE_COUNT));
}
return lists;
}
std::vector<list_head> listOfLists = makeLists();
typedef long (list_sum)(list_head head);
template <list_sum SUM_IMPL>
long linkedlist_sum(uint64_t iters) {
int sum = 0;
while (iters-- > 0) {
for (size_t list_index = 0; list_index < LIST_COUNT; list_index++) {
sum += SUM_IMPL(listOfLists[list_index]);
}
}
return sum;
}
long sum_counter(list_head list) {
int sum = 0;
list_node* cur = list.first;
for (int i = 0; i < list.size; cur = cur->next, i++) {
sum += cur->value;
}
return sum;
}
long sum_sentinel(list_head list) {
int sum = 0;
for (list_node* cur = list.first; cur; cur = cur->next) {
sum += cur->value;
}
return sum;
}
long linkedlist_counter(uint64_t iters, void *arg) {
return linkedlist_sum<sum_counter>(iters);
}
long linkedlist_sentinel(uint64_t iters, void *arg) {
return linkedlist_sum<sum_sentinel>(iters);
}
long sumlist(list_node *first) {
long sum = 0;
list_node *p = first;
do {
sum += p->value;
p = p->next;
} while (p != first);
return sum;
}
long shuffled_list_sum(uint64_t iters, void *arg) {
int sum = 0;
region* r = (region*)arg;
while (iters-- > 0) {
sum += sumlist((list_node*)r->start);
}
return sum;
}
long gettimeofday_bench(uint64_t iters, void *arg) {
struct timeval tv;
for (uint64_t i = 0; i < iters; i++) {
gettimeofday(&tv, nullptr);
}
return (long)tv.tv_usec;
}
static inline void sink_ptr(void *p) {
__asm__ volatile ("" :: "r"(p) : "memory");
}
long strided_stores(uint64_t iters, void *arg) {
mem_args args = *(mem_args *)arg;
for (uint64_t i = 0; i < iters; i += 4) {
uint64_t offset = i * args.stride & args.mask;
args.region[offset + args.stride * 0] = 0;
args.region[offset + args.stride * 1] = 0;
args.region[offset + args.stride * 2] = 0;
args.region[offset + args.stride * 3] = 0;
}
sink_ptr(args.region);
return (long)args.region[0];
}
long portable_add_chain(uint64_t itersu, void *arg) {
using opt_control::modify;
int64_t iters = itersu;
// we use the modify call to force the compiler to emit the separate
// decrements, otherwise it will simply combine consecutive subtractions
do {
modify(iters);
--iters;
modify(iters);
--iters;
modify(iters);
--iters;
modify(iters);
--iters;
// it is key that the last decrement before the check doesn't have a modify call
// after since this lets the compiler use the result of the flags set by the last
// decrement in the check (which will be fused)
} while (iters != 0);
return iters;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <seqan/arg_parse.h>
#include <seqan/seq_io.h>
using namespace seqan;
using namespace std;
const char *PROGRAM_NAME = "biotool";
const char *HEADER = "FILENAME\tNUMSEQ\tTOTAL\tMIN\tAVG\tMAX";
const unsigned DEFAULT_MIN_LEN = 0;
typedef enum {Success=0, Error_command_line=1, Error_open_file=2, Error_parse_file=3} exit_status;
struct BiotoolOptions
{
unsigned minlen;
bool verbose;
bool version;
vector<string> fasta_files;
BiotoolOptions() :
minlen(DEFAULT_MIN_LEN), verbose(false), version(false), fasta_files({})
{}
};
void print_error(const char *message)
{
cerr << PROGRAM_NAME << " ERROR: " << message << endl;
}
BiotoolOptions parse_options(int argc, char const **argv)
{
ArgumentParser parser(PROGRAM_NAME);
addArgument(parser, ArgParseArgument(
ArgParseArgument::STRING, "FASTA_FILE", true));
addOption(parser, ArgParseOption(
"m", "minlen", "Minimum length sequence to include in stats (default " + to_string(DEFAULT_MIN_LEN) + ")",
ArgParseArgument::INTEGER, "INT"));
addOption(parser, ArgParseOption(
"v", "version", "Display program version and exit"));
addOption(parser, ArgParseOption(
"b", "verbose", "Print more stuff about what's happening"));
ArgumentParser::ParseResult res = parse(parser, argc, argv);
//if (res == ArgumentParser::PARSE_ERROR)
if (res != ArgumentParser::PARSE_OK)
{
if (res == ArgumentParser::PARSE_ERROR) {
exit(Error_command_line);
}
else {
exit(Success);
}
}
BiotoolOptions options;
getOptionValue(options.minlen, parser, "minlen");
options.verbose = isSet(parser, "verbose");
options.version = isSet(parser, "version");
options.fasta_files = getArgumentValues(parser, 0);
return options;
}
void process_files(BiotoolOptions options)
{
CharString id;
CharString seq;
cout << HEADER << endl;
for (string filename : options.fasta_files) {
SeqFileIn seqFileIn;
if (!open(seqFileIn, toCString(filename)))
{
print_error("Could not open the file.");
exit(Error_open_file);
}
int max_len = 0;
int min_len = -1;
int this_len;
unsigned total_len = 0;
unsigned num_seqs = 0;
unsigned int average;
while(!atEnd(seqFileIn))
{
try
{
readRecord(id, seq, seqFileIn);
}
catch (Exception const & e)
{
print_error(e.what());
exit(Error_parse_file);
}
this_len = length(seq);
if (this_len > options.minlen)
{
num_seqs++;
total_len += this_len;
max_len = max(max_len, this_len);
if (min_len < 0 || this_len < min_len)
{
min_len = this_len;
}
}
}
if (num_seqs > 0)
{
average = (unsigned int) floor((double) total_len / (double) num_seqs);
cout << filename << '\t' << num_seqs << '\t' << total_len << '\t' \
<< min_len << '\t' << average << '\t' << max_len << endl;
}
else
{
cout << filename << "\t0\t0\t-\t-\t-" << endl;
}
}
}
int main(int argc, char const **argv)
{
BiotoolOptions options = parse_options(argc, argv);
process_files(options);
return 0;
}
<commit_msg>Refactor C++ code to use class for computing FASTA stats<commit_after>#include <iostream>
#include <seqan/arg_parse.h>
#include <seqan/seq_io.h>
using namespace seqan;
using namespace std;
const char *PROGRAM_NAME = "biotool";
const char *HEADER = "FILENAME\tNUMSEQ\tTOTAL\tMIN\tAVG\tMAX";
const unsigned DEFAULT_MIN_LEN = 0;
typedef enum {Success=0, Error_command_line=1, Error_open_file=2, Error_parse_file=3} exit_status;
struct BiotoolOptions
{
unsigned minlen;
bool verbose;
bool version;
vector<string> fasta_files;
BiotoolOptions() :
minlen(DEFAULT_MIN_LEN), verbose(false), version(false), fasta_files({})
{}
};
void print_error(const char *message)
{
cerr << PROGRAM_NAME << " ERROR: " << message << endl;
}
BiotoolOptions parse_options(int argc, char const **argv)
{
ArgumentParser parser(PROGRAM_NAME);
addOption(parser, ArgParseOption(
"m", "minlen", "Minimum length sequence to include in stats (default " + to_string(DEFAULT_MIN_LEN) + ")",
ArgParseArgument::INTEGER, "INT"));
addOption(parser, ArgParseOption(
"v", "version", "Display program version and exit"));
addOption(parser, ArgParseOption(
"b", "verbose", "Print more stuff about what's happening"));
addArgument(parser, ArgParseArgument(
ArgParseArgument::STRING, "FASTA_FILE", true));
ArgumentParser::ParseResult res = parse(parser, argc, argv);
if (res != ArgumentParser::PARSE_OK)
{
if (res == ArgumentParser::PARSE_ERROR) {
exit(Error_command_line);
}
else {
exit(Success);
}
}
BiotoolOptions options;
getOptionValue(options.minlen, parser, "minlen");
options.verbose = isSet(parser, "verbose");
options.version = isSet(parser, "version");
options.fasta_files = getArgumentValues(parser, 0);
return options;
}
class FastaStats {
private:
unsigned num_seqs;
unsigned num_bases;
unsigned min_len;
unsigned max_len;
public:
void from_file(SeqFileIn &seq_file_in, unsigned minlen_threshold);
FastaStats (void);
friend ostream& operator<< (ostream &out, const FastaStats &stats);
string pretty (string filename);
};
FastaStats::FastaStats(void)
{
num_seqs = 0;
num_bases = 0;
}
ostream& operator<< (ostream &out, const FastaStats &stats)
{
out << "FastaStats(" << stats.num_seqs << ", "
<< stats.num_bases << ", "
<< stats.min_len << ","
<< stats.max_len << ")";
return out;
}
string FastaStats::pretty(string filename)
{
ostringstream result;
if(num_seqs > 0)
{
unsigned average = num_bases / num_seqs;
result << filename << "\t"
<< num_seqs << "\t"
<< num_bases << "\t"
<< min_len << "\t"
<< average << "\t"
<< max_len;
}
else
{
result << filename << "\t0\t0\t-\t-\t-";
}
return result.str();
}
void FastaStats::from_file(SeqFileIn &seq_file_in, unsigned minlen_threshold)
{
unsigned this_len;
CharString id;
CharString seq;
while(!atEnd(seq_file_in))
{
try
{
readRecord(id, seq, seq_file_in);
}
catch (Exception const & e)
{
print_error(e.what());
exit(Error_parse_file);
}
this_len = length(seq);
if (this_len > minlen_threshold)
{
if (num_seqs == 0)
{
min_len = max_len = this_len;
}
else
{
min_len = min(min_len, this_len);
max_len = max(max_len, this_len);
}
num_seqs++;
num_bases += this_len;
}
}
}
void process_files(BiotoolOptions options)
{
cout << HEADER << endl;
FastaStats fasta_stats;
if (options.fasta_files.size() == 0)
{
SeqFileIn seq_file(cin);
fasta_stats.from_file(seq_file, options.minlen);
cout << fasta_stats.pretty("stdin") << endl;
}
else
{
for (string filename : options.fasta_files)
{
SeqFileIn seq_file;
if (!open(seq_file, toCString(filename)))
{
print_error("Could not open the file.");
exit(Error_open_file);
}
fasta_stats.from_file(seq_file, options.minlen);
cout << fasta_stats.pretty(filename) << endl;
}
}
}
int main(int argc, char const **argv)
{
BiotoolOptions options = parse_options(argc, argv);
process_files(options);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
* This file is part of sot-core.
* sot-core 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 3 of
* the License, or (at your option) any later version.
* sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __SOT_BINARY_INT_TO_UINT_HH__
#define __SOT_BINARY_INT_TO_UINT_HH__
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* SOT */
#include <dynamic-graph/entity.h>
#include <sot/core/exception-task.hh>
#include <dynamic-graph/all-signals.h>
/* --------------------------------------------------------------------- */
/* --- API ------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#if defined (WIN32)
# if defined (binary_int_to_uint_EXPORTS)
# define SOTBINARYINTTOUINT_EXPORT __declspec(dllexport)
# else
# define SOTBINARYINTTOUINT_EXPORT __declspec(dllimport)
# endif
#else
# define SOTBINARYINTTOUINT_EXPORT
#endif
namespace dynamicgraph { namespace sot {
namespace dg = dynamicgraph;
class BinaryIntToUint
: public dg::Entity
{
public:
static const std::string CLASS_NAME;
virtual const std::string& getClassName( void ) const { return CLASS_NAME; }
/* --- SIGNALS ------------------------------------------------------------ */
public:
dg::SignalPtr< int,int > binaryIntSIN;
dg::SignalTimeDependent< unsigned,int > binaryUintSOUT;
public:
BinaryIntToUint( const std::string& name );
virtual ~BinaryIntToUint() {}
virtual unsigned& computeOutput( unsigned& res,int time );
virtual void display( std::ostream& os ) const;
void commandLine( const std::string& cmdLine,
std::istringstream& cmdArgs,
std::ostream& os );
};
} /* namespace sot */} /* namespace dynamicgraph */
#endif
<commit_msg>Add missing symbol exportation<commit_after>/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
* This file is part of sot-core.
* sot-core 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 3 of
* the License, or (at your option) any later version.
* sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __SOT_BINARY_INT_TO_UINT_HH__
#define __SOT_BINARY_INT_TO_UINT_HH__
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* SOT */
#include <dynamic-graph/entity.h>
#include <sot/core/exception-task.hh>
#include <dynamic-graph/all-signals.h>
/* --------------------------------------------------------------------- */
/* --- API ------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#if defined (WIN32)
# if defined (binary_int_to_uint_EXPORTS)
# define SOTBINARYINTTOUINT_EXPORT __declspec(dllexport)
# else
# define SOTBINARYINTTOUINT_EXPORT __declspec(dllimport)
# endif
#else
# define SOTBINARYINTTOUINT_EXPORT
#endif
namespace dynamicgraph { namespace sot {
namespace dg = dynamicgraph;
class SOTBINARYINTTOUINT_EXPORT BinaryIntToUint
: public dg::Entity
{
public:
static const std::string CLASS_NAME;
virtual const std::string& getClassName( void ) const { return CLASS_NAME; }
/* --- SIGNALS ------------------------------------------------------------ */
public:
dg::SignalPtr< int,int > binaryIntSIN;
dg::SignalTimeDependent< unsigned,int > binaryUintSOUT;
public:
BinaryIntToUint( const std::string& name );
virtual ~BinaryIntToUint() {}
virtual unsigned& computeOutput( unsigned& res,int time );
virtual void display( std::ostream& os ) const;
void commandLine( const std::string& cmdLine,
std::istringstream& cmdArgs,
std::ostream& os );
};
} /* namespace sot */} /* namespace dynamicgraph */
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/cpp/instance.h"
#include "ppapi/c/ppb_instance.h"
#include "ppapi/c/ppp_printing.h"
#include "ppapi/cpp/device_context_2d.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/resource.h"
#include "ppapi/cpp/var.h"
namespace pp {
namespace {
const PPB_Instance* ppb_instance_funcs = NULL;
bool EnsureFuncs() {
if (!ppb_instance_funcs) {
ppb_instance_funcs = reinterpret_cast<PPB_Instance const*>(
Module::Get()->GetBrowserInterface(PPB_INSTANCE_INTERFACE));
if (!ppb_instance_funcs)
return false;
}
return true;
}
} // namespace
Instance::Instance(PP_Instance instance) : pp_instance_(instance) {
}
Instance::~Instance() {
}
bool Instance::Init(uint32_t /*argc*/, const char* /*argn*/[],
const char* /*argv*/[]) {
return true;
}
bool Instance::HandleDocumentLoad(const URLLoader& /*url_loader*/) {
return false;
}
bool Instance::HandleEvent(const PP_Event& /*event*/) {
return false;
}
Var Instance::GetInstanceObject() {
return Var();
}
void Instance::ViewChanged(const PP_Rect& /*position*/,
const PP_Rect& /*clip*/) {
}
int32_t Instance::PrintBegin(const PP_PrintSettings&) {
return 0;
}
Resource Instance::PrintPages(const PP_PrintPageNumberRange* /*page_ranges*/,
uint32_t /*page_range_count*/) {
return Resource();
}
void Instance::PrintEnd() {
}
void Instance::InvalidateWidget(PP_Resource /*widget_id*/,
const PP_Rect& /*dirty*/) {
}
void Instance::ScrollbarValueChanged(PP_Resource /*scrollbar_id*/,
uint32_t /*value*/) {
}
Var Instance::GetWindowObject() {
if (!EnsureFuncs())
return Var();
return Var(Var::PassRef(),
ppb_instance_funcs->GetWindowObject(pp_instance()));
}
Var Instance::GetOwnerElementObject() {
if (!EnsureFuncs())
return Var();
return Var(Var::PassRef(),
ppb_instance_funcs->GetOwnerElementObject(pp_instance()));
}
bool Instance::BindGraphicsDeviceContext(const DeviceContext2D& context) {
if (!EnsureFuncs())
return false;
return ppb_instance_funcs->BindGraphicsDeviceContext(pp_instance(),
context.pp_resource());
}
bool Instance::IsFullFrame() {
if (!EnsureFuncs())
return false;
return ppb_instance_funcs->IsFullFrame(pp_instance());
}
} // namespace pp
<commit_msg>commit file I missed<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/cpp/instance.h"
#include "ppapi/c/ppb_instance.h"
#include "ppapi/c/ppp_printing.h"
#include "ppapi/cpp/device_context_2d.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/resource.h"
#include "ppapi/cpp/var.h"
namespace pp {
namespace {
const PPB_Instance* ppb_instance_funcs = NULL;
bool EnsureFuncs() {
if (!ppb_instance_funcs) {
ppb_instance_funcs = reinterpret_cast<PPB_Instance const*>(
Module::Get()->GetBrowserInterface(PPB_INSTANCE_INTERFACE));
if (!ppb_instance_funcs)
return false;
}
return true;
}
} // namespace
Instance::Instance(PP_Instance instance) : pp_instance_(instance) {
}
Instance::~Instance() {
}
bool Instance::Init(uint32_t /*argc*/, const char* /*argn*/[],
const char* /*argv*/[]) {
return true;
}
bool Instance::HandleDocumentLoad(const URLLoader& /*url_loader*/) {
return false;
}
bool Instance::HandleEvent(const PP_Event& /*event*/) {
return false;
}
Var Instance::GetInstanceObject() {
return Var();
}
void Instance::ViewChanged(const PP_Rect& /*position*/,
const PP_Rect& /*clip*/) {
}
int32_t Instance::PrintBegin(const PP_PrintSettings&) {
return 0;
}
Resource Instance::PrintPages(const PP_PrintPageNumberRange* /*page_ranges*/,
uint32_t /*page_range_count*/) {
return Resource();
}
void Instance::PrintEnd() {
}
Var Instance::GetWindowObject() {
if (!EnsureFuncs())
return Var();
return Var(Var::PassRef(),
ppb_instance_funcs->GetWindowObject(pp_instance()));
}
Var Instance::GetOwnerElementObject() {
if (!EnsureFuncs())
return Var();
return Var(Var::PassRef(),
ppb_instance_funcs->GetOwnerElementObject(pp_instance()));
}
bool Instance::BindGraphicsDeviceContext(const DeviceContext2D& context) {
if (!EnsureFuncs())
return false;
return ppb_instance_funcs->BindGraphicsDeviceContext(pp_instance(),
context.pp_resource());
}
bool Instance::IsFullFrame() {
if (!EnsureFuncs())
return false;
return ppb_instance_funcs->IsFullFrame(pp_instance());
}
} // namespace pp
<|endoftext|>
|
<commit_before>#pragma once
#include <gcl/algorithms/ranges.hpp>
#include <gcl/algorithms/maths.hpp>
#include <functional>
#include <iterator>
#include <algorithm>
#include <concepts>
namespace gcl::algorithms
{
// todo :
// for_each that detected if the projection takes an iterator or value as parameter ?
// Similar to `std::for_each` by defaut
// but add the ability to project iterator (not values)
// for values, simply use common projections
template <class iterator_type, class UnaryFunction, class Projection = std::identity>
// requires
// std::invocable<Projection, iterator_type> and
// std::invocable<UnaryFunction, std::add_rvalue_reference_t<std::invoke_result_t<Projection, iterator_type>>>
constexpr UnaryFunction for_each_it(
iterator_type range_begin, iterator_type range_end, UnaryFunction f, Projection proj = {})
// noexcept(...)
{
static_assert(std::is_invocable_v<Projection, iterator_type>);
using projection_result_t = std::invoke_result_t<Projection, iterator_type>;
static_assert(std::is_invocable_v<UnaryFunction, std::add_rvalue_reference_t<projection_result_t>>);
for (; range_begin != range_end; ++range_begin)
{
auto value = std::invoke(proj, range_begin);
std::invoke(f, std::move(value));
}
return f;
}
template <typename container_type>
constexpr auto adjacent(container_type& container, typename container_type::iterator it) noexcept
{
if (it == std::end(container))
return std::pair{it, it};
return std::pair{
it == std::begin(container) ? std::end(container) : std::prev(it),
it == std::end(container) ? it : std::next(it)};
}
}
#ifdef GCL_ENABLE_COMPILE_TIME_TESTS
#include <vector>
namespace gcl::algorithms::tests
{
constexpr void for_each_(){
constexpr auto values = std::array{'a', 'b', 'c', 'd'};
// same as std::for_each
gcl::algorithms::for_each_it(
std::cbegin(values), std::cend(values), [](const auto& value) { });
// same as std::for_each with projection on it
gcl::algorithms::for_each_it(
std::cbegin(values),
std::cend(values),
[](const auto& projected_element) { const auto& [index, value] = projected_element; },
[range_begin = std::cbegin(values)](const auto& it) {
return std::pair{std::distance(range_begin, it), *it};
});
}
}
#endif<commit_msg>[algorithms] : adjacent_if<commit_after>#pragma once
#include <gcl/algorithms/ranges.hpp>
#include <gcl/algorithms/maths.hpp>
#include <functional>
#include <iterator>
#include <algorithm>
#include <concepts>
namespace gcl::algorithms
{
// todo :
// for_each that detected if the projection takes an iterator or value as parameter ?
// Similar to `std::for_each` by defaut
// but add the ability to project iterator (not values)
// for values, simply use common projections
template <class iterator_type, class UnaryFunction, class Projection = std::identity>
// requires
// std::invocable<Projection, iterator_type> and
// std::invocable<UnaryFunction, std::add_rvalue_reference_t<std::invoke_result_t<Projection, iterator_type>>>
constexpr UnaryFunction for_each_it(
iterator_type range_begin, iterator_type range_end, UnaryFunction f, Projection proj = {})
// noexcept(...)
{
static_assert(std::is_invocable_v<Projection, iterator_type>);
using projection_result_t = std::invoke_result_t<Projection, iterator_type>;
static_assert(std::is_invocable_v<UnaryFunction, std::add_rvalue_reference_t<projection_result_t>>);
for (; range_begin != range_end; ++range_begin)
{
auto value = std::invoke(proj, range_begin);
std::invoke(f, std::move(value));
}
return f;
}
template <typename container_type>
constexpr auto adjacent(container_type& container, typename container_type::iterator it) noexcept
{
if (it == std::end(container))
return std::pair{it, it};
return std::pair{
it == std::begin(container) ? std::end(container) : std::prev(it),
it == std::end(container) ? it : std::next(it)};
}
template <typename container_type, typename Predicate>
constexpr auto adjacent_if(container_type & container, typename container_type::iterator it, Predicate predicate)
noexcept(std::is_nothrow_invocable_v<Predicate, const typename container_type::value_type&>) {
auto [lhs, rhs] = adjacent(container, it);
static_assert(std::is_invocable_v<Predicate, decltype(*lhs)>);
static_assert(std::is_invocable_v<Predicate, decltype(*rhs)>);
return std::pair{
predicate(*lhs) ? lhs : std::end(container),
predicate(*rhs) ? rhs : std::end(container)
};
}
}
#ifdef GCL_ENABLE_COMPILE_TIME_TESTS
#include <vector>
namespace gcl::algorithms::tests
{
constexpr void for_each_(){
constexpr auto values = std::array{'a', 'b', 'c', 'd'};
// same as std::for_each
gcl::algorithms::for_each_it(
std::cbegin(values), std::cend(values), [](const auto& value) { });
// same as std::for_each with projection on it
gcl::algorithms::for_each_it(
std::cbegin(values),
std::cend(values),
[](const auto& projected_element) { const auto& [index, value] = projected_element; },
[range_begin = std::cbegin(values)](const auto& it) {
return std::pair{std::distance(range_begin, it), *it};
});
}
}
#endif<|endoftext|>
|
<commit_before>/**
* @file llfloaterbuycontents.cpp
* @author James Cook
* @brief LLFloaterBuyContents class implementation
*
* $LicenseInfo:firstyear=2004&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
/**
* Shows the contents of an object and their permissions when you
* click "Buy..." on an object with "Sell Contents" checked.
*/
#include "llviewerprecompiledheaders.h"
#include "llfloaterbuycontents.h"
#include "llcachename.h"
#include "llagent.h" // for agent id
#include "llcheckboxctrl.h"
#include "llinventorydefines.h"
#include "llinventoryfunctions.h"
#include "llinventorymodel.h" // for gInventory
#include "llfirstuse.h"
#include "llfloaterreg.h"
#include "llfloaterinventory.h" // for LLInventoryIcon::getIcon
#include "llnotificationsutil.h"
#include "llselectmgr.h"
#include "llscrolllistctrl.h"
#include "llviewerobject.h"
#include "llviewerregion.h"
#include "lluictrlfactory.h"
#include "llviewerwindow.h"
LLFloaterBuyContents::LLFloaterBuyContents(const LLSD& key)
: LLFloater(key)
{
}
BOOL LLFloaterBuyContents::postBuild()
{
getChild<LLUICtrl>("cancel_btn")->setCommitCallback( boost::bind(&LLFloaterBuyContents::onClickCancel, this));
getChild<LLUICtrl>("buy_btn")->setCommitCallback( boost::bind(&LLFloaterBuyContents::onClickBuy, this));
getChildView("item_list")->setEnabled(FALSE);
getChildView("buy_btn")->setEnabled(FALSE);
getChildView("wear_check")->setEnabled(FALSE);
setDefaultBtn("cancel_btn"); // to avoid accidental buy (SL-43130)
// Always center the dialog. User can change the size,
// but purchases are important and should be center screen.
// This also avoids problems where the user resizes the application window
// mid-session and the saved rect is off-center.
center();
return TRUE;
}
LLFloaterBuyContents::~LLFloaterBuyContents()
{
}
// static
void LLFloaterBuyContents::show(const LLSaleInfo& sale_info)
{
LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
if (selection->getRootObjectCount() != 1)
{
LLNotificationsUtil::add("BuyContentsOneOnly");
return;
}
LLFloaterBuyContents* floater = LLFloaterReg::showTypedInstance<LLFloaterBuyContents>("buy_object_contents");
if (!floater)
return;
LLScrollListCtrl* list = floater->getChild<LLScrollListCtrl>("item_list");
if (list)
list->deleteAllItems();
floater->mObjectSelection = LLSelectMgr::getInstance()->getEditSelection();
LLUUID owner_id;
std::string owner_name;
BOOL owners_identical = LLSelectMgr::getInstance()->selectGetOwner(owner_id, owner_name);
if (!owners_identical)
{
LLNotificationsUtil::add("BuyContentsOneOwner");
return;
}
floater->mSaleInfo = sale_info;
// Update the display
LLSelectNode* node = selection->getFirstRootNode();
if (!node) return;
if(node->mPermissions->isGroupOwned())
{
gCacheName->getGroupName(owner_id, owner_name);
}
floater->getChild<LLUICtrl>("contains_text")->setTextArg("[NAME]", node->mName);
floater->getChild<LLUICtrl>("buy_text")->setTextArg("[AMOUNT]", llformat("%d", sale_info.getSalePrice()));
floater->getChild<LLUICtrl>("buy_text")->setTextArg("[NAME]", owner_name);
// Must do this after the floater is created, because
// sometimes the inventory is already there and
// the callback is called immediately.
LLViewerObject* obj = selection->getFirstRootObject();
floater->registerVOInventoryListener(obj,NULL);
floater->requestVOInventory();
}
void LLFloaterBuyContents::inventoryChanged(LLViewerObject* obj,
LLInventoryObject::object_list_t* inv,
S32 serial_num,
void* data)
{
if (!obj)
{
llwarns << "No object in LLFloaterBuyContents::inventoryChanged" << llendl;
return;
}
if (!inv)
{
llwarns << "No inventory in LLFloaterBuyContents::inventoryChanged"
<< llendl;
removeVOInventoryListener();
return;
}
LLCtrlListInterface *item_list = childGetListInterface("item_list");
if (!item_list)
{
removeVOInventoryListener();
return;
}
// default to turning off the buy button.
getChildView("buy_btn")->setEnabled(FALSE);
LLUUID owner_id;
BOOL is_group_owned;
LLAssetType::EType asset_type;
LLInventoryType::EType inv_type;
S32 wearable_count = 0;
LLInventoryObject::object_list_t::const_iterator it = inv->begin();
LLInventoryObject::object_list_t::const_iterator end = inv->end();
for ( ; it != end; ++it )
{
asset_type = (*it)->getType();
// Skip folders, so we know we have inventory items only
if (asset_type == LLAssetType::AT_CATEGORY)
continue;
LLInventoryItem* inv_item = (LLInventoryItem*)((LLInventoryObject*)(*it));
inv_type = inv_item->getInventoryType();
// Count clothing items for later
if (LLInventoryType::IT_WEARABLE == inv_type)
{
wearable_count++;
}
// Skip items the object's owner can't copy (and hence can't sell)
if (!inv_item->getPermissions().getOwnership(owner_id, is_group_owned))
continue;
if (!inv_item->getPermissions().allowCopyBy(owner_id, owner_id))
continue;
// Skip items we can't transfer
if (!inv_item->getPermissions().allowTransferTo(gAgent.getID()))
continue;
// There will be at least one item shown in the display, so go
// ahead and enable the buy button.
getChildView("buy_btn")->setEnabled(TRUE);
// Create the line in the list
LLSD row;
BOOL item_is_multi = FALSE;
if ( inv_item->getFlags() & LLInventoryItemFlags::II_FLAGS_LANDMARK_VISITED )
{
item_is_multi = TRUE;
}
std::string icon_name = LLInventoryIcon::getIconName(inv_item->getType(),
inv_item->getInventoryType(),
inv_item->getFlags(),
item_is_multi);
row["columns"][0]["column"] = "icon";
row["columns"][0]["type"] = "icon";
row["columns"][0]["value"] = icon_name;
// Append the permissions that you will acquire (not the current
// permissions).
U32 next_owner_mask = inv_item->getPermissions().getMaskNextOwner();
std::string text = (*it)->getName();
if (!(next_owner_mask & PERM_COPY))
{
text.append(getString("no_copy_text"));
}
if (!(next_owner_mask & PERM_MODIFY))
{
text.append(getString("no_modify_text"));
}
if (!(next_owner_mask & PERM_TRANSFER))
{
text.append(getString("no_transfer_text"));
}
row["columns"][1]["column"] = "text";
row["columns"][1]["value"] = text;
row["columns"][1]["font"] = "SANSSERIF";
item_list->addElement(row);
}
if (wearable_count > 0)
{
getChildView("wear_check")->setEnabled(TRUE);
getChild<LLUICtrl>("wear_check")->setValue(LLSD(false) );
}
removeVOInventoryListener();
}
void LLFloaterBuyContents::onClickBuy()
{
// Make sure this wasn't selected through other mechanisms
// (ie, being the default button and pressing enter.
if(!getChildView("buy_btn")->getEnabled())
{
// We shouldn't be enabled. Just close.
closeFloater();
return;
}
// We may want to wear this item
if (getChild<LLUICtrl>("wear_check")->getValue())
{
LLInventoryState::sWearNewClothing = TRUE;
}
// Put the items where we put new folders.
LLUUID category_id;
category_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_ROOT_INVENTORY);
// *NOTE: doesn't work for multiple object buy, which UI does not
// currently support sale info is used for verification only, if
// it doesn't match region info then sale is canceled.
LLSelectMgr::getInstance()->sendBuy(gAgent.getID(), category_id, mSaleInfo);
// NOTE: do this here instead of on receipt of object, since contents are transfered
// via a generic BulkUpdateInventory message with no way of distinguishing it from
// other inventory operations
LLFirstUse::newInventory();
closeFloater();
}
void LLFloaterBuyContents::onClickCancel()
{
closeFloater();
}
<commit_msg>EXP-1546 FIXED (received items - purchasing some bodyparts and clothing from a prim marked for sale show wrong inventory icons)<commit_after>/**
* @file llfloaterbuycontents.cpp
* @author James Cook
* @brief LLFloaterBuyContents class implementation
*
* $LicenseInfo:firstyear=2004&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
/**
* Shows the contents of an object and their permissions when you
* click "Buy..." on an object with "Sell Contents" checked.
*/
#include "llviewerprecompiledheaders.h"
#include "llfloaterbuycontents.h"
#include "llcachename.h"
#include "llagent.h" // for agent id
#include "llcheckboxctrl.h"
#include "llinventorydefines.h"
#include "llinventoryfunctions.h"
#include "llinventorymodel.h" // for gInventory
#include "llfirstuse.h"
#include "llfloaterreg.h"
#include "llfloaterinventory.h" // for LLInventoryIcon::getIcon
#include "llnotificationsutil.h"
#include "llselectmgr.h"
#include "llscrolllistctrl.h"
#include "llviewerobject.h"
#include "llviewerregion.h"
#include "lluictrlfactory.h"
#include "llviewerwindow.h"
LLFloaterBuyContents::LLFloaterBuyContents(const LLSD& key)
: LLFloater(key)
{
}
BOOL LLFloaterBuyContents::postBuild()
{
getChild<LLUICtrl>("cancel_btn")->setCommitCallback( boost::bind(&LLFloaterBuyContents::onClickCancel, this));
getChild<LLUICtrl>("buy_btn")->setCommitCallback( boost::bind(&LLFloaterBuyContents::onClickBuy, this));
getChildView("item_list")->setEnabled(FALSE);
getChildView("buy_btn")->setEnabled(FALSE);
getChildView("wear_check")->setEnabled(FALSE);
setDefaultBtn("cancel_btn"); // to avoid accidental buy (SL-43130)
// Always center the dialog. User can change the size,
// but purchases are important and should be center screen.
// This also avoids problems where the user resizes the application window
// mid-session and the saved rect is off-center.
center();
return TRUE;
}
LLFloaterBuyContents::~LLFloaterBuyContents()
{
}
// static
void LLFloaterBuyContents::show(const LLSaleInfo& sale_info)
{
LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
if (selection->getRootObjectCount() != 1)
{
LLNotificationsUtil::add("BuyContentsOneOnly");
return;
}
LLFloaterBuyContents* floater = LLFloaterReg::showTypedInstance<LLFloaterBuyContents>("buy_object_contents");
if (!floater)
return;
LLScrollListCtrl* list = floater->getChild<LLScrollListCtrl>("item_list");
if (list)
list->deleteAllItems();
floater->mObjectSelection = LLSelectMgr::getInstance()->getEditSelection();
LLUUID owner_id;
std::string owner_name;
BOOL owners_identical = LLSelectMgr::getInstance()->selectGetOwner(owner_id, owner_name);
if (!owners_identical)
{
LLNotificationsUtil::add("BuyContentsOneOwner");
return;
}
floater->mSaleInfo = sale_info;
// Update the display
LLSelectNode* node = selection->getFirstRootNode();
if (!node) return;
if(node->mPermissions->isGroupOwned())
{
gCacheName->getGroupName(owner_id, owner_name);
}
floater->getChild<LLUICtrl>("contains_text")->setTextArg("[NAME]", node->mName);
floater->getChild<LLUICtrl>("buy_text")->setTextArg("[AMOUNT]", llformat("%d", sale_info.getSalePrice()));
floater->getChild<LLUICtrl>("buy_text")->setTextArg("[NAME]", owner_name);
// Must do this after the floater is created, because
// sometimes the inventory is already there and
// the callback is called immediately.
LLViewerObject* obj = selection->getFirstRootObject();
floater->registerVOInventoryListener(obj,NULL);
floater->requestVOInventory();
}
void LLFloaterBuyContents::inventoryChanged(LLViewerObject* obj,
LLInventoryObject::object_list_t* inv,
S32 serial_num,
void* data)
{
if (!obj)
{
llwarns << "No object in LLFloaterBuyContents::inventoryChanged" << llendl;
return;
}
if (!inv)
{
llwarns << "No inventory in LLFloaterBuyContents::inventoryChanged"
<< llendl;
removeVOInventoryListener();
return;
}
LLCtrlListInterface *item_list = childGetListInterface("item_list");
if (!item_list)
{
removeVOInventoryListener();
return;
}
// default to turning off the buy button.
getChildView("buy_btn")->setEnabled(FALSE);
LLUUID owner_id;
BOOL is_group_owned;
LLAssetType::EType asset_type;
LLInventoryType::EType inv_type;
S32 wearable_count = 0;
LLInventoryObject::object_list_t::const_iterator it = inv->begin();
LLInventoryObject::object_list_t::const_iterator end = inv->end();
for ( ; it != end; ++it )
{
asset_type = (*it)->getType();
// Skip folders, so we know we have inventory items only
if (asset_type == LLAssetType::AT_CATEGORY)
continue;
LLInventoryItem* inv_item = (LLInventoryItem*)((LLInventoryObject*)(*it));
inv_type = inv_item->getInventoryType();
// Count clothing items for later
if (LLInventoryType::IT_WEARABLE == inv_type)
{
wearable_count++;
}
// Skip items the object's owner can't copy (and hence can't sell)
if (!inv_item->getPermissions().getOwnership(owner_id, is_group_owned))
continue;
if (!inv_item->getPermissions().allowCopyBy(owner_id, owner_id))
continue;
// Skip items we can't transfer
if (!inv_item->getPermissions().allowTransferTo(gAgent.getID()))
continue;
// There will be at least one item shown in the display, so go
// ahead and enable the buy button.
getChildView("buy_btn")->setEnabled(TRUE);
// Create the line in the list
LLSD row;
BOOL item_is_multi = FALSE;
if ((inv_item->getFlags() & LLInventoryItemFlags::II_FLAGS_LANDMARK_VISITED
|| inv_item->getFlags() & LLInventoryItemFlags::II_FLAGS_OBJECT_HAS_MULTIPLE_ITEMS)
&& !(inv_item->getFlags() & LLInventoryItemFlags::II_FLAGS_WEARABLES_MASK))
{
item_is_multi = TRUE;
}
std::string icon_name = LLInventoryIcon::getIconName(inv_item->getType(),
inv_item->getInventoryType(),
inv_item->getFlags(),
item_is_multi);
row["columns"][0]["column"] = "icon";
row["columns"][0]["type"] = "icon";
row["columns"][0]["value"] = icon_name;
// Append the permissions that you will acquire (not the current
// permissions).
U32 next_owner_mask = inv_item->getPermissions().getMaskNextOwner();
std::string text = (*it)->getName();
if (!(next_owner_mask & PERM_COPY))
{
text.append(getString("no_copy_text"));
}
if (!(next_owner_mask & PERM_MODIFY))
{
text.append(getString("no_modify_text"));
}
if (!(next_owner_mask & PERM_TRANSFER))
{
text.append(getString("no_transfer_text"));
}
row["columns"][1]["column"] = "text";
row["columns"][1]["value"] = text;
row["columns"][1]["font"] = "SANSSERIF";
item_list->addElement(row);
}
if (wearable_count > 0)
{
getChildView("wear_check")->setEnabled(TRUE);
getChild<LLUICtrl>("wear_check")->setValue(LLSD(false) );
}
removeVOInventoryListener();
}
void LLFloaterBuyContents::onClickBuy()
{
// Make sure this wasn't selected through other mechanisms
// (ie, being the default button and pressing enter.
if(!getChildView("buy_btn")->getEnabled())
{
// We shouldn't be enabled. Just close.
closeFloater();
return;
}
// We may want to wear this item
if (getChild<LLUICtrl>("wear_check")->getValue())
{
LLInventoryState::sWearNewClothing = TRUE;
}
// Put the items where we put new folders.
LLUUID category_id;
category_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_ROOT_INVENTORY);
// *NOTE: doesn't work for multiple object buy, which UI does not
// currently support sale info is used for verification only, if
// it doesn't match region info then sale is canceled.
LLSelectMgr::getInstance()->sendBuy(gAgent.getID(), category_id, mSaleInfo);
// NOTE: do this here instead of on receipt of object, since contents are transfered
// via a generic BulkUpdateInventory message with no way of distinguishing it from
// other inventory operations
LLFirstUse::newInventory();
closeFloater();
}
void LLFloaterBuyContents::onClickCancel()
{
closeFloater();
}
<|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 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_UT_NAME_HH
#define CQL3_UT_NAME_HH
#include "core/shared_ptr.hh"
#include <experimental/optional>
namespace cql3 {
class ut_name final {
std::experimental::optional<sstring> _ks_name;
const ::shared_ptr<column_identifier> _ut_name;
public:
ut_name(std::experimental::optional<::shared_ptr<column_identifier>> ks_name, ::shared_ptr<column_identifier> ut_name)
: _ks_name{!ks_name ? std::experimental::optional<sstring>{} : std::experimental::optional<sstring>{ks_name.value()->to_string()}}
, _ut_name{ut_name}
{ }
bool has_keyspace() const {
return bool(_ks_name);
}
void set_keyspace(sstring keyspace) {
_ks_name = std::experimental::optional<sstring>{keyspace};
}
sstring get_keyspace() const {
return _ks_name.value();
}
bytes get_user_type_name() const {
return _ut_name->bytes_;
}
sstring get_string_type_name() const
{
return _ut_name->to_string();
}
sstring to_string() const {
return (has_keyspace() ? (_ks_name.value() + ".") : "") + _ut_name->to_string();
}
};
}
#endif
<commit_msg>cql3: add missing include to ut_name.hh<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 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_UT_NAME_HH
#define CQL3_UT_NAME_HH
#include "core/shared_ptr.hh"
#include "column_identifier.hh"
#include <experimental/optional>
namespace cql3 {
class ut_name final {
std::experimental::optional<sstring> _ks_name;
const ::shared_ptr<column_identifier> _ut_name;
public:
ut_name(std::experimental::optional<::shared_ptr<column_identifier>> ks_name, ::shared_ptr<column_identifier> ut_name)
: _ks_name{!ks_name ? std::experimental::optional<sstring>{} : std::experimental::optional<sstring>{ks_name.value()->to_string()}}
, _ut_name{ut_name}
{ }
bool has_keyspace() const {
return bool(_ks_name);
}
void set_keyspace(sstring keyspace) {
_ks_name = std::experimental::optional<sstring>{keyspace};
}
sstring get_keyspace() const {
return _ks_name.value();
}
bytes get_user_type_name() const {
return _ut_name->bytes_;
}
sstring get_string_type_name() const
{
return _ut_name->to_string();
}
sstring to_string() const {
return (has_keyspace() ? (_ks_name.value() + ".") : "") + _ut_name->to_string();
}
};
}
#endif
<|endoftext|>
|
<commit_before>#include "World/Scene.h"
#include "Core/Intersectable/Intersector.h"
#include "Core/Emitter/Sampler/EmitterSampler.h"
#include "Core/HitProbe.h"
#include "Core/HitDetail.h"
#include "Common/assertion.h"
#include "Core/Ray.h"
#include "Core/Intersectable/Primitive.h"
#include "Core/Emitter/Emitter.h"
#include <limits>
namespace ph
{
Scene::Scene() :
m_intersector(nullptr), m_emitterSampler(nullptr),
m_backgroundEmitterPrimitive(nullptr)
{}
Scene::Scene(const Intersector* intersector, const EmitterSampler* emitterSampler) :
m_intersector(intersector), m_emitterSampler(emitterSampler),
m_backgroundEmitterPrimitive(nullptr)
{}
bool Scene::isIntersecting(const Ray& ray, HitProbe* const out_probe) const
{
PH_ASSERT(out_probe);
out_probe->clear();
if(m_intersector->isIntersecting(ray, *out_probe))
{
return true;
}
else if(m_backgroundEmitterPrimitive)
{
return m_backgroundEmitterPrimitive->isIntersecting(ray, *out_probe);
}
return false;
}
bool Scene::isIntersecting(const Ray& ray) const
{
PH_ASSERT(ray.getOrigin().isFinite() && ray.getDirection().isFinite());
if(m_intersector->isIntersecting(ray))
{
return true;
}
else if(m_backgroundEmitterPrimitive)
{
return m_backgroundEmitterPrimitive->isIntersecting(ray);
}
return false;
}
const Emitter* Scene::pickEmitter(real* const out_PDF) const
{
PH_ASSERT(out_PDF);
return m_emitterSampler->pickEmitter(out_PDF);
}
void Scene::genDirectSample(DirectLightSample& sample) const
{
m_emitterSampler->genDirectSample(sample);
}
real Scene::calcDirectPdfW(const SurfaceHit& emitPos, const Vector3R& targetPos) const
{
return m_emitterSampler->calcDirectPdfW(emitPos, targetPos);
}
void Scene::genSensingRay(Ray* out_ray, SpectralStrength* out_Le, Vector3R* out_eN, real* out_pdfA, real* out_pdfW) const
{
real pickPdf;
const Emitter* emitter = m_emitterSampler->pickEmitter(&pickPdf);
emitter->genSensingRay(out_ray, out_Le, out_eN, out_pdfA, out_pdfW);
*out_pdfA *= pickPdf;
}
}// end namespace ph<commit_msg>[bugfix] fixed heisenbug -- a missing probe clear<commit_after>#include "World/Scene.h"
#include "Core/Intersectable/Intersector.h"
#include "Core/Emitter/Sampler/EmitterSampler.h"
#include "Core/HitProbe.h"
#include "Core/HitDetail.h"
#include "Common/assertion.h"
#include "Core/Ray.h"
#include "Core/Intersectable/Primitive.h"
#include "Core/Emitter/Emitter.h"
#include <limits>
namespace ph
{
Scene::Scene() :
m_intersector(nullptr), m_emitterSampler(nullptr),
m_backgroundEmitterPrimitive(nullptr)
{}
Scene::Scene(const Intersector* intersector, const EmitterSampler* emitterSampler) :
m_intersector(intersector), m_emitterSampler(emitterSampler),
m_backgroundEmitterPrimitive(nullptr)
{}
bool Scene::isIntersecting(const Ray& ray, HitProbe* const out_probe) const
{
PH_ASSERT(out_probe);
out_probe->clear();
if(m_intersector->isIntersecting(ray, *out_probe))
{
return true;
}
else if(m_backgroundEmitterPrimitive)
{
out_probe->clear();
return m_backgroundEmitterPrimitive->isIntersecting(ray, *out_probe);
}
return false;
}
bool Scene::isIntersecting(const Ray& ray) const
{
PH_ASSERT(ray.getOrigin().isFinite() && ray.getDirection().isFinite());
if(m_intersector->isIntersecting(ray))
{
return true;
}
else if(m_backgroundEmitterPrimitive)
{
return m_backgroundEmitterPrimitive->isIntersecting(ray);
}
return false;
}
const Emitter* Scene::pickEmitter(real* const out_PDF) const
{
PH_ASSERT(out_PDF);
return m_emitterSampler->pickEmitter(out_PDF);
}
void Scene::genDirectSample(DirectLightSample& sample) const
{
m_emitterSampler->genDirectSample(sample);
}
real Scene::calcDirectPdfW(const SurfaceHit& emitPos, const Vector3R& targetPos) const
{
return m_emitterSampler->calcDirectPdfW(emitPos, targetPos);
}
void Scene::genSensingRay(Ray* out_ray, SpectralStrength* out_Le, Vector3R* out_eN, real* out_pdfA, real* out_pdfW) const
{
real pickPdf;
const Emitter* emitter = m_emitterSampler->pickEmitter(&pickPdf);
emitter->genSensingRay(out_ray, out_Le, out_eN, out_pdfA, out_pdfW);
*out_pdfA *= pickPdf;
}
}// end namespace ph<|endoftext|>
|
<commit_before>// Copyright (c) 2014 The Chromium Embedded Framework 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 <algorithm>
#include <cstdlib>
#include <string>
#include "include/cef_stream.h"
#include "include/wrapper/cef_stream_resource_handler.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "tests/unittests/routing_test_handler.h"
namespace {
const char kTestUrl[] = "http://tests-srh/test.html";
const size_t kReadBlockSize = 1024U; // 1k.
// The usual network buffer size is about 32k. Choose a value that's larger.
const size_t kReadDesiredSize = 100U * 1024U; // 100k
class ReadHandler : public CefReadHandler {
public:
explicit ReadHandler(bool may_block)
: may_block_(may_block),
offset_(0),
expected_result_(0) {
}
void CreateContent() {
// To verify that the data transers successfully we're going to make a big
// math problem.
content_.reserve(kReadDesiredSize + 50U);
content_ = "<html><body><script>var myratherlongvariablename=0;";
while (content_.size() < kReadDesiredSize) {
content_ += "myratherlongvariablename=myratherlongvariablename+1;";
expected_result_++;
}
content_ += "window.testQuery({request:myratherlongvariablename+''});"
"</script></body></html>";
}
int GetExpectedResult() const {
return expected_result_;
}
virtual size_t Read(void* ptr, size_t size, size_t n) OVERRIDE {
EXPECT_EQ(1, size);
// Read the minimum of requested size, remaining size or kReadBlockSize.
const size_t read_bytes =
std::min(std::min(size * n, content_.size() - offset_), kReadBlockSize);
if (read_bytes > 0) {
memcpy(ptr, content_.c_str() + offset_, read_bytes);
offset_ += read_bytes;
}
return read_bytes;
}
virtual int Seek(int64 offset, int whence) OVERRIDE {
EXPECT_TRUE(false); // Not reached.
return 0;
}
virtual int64 Tell() OVERRIDE {
EXPECT_TRUE(false); // Not reached.
return 0;
}
virtual int Eof() OVERRIDE {
EXPECT_TRUE(false); // Not reached.
return 0;
}
virtual bool MayBlock() OVERRIDE {
return may_block_;
}
private:
const bool may_block_;
std::string content_;
size_t offset_;
int expected_result_;
IMPLEMENT_REFCOUNTING(StreamReader);
};
class ReadTestHandler : public RoutingTestHandler {
public:
explicit ReadTestHandler(bool may_block)
: may_block_(may_block),
expected_result_(0) {}
virtual void RunTest() OVERRIDE {
// Create the browser.
CreateBrowser(kTestUrl);
}
virtual CefRefPtr<CefResourceHandler> GetResourceHandler(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) OVERRIDE {
got_resource_handler_.yes();
const std::string& url = request->GetURL();
EXPECT_STREQ(kTestUrl, url.c_str());
CefRefPtr<ReadHandler> handler = new ReadHandler(may_block_);
handler->CreateContent();
expected_result_ = handler->GetExpectedResult();
CefRefPtr<CefStreamReader> stream =
CefStreamReader::CreateForHandler(handler.get());
return new CefStreamResourceHandler("text/html", stream);
}
virtual bool OnQuery(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int64 query_id,
const CefString& request,
bool persistent,
CefRefPtr<Callback> callback) OVERRIDE {
got_on_query_.yes();
const int actual_result = atoi(request.ToString().c_str());
EXPECT_EQ(expected_result_, actual_result);
DestroyTest();
return true;
}
private:
virtual void DestroyTest() OVERRIDE {
EXPECT_TRUE(got_resource_handler_);
EXPECT_TRUE(got_on_query_);
RoutingTestHandler::DestroyTest();
}
const bool may_block_;
int expected_result_;
TrackCallback got_resource_handler_;
TrackCallback got_on_query_;
};
} // namespace
TEST(StreamResourceHandlerTest, ReadWillBlock) {
CefRefPtr<ReadTestHandler> handler = new ReadTestHandler(true);
handler->ExecuteTest();
}
TEST(StreamResourceHandlerTest, ReadWontBlock) {
CefRefPtr<ReadTestHandler> handler = new ReadTestHandler(false);
handler->ExecuteTest();
}
<commit_msg>Mac: Fix compile errors.<commit_after>// Copyright (c) 2014 The Chromium Embedded Framework 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 <algorithm>
#include <cstdlib>
#include <string>
#include "include/cef_stream.h"
#include "include/wrapper/cef_stream_resource_handler.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "tests/unittests/routing_test_handler.h"
namespace {
const char kTestUrl[] = "http://tests-srh/test.html";
const size_t kReadBlockSize = 1024U; // 1k.
// The usual network buffer size is about 32k. Choose a value that's larger.
const size_t kReadDesiredSize = 100U * 1024U; // 100k
class ReadHandler : public CefReadHandler {
public:
explicit ReadHandler(bool may_block)
: may_block_(may_block),
offset_(0),
expected_result_(0) {
}
void CreateContent() {
// To verify that the data transers successfully we're going to make a big
// math problem.
content_.reserve(kReadDesiredSize + 50U);
content_ = "<html><body><script>var myratherlongvariablename=0;";
while (content_.size() < kReadDesiredSize) {
content_ += "myratherlongvariablename=myratherlongvariablename+1;";
expected_result_++;
}
content_ += "window.testQuery({request:myratherlongvariablename+''});"
"</script></body></html>";
}
int GetExpectedResult() const {
return expected_result_;
}
virtual size_t Read(void* ptr, size_t size, size_t n) OVERRIDE {
EXPECT_EQ(1U, size);
// Read the minimum of requested size, remaining size or kReadBlockSize.
const size_t read_bytes =
std::min(std::min(size * n, content_.size() - offset_), kReadBlockSize);
if (read_bytes > 0) {
memcpy(ptr, content_.c_str() + offset_, read_bytes);
offset_ += read_bytes;
}
return read_bytes;
}
virtual int Seek(int64 offset, int whence) OVERRIDE {
EXPECT_TRUE(false); // Not reached.
return 0;
}
virtual int64 Tell() OVERRIDE {
EXPECT_TRUE(false); // Not reached.
return 0;
}
virtual int Eof() OVERRIDE {
EXPECT_TRUE(false); // Not reached.
return 0;
}
virtual bool MayBlock() OVERRIDE {
return may_block_;
}
private:
const bool may_block_;
std::string content_;
size_t offset_;
int expected_result_;
IMPLEMENT_REFCOUNTING(StreamReader);
};
class ReadTestHandler : public RoutingTestHandler {
public:
explicit ReadTestHandler(bool may_block)
: may_block_(may_block),
expected_result_(0) {}
virtual void RunTest() OVERRIDE {
// Create the browser.
CreateBrowser(kTestUrl);
}
virtual CefRefPtr<CefResourceHandler> GetResourceHandler(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) OVERRIDE {
got_resource_handler_.yes();
const std::string& url = request->GetURL();
EXPECT_STREQ(kTestUrl, url.c_str());
CefRefPtr<ReadHandler> handler = new ReadHandler(may_block_);
handler->CreateContent();
expected_result_ = handler->GetExpectedResult();
CefRefPtr<CefStreamReader> stream =
CefStreamReader::CreateForHandler(handler.get());
return new CefStreamResourceHandler("text/html", stream);
}
virtual bool OnQuery(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int64 query_id,
const CefString& request,
bool persistent,
CefRefPtr<Callback> callback) OVERRIDE {
got_on_query_.yes();
const int actual_result = atoi(request.ToString().c_str());
EXPECT_EQ(expected_result_, actual_result);
DestroyTest();
return true;
}
private:
virtual void DestroyTest() OVERRIDE {
EXPECT_TRUE(got_resource_handler_);
EXPECT_TRUE(got_on_query_);
RoutingTestHandler::DestroyTest();
}
const bool may_block_;
int expected_result_;
TrackCallback got_resource_handler_;
TrackCallback got_on_query_;
};
} // namespace
TEST(StreamResourceHandlerTest, ReadWillBlock) {
CefRefPtr<ReadTestHandler> handler = new ReadTestHandler(true);
handler->ExecuteTest();
}
TEST(StreamResourceHandlerTest, ReadWontBlock) {
CefRefPtr<ReadTestHandler> handler = new ReadTestHandler(false);
handler->ExecuteTest();
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2011 The Libphonenumber Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Tao Huang
//
// Basic test cases for PhoneNumberMatch.
#include "phonenumbers/phonenumber.h"
#include "phonenumbers/phonenumbermatch.h"
#include <gtest/gtest.h>
#include "phonenumbers/phonenumber.pb.h"
namespace i18n {
namespace phonenumbers {
TEST(PhoneNumberMatch, TestGetterMethods) {
PhoneNumber number;
const int start_index = 10;
const string raw_phone_number("1 800 234 45 67");
PhoneNumberMatch match1(start_index, raw_phone_number, number);
EXPECT_EQ(start_index, match1.start());
EXPECT_EQ(start_index + raw_phone_number.length(), match1.end());
EXPECT_EQ(raw_phone_number.length(), match1.length());
EXPECT_EQ(raw_phone_number, match1.raw_string());
EXPECT_EQ("PhoneNumberMatch [10,25) 1 800 234 45 67", match1.ToString());
}
TEST(PhoneNumberMatch, TestEquals) {
PhoneNumber number;
PhoneNumberMatch match1(10, "1 800 234 45 67", number);
PhoneNumberMatch match2(10, "1 800 234 45 67", number);
match2.set_start(11);
ASSERT_FALSE(match1.Equals(match2));
match2.set_start(match1.start());
EXPECT_TRUE(match1.Equals(match2));
PhoneNumber number2;
number2.set_raw_input("123");
match2.set_number(number2);
ASSERT_FALSE(match1.Equals(match2));
match2.set_number(match1.number());
EXPECT_TRUE(ExactlySameAs(match1.number(), match2.number()));
EXPECT_TRUE(match1.Equals(match2));
match2.set_raw_string("123");
ASSERT_FALSE(match1.Equals(match2));
}
TEST(PhoneNumberMatch, TestAssignmentOverload) {
PhoneNumber number;
PhoneNumberMatch match1(10, "1 800 234 45 67", number);
PhoneNumberMatch match2;
ASSERT_FALSE(match1.Equals(match2));
match2.CopyFrom(match1);
ASSERT_TRUE(match1.Equals(match2));
PhoneNumberMatch match3;
PhoneNumberMatch match4;
match4.CopyFrom(match2);
match3.CopyFrom(match2);
ASSERT_TRUE(match3.Equals(match4));
ASSERT_TRUE(match4.Equals(match2));
}
TEST(PhoneNumberMatch, TestCopyConstructor) {
PhoneNumber number;
PhoneNumberMatch match1(10, "1 800 234 45 67", number);
PhoneNumberMatch match2;
match2.CopyFrom(match1);
ASSERT_TRUE(match1.Equals(match2));
}
} // namespace phonenumbers
} // namespace i18n
<commit_msg>CPP: Adjust phonenumbermatch_test.cc integer types.<commit_after>// Copyright (C) 2011 The Libphonenumber Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Tao Huang
//
// Basic test cases for PhoneNumberMatch.
#include "phonenumbers/phonenumber.h"
#include "phonenumbers/phonenumbermatch.h"
#include <gtest/gtest.h>
#include "phonenumbers/phonenumber.pb.h"
namespace i18n {
namespace phonenumbers {
TEST(PhoneNumberMatch, TestGetterMethods) {
PhoneNumber number;
const int start_index = 10;
const string raw_phone_number("1 800 234 45 67");
PhoneNumberMatch match1(start_index, raw_phone_number, number);
EXPECT_EQ(start_index, match1.start());
EXPECT_EQ(start_index + static_cast<int>(raw_phone_number.length()),
match1.end());
EXPECT_EQ(static_cast<int>(raw_phone_number.length()), match1.length());
EXPECT_EQ(raw_phone_number, match1.raw_string());
EXPECT_EQ("PhoneNumberMatch [10,25) 1 800 234 45 67", match1.ToString());
}
TEST(PhoneNumberMatch, TestEquals) {
PhoneNumber number;
PhoneNumberMatch match1(10, "1 800 234 45 67", number);
PhoneNumberMatch match2(10, "1 800 234 45 67", number);
match2.set_start(11);
ASSERT_FALSE(match1.Equals(match2));
match2.set_start(match1.start());
EXPECT_TRUE(match1.Equals(match2));
PhoneNumber number2;
number2.set_raw_input("123");
match2.set_number(number2);
ASSERT_FALSE(match1.Equals(match2));
match2.set_number(match1.number());
EXPECT_TRUE(ExactlySameAs(match1.number(), match2.number()));
EXPECT_TRUE(match1.Equals(match2));
match2.set_raw_string("123");
ASSERT_FALSE(match1.Equals(match2));
}
TEST(PhoneNumberMatch, TestAssignmentOverload) {
PhoneNumber number;
PhoneNumberMatch match1(10, "1 800 234 45 67", number);
PhoneNumberMatch match2;
ASSERT_FALSE(match1.Equals(match2));
match2.CopyFrom(match1);
ASSERT_TRUE(match1.Equals(match2));
PhoneNumberMatch match3;
PhoneNumberMatch match4;
match4.CopyFrom(match2);
match3.CopyFrom(match2);
ASSERT_TRUE(match3.Equals(match4));
ASSERT_TRUE(match4.Equals(match2));
}
TEST(PhoneNumberMatch, TestCopyConstructor) {
PhoneNumber number;
PhoneNumberMatch match1(10, "1 800 234 45 67", number);
PhoneNumberMatch match2;
match2.CopyFrom(match1);
ASSERT_TRUE(match1.Equals(match2));
}
} // namespace phonenumbers
} // namespace i18n
<|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 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#pragma once
#include "cql3/restrictions/abstract_restriction.hh"
#include "cql3/restrictions/term_slice.hh"
#include "cql3/term.hh"
#include "core/shared_ptr.hh"
#include "schema.hh"
#include "to_string.hh"
#include "exceptions/exceptions.hh"
namespace cql3 {
namespace restrictions {
class single_column_restriction : public abstract_restriction {
protected:
/**
* The definition of the column to which apply the restriction.
*/
const column_definition& _column_def;
public:
single_column_restriction(const column_definition& column_def)
: _column_def(column_def)
{ }
const column_definition& get_column_def() {
return _column_def;
}
#if 0
@Override
public void addIndexExpressionTo(List<IndexExpression> expressions,
QueryOptions options) throws InvalidRequestException
{
List<ByteBuffer> values = values(options);
checkTrue(values.size() == 1, "IN restrictions are not supported on indexed columns");
ByteBuffer value = validateIndexedValue(columnDef, values.get(0));
expressions.add(new IndexExpression(columnDef.name.bytes, Operator.EQ, value));
}
@Override
public boolean hasSupportingIndex(SecondaryIndexManager indexManager)
{
SecondaryIndex index = indexManager.getIndexForColumn(columnDef.name.bytes);
return index != null && isSupportedBy(index);
}
/**
* Check if this type of restriction is supported by the specified index.
*
* @param index the Secondary index
* @return <code>true</code> this type of restriction is supported by the specified index,
* <code>false</code> otherwise.
*/
protected abstract boolean isSupportedBy(SecondaryIndex index);
#endif
class EQ;
class IN;
class IN_with_values;
#if 0
public static class InWithMarker extends IN
{
protected final AbstractMarker marker;
public InWithMarker(ColumnDefinition columnDef, AbstractMarker marker)
{
super(columnDef);
this.marker = marker;
}
@Override
public boolean usesFunction(String ksName, String functionName)
{
return false;
}
public List<ByteBuffer> values(QueryOptions options) throws InvalidRequestException
{
Term.MultiItemTerminal lval = (Term.MultiItemTerminal) marker.bind(options);
if (lval == null)
throw new InvalidRequestException("Invalid null value for IN restriction");
return lval.getElements();
}
@Override
public String toString()
{
return "IN ?";
}
}
#endif
class slice;
class contains;
};
class single_column_restriction::EQ final : public single_column_restriction {
private:
::shared_ptr<term> _value;
public:
EQ(const column_definition& column_def, ::shared_ptr<term> value)
: single_column_restriction(column_def)
, _value(std::move(value))
{ }
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return abstract_restriction::uses_function(_value, ks_name, function_name);
}
virtual bool is_EQ() override {
return true;
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
std::vector<bytes_opt> v;
v.push_back(_value->bind_and_get(options));
return v;
}
virtual bytes_opt value(const query_options& options) override {
return _value->bind_and_get(options);
}
virtual sstring to_string() override {
return sprint("EQ(%s)", _value->to_string());
}
virtual void merge_with(::shared_ptr<restriction> other) {
throw exceptions::invalid_request_exception(sprint(
"%s cannot be restricted by more than one relation if it includes an Equal", _column_def.name_as_text()));
}
#if 0
@Override
protected boolean isSupportedBy(SecondaryIndex index)
{
return index.supportsOperator(Operator.EQ);
}
#endif
};
class single_column_restriction::IN : public single_column_restriction {
public:
IN(const column_definition& column_def)
: single_column_restriction(column_def)
{ }
virtual bool is_IN() override {
return true;
}
virtual void merge_with(::shared_ptr<restriction> r) override {
throw exceptions::invalid_request_exception(sprint(
"%s cannot be restricted by more than one relation if it includes a IN", _column_def.name_as_text()));
}
#if 0
@Override
protected final boolean isSupportedBy(SecondaryIndex index)
{
return index.supportsOperator(Operator.IN);
}
#endif
};
class single_column_restriction::IN_with_values : public single_column_restriction::IN {
protected:
std::vector<::shared_ptr<term>> _values;
public:
IN_with_values(const column_definition& column_def, std::vector<::shared_ptr<term>> values)
: single_column_restriction::IN(column_def)
, _values(std::move(values))
{ }
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return abstract_restriction::uses_function(_values, ks_name, function_name);
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
std::vector<bytes_opt> ret;
for (auto&& v : _values) {
ret.emplace_back(v->bind_and_get(options));
}
return ret;
}
virtual sstring to_string() override {
return sprint("IN(%s)", ::to_string(_values));
}
};
class single_column_restriction::slice : public single_column_restriction {
private:
term_slice _slice;
public:
slice(const column_definition& column_def, statements::bound bound, bool inclusive, ::shared_ptr<term> term)
: single_column_restriction(column_def)
, _slice(term_slice::new_instance(bound, inclusive, std::move(term)))
{ }
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return (_slice.has_bound(statements::bound::START) && abstract_restriction::uses_function(_slice.bound(statements::bound::START), ks_name, function_name))
|| (_slice.has_bound(statements::bound::END) && abstract_restriction::uses_function(_slice.bound(statements::bound::END), ks_name, function_name));
}
virtual bool is_slice() override {
return true;
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
throw exceptions::unsupported_operation_exception();
}
virtual bool has_bound(statements::bound b) override {
return _slice.has_bound(b);
}
virtual std::vector<bytes_opt> bounds(statements::bound b, const query_options& options) override {
return {_slice.bound(b)->bind_and_get(options)};
}
virtual bool is_inclusive(statements::bound b) override {
return _slice.is_inclusive(b);
}
virtual void merge_with(::shared_ptr<restriction> r) override {
if (!r->is_slice()) {
throw exceptions::invalid_request_exception(sprint(
"Column \"%s\" cannot be restricted by both an equality and an inequality relation", _column_def.name_as_text()));
}
auto other_slice = static_pointer_cast<slice>(r);
if (has_bound(statements::bound::START) && other_slice->has_bound(statements::bound::START)) {
throw exceptions::invalid_request_exception(sprint(
"More than one restriction was found for the start bound on %s", _column_def.name_as_text()));
}
if (has_bound(statements::bound::END) && other_slice->has_bound(statements::bound::END)) {
throw exceptions::invalid_request_exception(sprint(
"More than one restriction was found for the end bound on %s", _column_def.name_as_text()));
}
_slice.merge(other_slice->_slice);
}
#if 0
virtual void addIndexExpressionTo(List<IndexExpression> expressions, override
QueryOptions options) throws InvalidRequestException
{
for (statements::bound b : {statements::bound::START, statements::bound::END})
{
if (has_bound(b))
{
ByteBuffer value = validateIndexedValue(columnDef, _slice.bound(b).bindAndGet(options));
Operator op = _slice.getIndexOperator(b);
// If the underlying comparator for name is reversed, we need to reverse the IndexOperator: user operation
// always refer to the "forward" sorting even if the clustering order is reversed, but the 2ndary code does
// use the underlying comparator as is.
op = columnDef.isReversedType() ? op.reverse() : op;
expressions.add(new IndexExpression(columnDef.name.bytes, op, value));
}
}
}
virtual bool isSupportedBy(SecondaryIndex index) override
{
return _slice.isSupportedBy(index);
}
#endif
virtual sstring to_string() override {
return sprint("SLICE%s", _slice);
}
};
// This holds CONTAINS, CONTAINS_KEY, and map[key] = value restrictions because we might want to have any combination of them.
class single_column_restriction::contains final : public single_column_restriction {
private:
std::vector<::shared_ptr<term>> _values;
std::vector<::shared_ptr<term>> _keys;
std::vector<::shared_ptr<term>> _entry_keys;
std::vector<::shared_ptr<term>> _entry_values;
public:
contains(const column_definition& column_def, ::shared_ptr<term> t, bool is_key)
: single_column_restriction(column_def) {
if (is_key) {
_keys.emplace_back(std::move(t));
} else {
_values.emplace_back(std::move(t));
}
}
contains(const column_definition& column_def, ::shared_ptr<term> map_key, ::shared_ptr<term> map_value)
: single_column_restriction(column_def) {
_entry_keys.emplace_back(std::move(map_key));
_entry_values.emplace_back(std::move(map_value));
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
return bind_and_get(_values, options);
}
virtual bool is_contains() override {
return true;
}
virtual void merge_with(::shared_ptr<restriction> other_restriction) override {
if (!other_restriction->is_contains()) {
throw exceptions::invalid_request_exception(sprint(
"Collection column %s can only be restricted by CONTAINS, CONTAINS KEY, or map-entry equality",
get_column_def().name_as_text()));
}
auto other = static_pointer_cast<contains>(other_restriction);
std::copy(other->_values.begin(), other->_values.end(), std::back_inserter(_values));
std::copy(other->_keys.begin(), other->_keys.end(), std::back_inserter(_keys));
std::copy(other->_entry_keys.begin(), other->_entry_keys.end(), std::back_inserter(_entry_keys));
std::copy(other->_entry_values.begin(), other->_entry_values.end(), std::back_inserter(_entry_values));
}
#if 0
virtual void add_index_expression_to(std::vector<::shared_ptr<index_expression>>& expressions,
const query_options& options) override {
add_expressions_for(expressions, values(options), operator_type::CONTAINS);
add_expressions_for(expressions, keys(options), operator_type::CONTAINS_KEY);
add_expressions_for(expressions, entries(options), operator_type::EQ);
}
private void add_expressions_for(std::vector<::shared_ptr<index_expression>>& target, std::vector<bytes_opt> values,
const operator_type& op) {
for (ByteBuffer value : values)
{
validateIndexedValue(columnDef, value);
target.add(new IndexExpression(columnDef.name.bytes, op, value));
}
}
virtual bool is_supported_by(SecondaryIndex index) override {
bool supported = false;
if (numberOfValues() > 0)
supported |= index.supportsOperator(Operator.CONTAINS);
if (numberOfKeys() > 0)
supported |= index.supportsOperator(Operator.CONTAINS_KEY);
if (numberOfEntries() > 0)
supported |= index.supportsOperator(Operator.EQ);
return supported;
}
#endif
uint32_t number_of_values() {
return _values.size();
}
uint32_t number_of_keys() {
return _keys.size();
}
uint32_t number_of_entries() {
return _entry_keys.size();
}
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return abstract_restriction::uses_function(_values, ks_name, function_name)
|| abstract_restriction::uses_function(_keys, ks_name, function_name)
|| abstract_restriction::uses_function(_entry_keys, ks_name, function_name)
|| abstract_restriction::uses_function(_entry_values, ks_name, function_name);
}
virtual sstring to_string() override {
return sprint("CONTAINS(values=%s, keys=%s, entryKeys=%s, entryValues=%s)",
::to_string(_values), ::to_string(_keys), ::to_string(_entry_keys), ::to_string(_entry_values));
}
virtual bool has_bound(statements::bound b) override {
throw exceptions::unsupported_operation_exception();
}
virtual std::vector<bytes_opt> bounds(statements::bound b, const query_options& options) override {
throw exceptions::unsupported_operation_exception();
}
virtual bool is_inclusive(statements::bound b) override {
throw exceptions::unsupported_operation_exception();
}
#if 0
private List<ByteBuffer> keys(const query_options& options) {
return bindAndGet(keys, options);
}
private List<ByteBuffer> entries(QueryOptions options) throws InvalidRequestException
{
List<ByteBuffer> entryBuffers = new ArrayList<>(_entry_keys.size());
List<ByteBuffer> keyBuffers = bindAndGet(_entry_keys, options);
List<ByteBuffer> valueBuffers = bindAndGet(_entry_values, options);
for (int i = 0; i < _entry_keys.size(); i++)
{
if (valueBuffers.get(i) == null)
throw new InvalidRequestException("Unsupported null value for map-entry equality");
entryBuffers.add(CompositeType.build(keyBuffers.get(i), valueBuffers.get(i)));
}
return entryBuffers;
}
#endif
private:
/**
* Binds the query options to the specified terms and returns the resulting values.
*
* @param terms the terms
* @param options the query options
* @return the value resulting from binding the query options to the specified terms
* @throws invalid_request_exception if a problem occurs while binding the query options
*/
static std::vector<bytes_opt> bind_and_get(std::vector<::shared_ptr<term>> terms, const query_options& options) {
std::vector<bytes_opt> values;
values.reserve(terms.size());
for (auto&& term : terms) {
values.emplace_back(term->bind_and_get(options));
}
return values;
}
};
}
}
<commit_msg>cql3: convert single_column_restriction::IN_with_marker to C++<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 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#pragma once
#include "cql3/restrictions/abstract_restriction.hh"
#include "cql3/restrictions/term_slice.hh"
#include "cql3/term.hh"
#include "cql3/abstract_marker.hh"
#include "core/shared_ptr.hh"
#include "schema.hh"
#include "to_string.hh"
#include "exceptions/exceptions.hh"
namespace cql3 {
namespace restrictions {
class single_column_restriction : public abstract_restriction {
protected:
/**
* The definition of the column to which apply the restriction.
*/
const column_definition& _column_def;
public:
single_column_restriction(const column_definition& column_def)
: _column_def(column_def)
{ }
const column_definition& get_column_def() {
return _column_def;
}
#if 0
@Override
public void addIndexExpressionTo(List<IndexExpression> expressions,
QueryOptions options) throws InvalidRequestException
{
List<ByteBuffer> values = values(options);
checkTrue(values.size() == 1, "IN restrictions are not supported on indexed columns");
ByteBuffer value = validateIndexedValue(columnDef, values.get(0));
expressions.add(new IndexExpression(columnDef.name.bytes, Operator.EQ, value));
}
@Override
public boolean hasSupportingIndex(SecondaryIndexManager indexManager)
{
SecondaryIndex index = indexManager.getIndexForColumn(columnDef.name.bytes);
return index != null && isSupportedBy(index);
}
/**
* Check if this type of restriction is supported by the specified index.
*
* @param index the Secondary index
* @return <code>true</code> this type of restriction is supported by the specified index,
* <code>false</code> otherwise.
*/
protected abstract boolean isSupportedBy(SecondaryIndex index);
#endif
class EQ;
class IN;
class IN_with_values;
class IN_with_marker;
class slice;
class contains;
};
class single_column_restriction::EQ final : public single_column_restriction {
private:
::shared_ptr<term> _value;
public:
EQ(const column_definition& column_def, ::shared_ptr<term> value)
: single_column_restriction(column_def)
, _value(std::move(value))
{ }
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return abstract_restriction::uses_function(_value, ks_name, function_name);
}
virtual bool is_EQ() override {
return true;
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
std::vector<bytes_opt> v;
v.push_back(_value->bind_and_get(options));
return v;
}
virtual bytes_opt value(const query_options& options) override {
return _value->bind_and_get(options);
}
virtual sstring to_string() override {
return sprint("EQ(%s)", _value->to_string());
}
virtual void merge_with(::shared_ptr<restriction> other) {
throw exceptions::invalid_request_exception(sprint(
"%s cannot be restricted by more than one relation if it includes an Equal", _column_def.name_as_text()));
}
#if 0
@Override
protected boolean isSupportedBy(SecondaryIndex index)
{
return index.supportsOperator(Operator.EQ);
}
#endif
};
class single_column_restriction::IN : public single_column_restriction {
public:
IN(const column_definition& column_def)
: single_column_restriction(column_def)
{ }
virtual bool is_IN() override {
return true;
}
virtual void merge_with(::shared_ptr<restriction> r) override {
throw exceptions::invalid_request_exception(sprint(
"%s cannot be restricted by more than one relation if it includes a IN", _column_def.name_as_text()));
}
#if 0
@Override
protected final boolean isSupportedBy(SecondaryIndex index)
{
return index.supportsOperator(Operator.IN);
}
#endif
};
class single_column_restriction::IN_with_values : public single_column_restriction::IN {
protected:
std::vector<::shared_ptr<term>> _values;
public:
IN_with_values(const column_definition& column_def, std::vector<::shared_ptr<term>> values)
: single_column_restriction::IN(column_def)
, _values(std::move(values))
{ }
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return abstract_restriction::uses_function(_values, ks_name, function_name);
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
std::vector<bytes_opt> ret;
for (auto&& v : _values) {
ret.emplace_back(v->bind_and_get(options));
}
return ret;
}
virtual sstring to_string() override {
return sprint("IN(%s)", ::to_string(_values));
}
};
class single_column_restriction::IN_with_marker : public IN {
public:
shared_ptr<abstract_marker> _marker;
public:
IN_with_marker(const column_definition& column_def, shared_ptr<abstract_marker> marker)
: IN(column_def), _marker(std::move(marker)) {
}
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return false;
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
auto&& lval = dynamic_pointer_cast<multi_item_terminal>(_marker->bind(options));
if (!lval) {
throw exceptions::invalid_request_exception("Invalid null value for IN restriction");
}
return lval->get_elements();
}
virtual sstring to_string() override {
return "IN ?";
}
};
class single_column_restriction::slice : public single_column_restriction {
private:
term_slice _slice;
public:
slice(const column_definition& column_def, statements::bound bound, bool inclusive, ::shared_ptr<term> term)
: single_column_restriction(column_def)
, _slice(term_slice::new_instance(bound, inclusive, std::move(term)))
{ }
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return (_slice.has_bound(statements::bound::START) && abstract_restriction::uses_function(_slice.bound(statements::bound::START), ks_name, function_name))
|| (_slice.has_bound(statements::bound::END) && abstract_restriction::uses_function(_slice.bound(statements::bound::END), ks_name, function_name));
}
virtual bool is_slice() override {
return true;
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
throw exceptions::unsupported_operation_exception();
}
virtual bool has_bound(statements::bound b) override {
return _slice.has_bound(b);
}
virtual std::vector<bytes_opt> bounds(statements::bound b, const query_options& options) override {
return {_slice.bound(b)->bind_and_get(options)};
}
virtual bool is_inclusive(statements::bound b) override {
return _slice.is_inclusive(b);
}
virtual void merge_with(::shared_ptr<restriction> r) override {
if (!r->is_slice()) {
throw exceptions::invalid_request_exception(sprint(
"Column \"%s\" cannot be restricted by both an equality and an inequality relation", _column_def.name_as_text()));
}
auto other_slice = static_pointer_cast<slice>(r);
if (has_bound(statements::bound::START) && other_slice->has_bound(statements::bound::START)) {
throw exceptions::invalid_request_exception(sprint(
"More than one restriction was found for the start bound on %s", _column_def.name_as_text()));
}
if (has_bound(statements::bound::END) && other_slice->has_bound(statements::bound::END)) {
throw exceptions::invalid_request_exception(sprint(
"More than one restriction was found for the end bound on %s", _column_def.name_as_text()));
}
_slice.merge(other_slice->_slice);
}
#if 0
virtual void addIndexExpressionTo(List<IndexExpression> expressions, override
QueryOptions options) throws InvalidRequestException
{
for (statements::bound b : {statements::bound::START, statements::bound::END})
{
if (has_bound(b))
{
ByteBuffer value = validateIndexedValue(columnDef, _slice.bound(b).bindAndGet(options));
Operator op = _slice.getIndexOperator(b);
// If the underlying comparator for name is reversed, we need to reverse the IndexOperator: user operation
// always refer to the "forward" sorting even if the clustering order is reversed, but the 2ndary code does
// use the underlying comparator as is.
op = columnDef.isReversedType() ? op.reverse() : op;
expressions.add(new IndexExpression(columnDef.name.bytes, op, value));
}
}
}
virtual bool isSupportedBy(SecondaryIndex index) override
{
return _slice.isSupportedBy(index);
}
#endif
virtual sstring to_string() override {
return sprint("SLICE%s", _slice);
}
};
// This holds CONTAINS, CONTAINS_KEY, and map[key] = value restrictions because we might want to have any combination of them.
class single_column_restriction::contains final : public single_column_restriction {
private:
std::vector<::shared_ptr<term>> _values;
std::vector<::shared_ptr<term>> _keys;
std::vector<::shared_ptr<term>> _entry_keys;
std::vector<::shared_ptr<term>> _entry_values;
public:
contains(const column_definition& column_def, ::shared_ptr<term> t, bool is_key)
: single_column_restriction(column_def) {
if (is_key) {
_keys.emplace_back(std::move(t));
} else {
_values.emplace_back(std::move(t));
}
}
contains(const column_definition& column_def, ::shared_ptr<term> map_key, ::shared_ptr<term> map_value)
: single_column_restriction(column_def) {
_entry_keys.emplace_back(std::move(map_key));
_entry_values.emplace_back(std::move(map_value));
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
return bind_and_get(_values, options);
}
virtual bool is_contains() override {
return true;
}
virtual void merge_with(::shared_ptr<restriction> other_restriction) override {
if (!other_restriction->is_contains()) {
throw exceptions::invalid_request_exception(sprint(
"Collection column %s can only be restricted by CONTAINS, CONTAINS KEY, or map-entry equality",
get_column_def().name_as_text()));
}
auto other = static_pointer_cast<contains>(other_restriction);
std::copy(other->_values.begin(), other->_values.end(), std::back_inserter(_values));
std::copy(other->_keys.begin(), other->_keys.end(), std::back_inserter(_keys));
std::copy(other->_entry_keys.begin(), other->_entry_keys.end(), std::back_inserter(_entry_keys));
std::copy(other->_entry_values.begin(), other->_entry_values.end(), std::back_inserter(_entry_values));
}
#if 0
virtual void add_index_expression_to(std::vector<::shared_ptr<index_expression>>& expressions,
const query_options& options) override {
add_expressions_for(expressions, values(options), operator_type::CONTAINS);
add_expressions_for(expressions, keys(options), operator_type::CONTAINS_KEY);
add_expressions_for(expressions, entries(options), operator_type::EQ);
}
private void add_expressions_for(std::vector<::shared_ptr<index_expression>>& target, std::vector<bytes_opt> values,
const operator_type& op) {
for (ByteBuffer value : values)
{
validateIndexedValue(columnDef, value);
target.add(new IndexExpression(columnDef.name.bytes, op, value));
}
}
virtual bool is_supported_by(SecondaryIndex index) override {
bool supported = false;
if (numberOfValues() > 0)
supported |= index.supportsOperator(Operator.CONTAINS);
if (numberOfKeys() > 0)
supported |= index.supportsOperator(Operator.CONTAINS_KEY);
if (numberOfEntries() > 0)
supported |= index.supportsOperator(Operator.EQ);
return supported;
}
#endif
uint32_t number_of_values() {
return _values.size();
}
uint32_t number_of_keys() {
return _keys.size();
}
uint32_t number_of_entries() {
return _entry_keys.size();
}
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return abstract_restriction::uses_function(_values, ks_name, function_name)
|| abstract_restriction::uses_function(_keys, ks_name, function_name)
|| abstract_restriction::uses_function(_entry_keys, ks_name, function_name)
|| abstract_restriction::uses_function(_entry_values, ks_name, function_name);
}
virtual sstring to_string() override {
return sprint("CONTAINS(values=%s, keys=%s, entryKeys=%s, entryValues=%s)",
::to_string(_values), ::to_string(_keys), ::to_string(_entry_keys), ::to_string(_entry_values));
}
virtual bool has_bound(statements::bound b) override {
throw exceptions::unsupported_operation_exception();
}
virtual std::vector<bytes_opt> bounds(statements::bound b, const query_options& options) override {
throw exceptions::unsupported_operation_exception();
}
virtual bool is_inclusive(statements::bound b) override {
throw exceptions::unsupported_operation_exception();
}
#if 0
private List<ByteBuffer> keys(const query_options& options) {
return bindAndGet(keys, options);
}
private List<ByteBuffer> entries(QueryOptions options) throws InvalidRequestException
{
List<ByteBuffer> entryBuffers = new ArrayList<>(_entry_keys.size());
List<ByteBuffer> keyBuffers = bindAndGet(_entry_keys, options);
List<ByteBuffer> valueBuffers = bindAndGet(_entry_values, options);
for (int i = 0; i < _entry_keys.size(); i++)
{
if (valueBuffers.get(i) == null)
throw new InvalidRequestException("Unsupported null value for map-entry equality");
entryBuffers.add(CompositeType.build(keyBuffers.get(i), valueBuffers.get(i)));
}
return entryBuffers;
}
#endif
private:
/**
* Binds the query options to the specified terms and returns the resulting values.
*
* @param terms the terms
* @param options the query options
* @return the value resulting from binding the query options to the specified terms
* @throws invalid_request_exception if a problem occurs while binding the query options
*/
static std::vector<bytes_opt> bind_and_get(std::vector<::shared_ptr<term>> terms, const query_options& options) {
std::vector<bytes_opt> values;
values.reserve(terms.size());
for (auto&& term : terms) {
values.emplace_back(term->bind_and_get(options));
}
return values;
}
};
}
}
<|endoftext|>
|
<commit_before>// @(#)root/auth:$Id$
// Author: G. Ganis, Nov 2006
/*************************************************************************
* Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef WIN32
# include <unistd.h>
#else
# define ssize_t int
# include <io.h>
# include <sys/types.h>
#endif
//////////////////////////////////////////////////////////////////////////
// //
// TAFS //
// //
// Utility class to acquire and handle an AFS tokens. //
// Interface to libTAFS.so. //
// //
//////////////////////////////////////////////////////////////////////////
#include "AFSAuth.h"
#include "TAFS.h"
#include "TError.h"
#include "TPluginManager.h"
#include "TROOT.h"
#include "TString.h"
#include "TSystem.h"
#include "Varargs.h"
#include "Getline.h"
Bool_t TAFS::fgUsePwdDialog = kTRUE;
TPluginHandler *TAFS::fgPasswdDialog = (TPluginHandler *)(-1);
ClassImp(TAFS)
// Hook to the constructor. This is needed to avoid using the plugin manager
// which may create problems in multi-threaded environments.
extern "C" {
TAFS *GetTAFS(const char *f, const char *u, Int_t lf) {
// Create and instance and return it only if valid
TAFS *afs = new TAFS(f, u, lf);
if (afs->Verify())
return afs;
delete afs;
return 0;
}
}
//________________________________________________________________________
TAFS::TAFS(const char *fpw, const char *user, int life)
{
// Constructor: get AFS token for usr using credentials from file 'fpw'.
// If 'usr' is undefined the current user is used.
// If 'fpw' is undefined the caller is prompt for a password.
// Used to test validity
fToken = 0;
// Determine the user
TString usr = (user && strlen(user) > 0) ? user : "";
if (usr.IsNull()) {
UserGroup_t *u = gSystem->GetUserInfo();
if (u) {
usr = (const char *) u->fUser;
delete u;
} else {
Info("TAFS","user undefined");
return;
}
}
// Find credentials
char *pw = 0;
Int_t pwlen = 0;
if (fpw) {
// Reading credentials from file
struct stat st;
if (!stat(fpw, &st)) {
pwlen = st.st_size;
// Open the file for reading
Int_t fd = open(fpw, O_RDONLY);
if (fd > 0) {
pw = new char[pwlen];
if (read(fd, pw, pwlen) != pwlen) {
delete [] pw;
pw = 0;
pwlen = 0;
}
}
}
// Notify failure
if (!pw) {
Info("TAFS","could not read credentials from %s", fpw);
}
}
// Prompt for credentials if not yet found
if (!pw) {
TString prompt = Form("AFS password for %s@%s", usr.Data(), AFSLocalCell());
// Init the dialog box, if needed
if (fgUsePwdDialog) {
if (fgPasswdDialog == (TPluginHandler *)(-1)) {
if (!gROOT->IsBatch()) {
if ((fgPasswdDialog =
gROOT->GetPluginManager()->FindHandler("TGPasswdDialog")))
if (fgPasswdDialog->LoadPlugin() == -1) {
fgPasswdDialog = 0;
Warning("TAFS",
"could not load plugin for the password dialog box");
}
} else
fgPasswdDialog = 0;
}
} else {
fgPasswdDialog = 0;
}
// Get the password now
char buf[128];
pw = buf;
if (fgPasswdDialog) {
// Use graphic dialog
fgPasswdDialog->ExecPlugin(3, prompt.Data(), buf, 128);
// Wait until the user is done
while (gROOT->IsInterrupted())
gSystem->DispatchOneEvent(kFALSE);
} else {
if (isatty(0) != 0 && isatty(1) != 0) {
Gl_config("noecho", 1);
pw = Getline((char *) prompt.Data());
Gl_config("noecho", 0);
} else {
Warning("TAFS", "not tty: cannot prompt for passwd: failure");
pw[0] = 0;
}
}
// Final checks
if (pw[0]) {
if (pw[strlen(pw)-1] == '\n')
pw[strlen(pw) - 1] = 0; // get rid of \n
}
}
// Now get the token
char *emsg;
if (!(fToken = GetAFSToken(usr, pw, pwlen, life, &emsg))) {
Info("TAFS", "token acquisition failed: %s", emsg);
return;
}
// Success
return;
}
//________________________________________________________________________
TAFS::~TAFS()
{
// Destructor
if (fToken)
DeleteAFSToken(fToken);
}
//________________________________________________________________________
Int_t TAFS::Verify()
{
// Return seconds to expiration (negative means expired)
return (fToken ? VerifyAFSToken(fToken) : -1);
}
//________________________________________________________________________
void TAFS::SetUsePwdDialog(Bool_t on)
{
// Switch on/off usage of password dialog box
fgUsePwdDialog = on;
}
<commit_msg>Use TString::Format instead of Form<commit_after>// @(#)root/auth:$Id$
// Author: G. Ganis, Nov 2006
/*************************************************************************
* Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef WIN32
# include <unistd.h>
#else
# define ssize_t int
# include <io.h>
# include <sys/types.h>
#endif
//////////////////////////////////////////////////////////////////////////
// //
// TAFS //
// //
// Utility class to acquire and handle an AFS tokens. //
// Interface to libTAFS.so. //
// //
//////////////////////////////////////////////////////////////////////////
#include "AFSAuth.h"
#include "TAFS.h"
#include "TError.h"
#include "TPluginManager.h"
#include "TROOT.h"
#include "TString.h"
#include "TSystem.h"
#include "Varargs.h"
#include "Getline.h"
Bool_t TAFS::fgUsePwdDialog = kTRUE;
TPluginHandler *TAFS::fgPasswdDialog = (TPluginHandler *)(-1);
ClassImp(TAFS)
// Hook to the constructor. This is needed to avoid using the plugin manager
// which may create problems in multi-threaded environments.
extern "C" {
TAFS *GetTAFS(const char *f, const char *u, Int_t lf) {
// Create and instance and return it only if valid
TAFS *afs = new TAFS(f, u, lf);
if (afs->Verify())
return afs;
delete afs;
return 0;
}
}
//________________________________________________________________________
TAFS::TAFS(const char *fpw, const char *user, int life)
{
// Constructor: get AFS token for usr using credentials from file 'fpw'.
// If 'usr' is undefined the current user is used.
// If 'fpw' is undefined the caller is prompt for a password.
// Used to test validity
fToken = 0;
// Determine the user
TString usr = (user && strlen(user) > 0) ? user : "";
if (usr.IsNull()) {
UserGroup_t *u = gSystem->GetUserInfo();
if (u) {
usr = (const char *) u->fUser;
delete u;
} else {
Info("TAFS","user undefined");
return;
}
}
// Find credentials
char *pw = 0;
Int_t pwlen = 0;
if (fpw) {
// Reading credentials from file
struct stat st;
if (!stat(fpw, &st)) {
pwlen = st.st_size;
// Open the file for reading
Int_t fd = open(fpw, O_RDONLY);
if (fd > 0) {
pw = new char[pwlen];
if (read(fd, pw, pwlen) != pwlen) {
delete [] pw;
pw = 0;
pwlen = 0;
}
}
}
// Notify failure
if (!pw) {
Info("TAFS","could not read credentials from %s", fpw);
}
}
// Prompt for credentials if not yet found
if (!pw) {
TString prompt = TString::Format("AFS password for %s@%s", usr.Data(), AFSLocalCell());
// Init the dialog box, if needed
if (fgUsePwdDialog) {
if (fgPasswdDialog == (TPluginHandler *)(-1)) {
if (!gROOT->IsBatch()) {
if ((fgPasswdDialog =
gROOT->GetPluginManager()->FindHandler("TGPasswdDialog")))
if (fgPasswdDialog->LoadPlugin() == -1) {
fgPasswdDialog = 0;
Warning("TAFS",
"could not load plugin for the password dialog box");
}
} else
fgPasswdDialog = 0;
}
} else {
fgPasswdDialog = 0;
}
// Get the password now
char buf[128];
pw = buf;
if (fgPasswdDialog) {
// Use graphic dialog
fgPasswdDialog->ExecPlugin(3, prompt.Data(), buf, 128);
// Wait until the user is done
while (gROOT->IsInterrupted())
gSystem->DispatchOneEvent(kFALSE);
} else {
if (isatty(0) != 0 && isatty(1) != 0) {
Gl_config("noecho", 1);
pw = Getline((char *) prompt.Data());
Gl_config("noecho", 0);
} else {
Warning("TAFS", "not tty: cannot prompt for passwd: failure");
pw[0] = 0;
}
}
// Final checks
if (pw[0]) {
if (pw[strlen(pw)-1] == '\n')
pw[strlen(pw) - 1] = 0; // get rid of \n
}
}
// Now get the token
char *emsg;
if (!(fToken = GetAFSToken(usr, pw, pwlen, life, &emsg))) {
Info("TAFS", "token acquisition failed: %s", emsg);
return;
}
// Success
return;
}
//________________________________________________________________________
TAFS::~TAFS()
{
// Destructor
if (fToken)
DeleteAFSToken(fToken);
}
//________________________________________________________________________
Int_t TAFS::Verify()
{
// Return seconds to expiration (negative means expired)
return (fToken ? VerifyAFSToken(fToken) : -1);
}
//________________________________________________________________________
void TAFS::SetUsePwdDialog(Bool_t on)
{
// Switch on/off usage of password dialog box
fgUsePwdDialog = on;
}
<|endoftext|>
|
<commit_before>
set<point> pts;
vector<point> up, dn;
void convexHull(){
up.assign(pts.size(),point());
dn.assign(pts.size(),point());
int i = 0, j = 0;
for(set<point>::iterator it = pts.begin(); it != pts.end(); ++it){
while(i > 1 && orientation(up[i-2], up[i-1], *it) <= 0) i--;
while(j > 1 && orientation(dn[j-2], dn[j-1], *it) >= 0) j--;
up[i++] = *it;
dn[j++] = *it;
}
up.resize(i);
dn.resize(j);
}
<commit_msg>deixando mais rapido<commit_after>inline ll orientation(point p, point q, point r){
return (q.second-p.second)*(r.first-p.first) - (q.first-p.first)*(r.second-p.second);
}
set<point> pts;
vector<point> up, dn;
void convexHull(){
up.assign(pts.size(),point());
dn.assign(pts.size(),point());
int i = 0, j = 0;
for(set<point>::iterator it = pts.begin(); it != pts.end(); ++it){
while(i > 1 && orientation(up[i-2], up[i-1], *it) <= 0) i--;
while(j > 1 && orientation(dn[j-2], dn[j-1], *it) >= 0) j--;
up[i++] = *it;
dn[j++] = *it;
}
up.resize(i);
dn.resize(j);
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );
return 0;
}
=============================================================
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
strcat(s1, "Melaniya!");
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );
return 0;
}
===============================================
Подава брой символи "strlen" :
fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) );
===============================================
Добавя "strcat":
strcat(s1, "- From team! :)");
================================================
Сравнява "strcmp":
strcmp("Hello", "Hello") = 0
strcmp(s1, "Hello") = 1
strcmp("Hello", s1) = -1
================================================
Търси съвпадение на символ в стринга "*strchr" и дава съдържание:
fprintf (stdout,"strchr -> %c\n",*strchr("Hello", 'H'));
ако не ползване * се получава НОТА :) превърта;
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
strcat(s1, "- From team! :)");
fprintf (stdout,"strcmp -> %d\n",strcmp("Hello", "Hello"));
fprintf (stdout,"strchr -> %c\n",strchr("Hello", 'H'));
fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) );
return 0;
}
================================================
адрес за обръщане на масив в обратен ред
http://www.introprogramming.info/intro-csharp-book/read-online/glava7-masivi/
================================================
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
int i;
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );
for (i=0; i<strlen(s1);i++)
fprintf (stdout,"[%c]",s1[i]);
return 0;
}
=============================================
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
int i;
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );
for (i=strlen(s1)-1;i>=0;i--)
fprintf (stdout,"%c",s1[i]);
return 0;
}
=====================================
Функция за въвеждане на стойности за масив
float arr_f [50];
for (i=0;i<10;i++) {
fprintf(stdout,"Enter a numer :");
fscan (stdin,"%f", &arr_f[i]);
}
=====================================
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
float arr_f[5], max;
int i;
for(i=0; i<4; i++)
{
fprintf(stdout,"Enter a Number:");
fscanf(stdin,"%f",&arr_f[i]);
}
max = arr_f[0];
for(i=0; i<4; i++)
{
if (max<arr_f[i]) max =arr_f[i];
}
fprintf(stdout,"MAX=%f",max);
return 0;
}
дава резултат
============================================
FILE *f = fopen ("out.txt", "r"/* read */, "w" /*write*/, "a" /*добавяне*/);
<commit_msg>Update exercises_22.11.2014.cpp<commit_after>#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );
return 0;
}
=============================================================
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
strcat(s1, "Melaniya!");
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );
return 0;
}
===============================================
Подава брой символи "strlen" :
fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) );
===============================================
Добавя "strcat":
strcat(s1, "- From team! :)");
================================================
Сравнява "strcmp":
strcmp("Hello", "Hello") = 0
strcmp(s1, "Hello") = 1
strcmp("Hello", s1) = -1
================================================
Търси съвпадение на символ в стринга "*strchr" и дава съдържание:
fprintf (stdout,"strchr -> %c\n",*strchr("Hello", 'H'));
ако не ползване * се получава НОТА :) превърта;
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
strcat(s1, "- From team! :)");
fprintf (stdout,"strcmp -> %d\n",strcmp("Hello", "Hello"));
fprintf (stdout,"strchr -> %c\n",strchr("Hello", 'H'));
fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) );
return 0;
}
================================================
адрес за обръщане на масив в обратен ред
http://www.introprogramming.info/intro-csharp-book/read-online/glava7-masivi/
================================================
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
int i;
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );
for (i=0; i<strlen(s1);i++)
fprintf (stdout,"[%c]",s1[i]);
return 0;
}
=============================================
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
int i;
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );
for (i=strlen(s1)-1;i>=0;i--)
fprintf (stdout,"%c",s1[i]);
return 0;
}
=====================================
Функция за въвеждане на стойности за масив
float arr_f [50];
for (i=0;i<10;i++) {
fprintf(stdout,"Enter a numer :");
fscan (stdin,"%f", &arr_f[i]);
}
=====================================
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
float arr_f[5], max;
int i;
for(i=0; i<4; i++)
{
fprintf(stdout,"Enter a Number:");
fscanf(stdin,"%f",&arr_f[i]);
}
max = arr_f[0];
for(i=0; i<4; i++)
{
if (max<arr_f[i]) max =arr_f[i];
}
fprintf(stdout,"MAX=%f",max);
return 0;
}
дава резултат
============================================
FILE *f = fopen ("out.txt", "r"/* read */, "w" /*write*/, "a" /*добавяне*/);
"C:\\out.txt" - точен адрес Windows
fprintf(f, "Hello!\n");
fclose(f);
============================================
<|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 "ShadowTree.h"
#include <react/renderer/components/root/RootComponentDescriptor.h>
#include <react/renderer/components/view/ViewShadowNode.h>
#include <react/renderer/core/LayoutContext.h>
#include <react/renderer/core/LayoutPrimitives.h>
#include <react/renderer/debug/SystraceSection.h>
#include <react/renderer/mounting/ShadowTreeRevision.h>
#include <react/renderer/mounting/ShadowViewMutation.h>
#include <react/renderer/mounting/TransactionTelemetry.h>
#include "ShadowTreeDelegate.h"
namespace facebook {
namespace react {
using CommitStatus = ShadowTree::CommitStatus;
using CommitMode = ShadowTree::CommitMode;
/*
* Generates (possibly) a new tree where all nodes with non-obsolete `State`
* objects. If all `State` objects in the tree are not obsolete for the moment
* of calling, the function returns `nullptr` (as an indication that no
* additional work is required).
*/
static ShadowNode::Unshared progressState(ShadowNode const &shadowNode) {
auto isStateChanged = false;
auto areChildrenChanged = false;
auto newState = shadowNode.getState();
if (newState) {
newState = newState->getMostRecentStateIfObsolete();
if (newState) {
isStateChanged = true;
}
}
auto newChildren = ShadowNode::ListOfShared{};
if (!shadowNode.getChildren().empty()) {
auto index = size_t{0};
for (auto const &childNode : shadowNode.getChildren()) {
auto newChildNode = progressState(*childNode);
if (newChildNode) {
if (!areChildrenChanged) {
// Making a copy before the first mutation.
newChildren = shadowNode.getChildren();
}
newChildren[index] = newChildNode;
areChildrenChanged = true;
}
index++;
}
}
if (!areChildrenChanged && !isStateChanged) {
return nullptr;
}
return shadowNode.clone({
ShadowNodeFragment::propsPlaceholder(),
areChildrenChanged ? std::make_shared<ShadowNode::ListOfShared const>(
std::move(newChildren))
: ShadowNodeFragment::childrenPlaceholder(),
isStateChanged ? newState : ShadowNodeFragment::statePlaceholder(),
});
}
/*
* An optimized version of the previous function (and relies on it).
* The function uses a given base tree to exclude unchanged (equal) parts
* of the three from the traversing.
*/
static ShadowNode::Unshared progressState(
ShadowNode const &shadowNode,
ShadowNode const &baseShadowNode) {
// The intuition behind the complexity:
// - A very few nodes have associated state, therefore it's mostly reading and
// it only writes when state objects were found obsolete;
// - Most before-after trees are aligned, therefore most tree branches will be
// skipped;
// - If trees are significantly different, any other algorithm will have
// close to linear complexity.
auto isStateChanged = false;
auto areChildrenChanged = false;
auto newState = shadowNode.getState();
if (newState) {
newState = newState->getMostRecentStateIfObsolete();
if (newState) {
isStateChanged = true;
}
}
auto &children = shadowNode.getChildren();
auto &baseChildren = baseShadowNode.getChildren();
auto newChildren = ShadowNode::ListOfShared{};
auto childrenSize = children.size();
auto baseChildrenSize = baseChildren.size();
auto index = size_t{0};
// Stage 1: Aligned part.
for (index = 0; index < childrenSize && index < baseChildrenSize; index++) {
const auto &childNode = *children.at(index);
const auto &baseChildNode = *baseChildren.at(index);
if (&childNode == &baseChildNode) {
// Nodes are identical, skipping.
continue;
}
if (!ShadowNode::sameFamily(childNode, baseChildNode)) {
// Totally different nodes, updating is impossible.
break;
}
auto newChildNode = progressState(childNode, baseChildNode);
if (newChildNode) {
if (!areChildrenChanged) {
// Making a copy before the first mutation.
newChildren = children;
}
newChildren[index] = newChildNode;
areChildrenChanged = true;
}
}
// Stage 2: Misaligned part.
for (; index < childrenSize; index++) {
auto newChildNode = progressState(*children.at(index));
if (newChildNode) {
if (!areChildrenChanged) {
// Making a copy before the first mutation.
newChildren = children;
}
newChildren[index] = newChildNode;
areChildrenChanged = true;
}
}
if (!areChildrenChanged && !isStateChanged) {
return nullptr;
}
return shadowNode.clone({
ShadowNodeFragment::propsPlaceholder(),
areChildrenChanged ? std::make_shared<ShadowNode::ListOfShared const>(
std::move(newChildren))
: ShadowNodeFragment::childrenPlaceholder(),
isStateChanged ? newState : ShadowNodeFragment::statePlaceholder(),
});
}
static void updateMountedFlag(
const SharedShadowNodeList &oldChildren,
const SharedShadowNodeList &newChildren) {
// This is a simplified version of Diffing algorithm that only updates
// `mounted` flag on `ShadowNode`s. The algorithm sets "mounted" flag before
// "unmounted" to allow `ShadowNode` detect a situation where the node was
// remounted.
if (&oldChildren == &newChildren) {
// Lists are identical, nothing to do.
return;
}
if (oldChildren.empty() && newChildren.empty()) {
// Both lists are empty, nothing to do.
return;
}
int index;
// Stage 1: Mount and unmount "updated" children.
for (index = 0; index < oldChildren.size() && index < newChildren.size();
index++) {
const auto &oldChild = oldChildren[index];
const auto &newChild = newChildren[index];
if (oldChild == newChild) {
// Nodes are identical, skipping the subtree.
continue;
}
if (!ShadowNode::sameFamily(*oldChild, *newChild)) {
// Totally different nodes, updating is impossible.
break;
}
newChild->setMounted(true);
oldChild->setMounted(false);
updateMountedFlag(oldChild->getChildren(), newChild->getChildren());
}
int lastIndexAfterFirstStage = index;
// State 2: Mount new children.
for (index = lastIndexAfterFirstStage; index < newChildren.size(); index++) {
const auto &newChild = newChildren[index];
newChild->setMounted(true);
updateMountedFlag({}, newChild->getChildren());
}
// State 3: Unmount old children.
for (index = lastIndexAfterFirstStage; index < oldChildren.size(); index++) {
const auto &oldChild = oldChildren[index];
oldChild->setMounted(false);
updateMountedFlag(oldChild->getChildren(), {});
}
}
ShadowTree::ShadowTree(
SurfaceId surfaceId,
LayoutConstraints const &layoutConstraints,
LayoutContext const &layoutContext,
ShadowTreeDelegate const &delegate)
: surfaceId_(surfaceId), delegate_(delegate) {
const auto noopEventEmitter = std::make_shared<const ViewEventEmitter>(
nullptr, -1, std::shared_ptr<const EventDispatcher>());
static auto globalRootComponentDescriptor =
std::make_unique<RootComponentDescriptor const>(
ComponentDescriptorParameters{
EventDispatcher::Shared{}, nullptr, nullptr});
const auto props = std::make_shared<const RootProps>(
*RootShadowNode::defaultSharedProps(), layoutConstraints, layoutContext);
auto const fragment =
ShadowNodeFamilyFragment{surfaceId, surfaceId, noopEventEmitter};
auto family = globalRootComponentDescriptor->createFamily(fragment, nullptr);
auto rootShadowNode = std::static_pointer_cast<const RootShadowNode>(
globalRootComponentDescriptor->createShadowNode(
ShadowNodeFragment{
/* .props = */ props,
},
family));
currentRevision_ = ShadowTreeRevision{
rootShadowNode, ShadowTreeRevision::Number{0}, TransactionTelemetry{}};
mountingCoordinator_ =
std::make_shared<MountingCoordinator const>(currentRevision_);
}
ShadowTree::~ShadowTree() {
mountingCoordinator_->revoke();
}
Tag ShadowTree::getSurfaceId() const {
return surfaceId_;
}
void ShadowTree::setCommitMode(CommitMode commitMode) const {
auto revision = ShadowTreeRevision{};
{
std::unique_lock<better::shared_mutex> lock(commitMutex_);
if (commitMode_ == commitMode) {
return;
}
commitMode_ = commitMode;
revision = currentRevision_;
}
if (commitMode == CommitMode::Normal) {
mount(revision);
}
}
CommitMode ShadowTree::getCommitMode() const {
std::shared_lock<better::shared_mutex> lock(commitMutex_);
return commitMode_;
}
MountingCoordinator::Shared ShadowTree::getMountingCoordinator() const {
return mountingCoordinator_;
}
CommitStatus ShadowTree::commit(
ShadowTreeCommitTransaction transaction,
CommitOptions commitOptions) const {
SystraceSection s("ShadowTree::commit");
int attempts = 0;
while (true) {
attempts++;
auto status = tryCommit(transaction, commitOptions);
if (status != CommitStatus::Failed) {
return status;
}
// After multiple attempts, we failed to commit the transaction.
// Something internally went terribly wrong.
assert(attempts < 1024);
}
}
CommitStatus ShadowTree::tryCommit(
ShadowTreeCommitTransaction transaction,
CommitOptions commitOptions) const {
SystraceSection s("ShadowTree::tryCommit");
auto telemetry = TransactionTelemetry{};
telemetry.willCommit();
CommitMode commitMode;
auto oldRevision = ShadowTreeRevision{};
auto newRevision = ShadowTreeRevision{};
{
// Reading `currentRevision_` in shared manner.
std::shared_lock<better::shared_mutex> lock(commitMutex_);
commitMode = commitMode_;
oldRevision = currentRevision_;
}
auto oldRootShadowNode = oldRevision.rootShadowNode;
auto newRootShadowNode = transaction(*oldRevision.rootShadowNode);
if (!newRootShadowNode ||
(commitOptions.shouldCancel && commitOptions.shouldCancel())) {
return CommitStatus::Cancelled;
}
if (commitOptions.enableStateReconciliation) {
auto updatedNewRootShadowNode =
progressState(*newRootShadowNode, *oldRevision.rootShadowNode);
if (updatedNewRootShadowNode) {
newRootShadowNode =
std::static_pointer_cast<RootShadowNode>(updatedNewRootShadowNode);
}
}
// Layout nodes.
std::vector<LayoutableShadowNode const *> affectedLayoutableNodes{};
affectedLayoutableNodes.reserve(1024);
telemetry.willLayout();
telemetry.setAsThreadLocal();
newRootShadowNode->layoutIfNeeded(&affectedLayoutableNodes);
telemetry.unsetAsThreadLocal();
telemetry.didLayout();
// Seal the shadow node so it can no longer be mutated
newRootShadowNode->sealRecursive();
{
// Updating `currentRevision_` in unique manner if it hasn't changed.
std::unique_lock<better::shared_mutex> lock(commitMutex_);
if (currentRevision_.number != oldRevision.number) {
return CommitStatus::Failed;
}
auto newRevisionNumber = oldRevision.number + 1;
newRootShadowNode = delegate_.shadowTreeWillCommit(
*this, oldRootShadowNode, newRootShadowNode);
if (!newRootShadowNode) {
return CommitStatus::Cancelled;
}
{
std::lock_guard<std::mutex> dispatchLock(EventEmitter::DispatchMutex());
updateMountedFlag(
currentRevision_.rootShadowNode->getChildren(),
newRootShadowNode->getChildren());
}
telemetry.didCommit();
telemetry.setRevisionNumber(newRevisionNumber);
newRevision =
ShadowTreeRevision{newRootShadowNode, newRevisionNumber, telemetry};
currentRevision_ = newRevision;
}
if (commitOptions.shouldCancel && commitOptions.shouldCancel()) {
return CommitStatus::Cancelled;
}
emitLayoutEvents(affectedLayoutableNodes);
if (commitMode == CommitMode::Normal) {
mount(newRevision);
}
return CommitStatus::Succeeded;
}
ShadowTreeRevision ShadowTree::getCurrentRevision() const {
std::shared_lock<better::shared_mutex> lock(commitMutex_);
return currentRevision_;
}
void ShadowTree::mount(ShadowTreeRevision const &revision) const {
mountingCoordinator_->push(revision);
delegate_.shadowTreeDidFinishTransaction(*this, mountingCoordinator_);
}
void ShadowTree::commitEmptyTree() const {
commit(
[](RootShadowNode const &oldRootShadowNode) -> RootShadowNode::Unshared {
return std::make_shared<RootShadowNode>(
oldRootShadowNode,
ShadowNodeFragment{
/* .props = */ ShadowNodeFragment::propsPlaceholder(),
/* .children = */ ShadowNode::emptySharedShadowNodeSharedList(),
});
});
}
void ShadowTree::emitLayoutEvents(
std::vector<LayoutableShadowNode const *> &affectedLayoutableNodes) const {
SystraceSection s("ShadowTree::emitLayoutEvents");
for (auto const *layoutableNode : affectedLayoutableNodes) {
// Only instances of `ViewShadowNode` (and subclasses) are supported.
auto const &viewShadowNode =
static_cast<ViewShadowNode const &>(*layoutableNode);
auto const &viewEventEmitter = static_cast<ViewEventEmitter const &>(
*viewShadowNode.getEventEmitter());
// Checking if the `onLayout` event was requested for the particular Shadow
// Node.
auto const &viewProps =
static_cast<ViewProps const &>(*viewShadowNode.getProps());
if (!viewProps.onLayout) {
continue;
}
viewEventEmitter.onLayout(layoutableNode->getLayoutMetrics());
}
}
void ShadowTree::notifyDelegatesOfUpdates() const {
delegate_.shadowTreeDidFinishTransaction(*this, mountingCoordinator_);
}
} // namespace react
} // namespace facebook
<commit_msg>Call updateMountedFlag in ShadowTree::tryCommit only if commit will go to native<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 "ShadowTree.h"
#include <react/renderer/components/root/RootComponentDescriptor.h>
#include <react/renderer/components/view/ViewShadowNode.h>
#include <react/renderer/core/LayoutContext.h>
#include <react/renderer/core/LayoutPrimitives.h>
#include <react/renderer/debug/SystraceSection.h>
#include <react/renderer/mounting/ShadowTreeRevision.h>
#include <react/renderer/mounting/ShadowViewMutation.h>
#include <react/renderer/mounting/TransactionTelemetry.h>
#include "ShadowTreeDelegate.h"
namespace facebook {
namespace react {
using CommitStatus = ShadowTree::CommitStatus;
using CommitMode = ShadowTree::CommitMode;
/*
* Generates (possibly) a new tree where all nodes with non-obsolete `State`
* objects. If all `State` objects in the tree are not obsolete for the moment
* of calling, the function returns `nullptr` (as an indication that no
* additional work is required).
*/
static ShadowNode::Unshared progressState(ShadowNode const &shadowNode) {
auto isStateChanged = false;
auto areChildrenChanged = false;
auto newState = shadowNode.getState();
if (newState) {
newState = newState->getMostRecentStateIfObsolete();
if (newState) {
isStateChanged = true;
}
}
auto newChildren = ShadowNode::ListOfShared{};
if (!shadowNode.getChildren().empty()) {
auto index = size_t{0};
for (auto const &childNode : shadowNode.getChildren()) {
auto newChildNode = progressState(*childNode);
if (newChildNode) {
if (!areChildrenChanged) {
// Making a copy before the first mutation.
newChildren = shadowNode.getChildren();
}
newChildren[index] = newChildNode;
areChildrenChanged = true;
}
index++;
}
}
if (!areChildrenChanged && !isStateChanged) {
return nullptr;
}
return shadowNode.clone({
ShadowNodeFragment::propsPlaceholder(),
areChildrenChanged ? std::make_shared<ShadowNode::ListOfShared const>(
std::move(newChildren))
: ShadowNodeFragment::childrenPlaceholder(),
isStateChanged ? newState : ShadowNodeFragment::statePlaceholder(),
});
}
/*
* An optimized version of the previous function (and relies on it).
* The function uses a given base tree to exclude unchanged (equal) parts
* of the three from the traversing.
*/
static ShadowNode::Unshared progressState(
ShadowNode const &shadowNode,
ShadowNode const &baseShadowNode) {
// The intuition behind the complexity:
// - A very few nodes have associated state, therefore it's mostly reading and
// it only writes when state objects were found obsolete;
// - Most before-after trees are aligned, therefore most tree branches will be
// skipped;
// - If trees are significantly different, any other algorithm will have
// close to linear complexity.
auto isStateChanged = false;
auto areChildrenChanged = false;
auto newState = shadowNode.getState();
if (newState) {
newState = newState->getMostRecentStateIfObsolete();
if (newState) {
isStateChanged = true;
}
}
auto &children = shadowNode.getChildren();
auto &baseChildren = baseShadowNode.getChildren();
auto newChildren = ShadowNode::ListOfShared{};
auto childrenSize = children.size();
auto baseChildrenSize = baseChildren.size();
auto index = size_t{0};
// Stage 1: Aligned part.
for (index = 0; index < childrenSize && index < baseChildrenSize; index++) {
const auto &childNode = *children.at(index);
const auto &baseChildNode = *baseChildren.at(index);
if (&childNode == &baseChildNode) {
// Nodes are identical, skipping.
continue;
}
if (!ShadowNode::sameFamily(childNode, baseChildNode)) {
// Totally different nodes, updating is impossible.
break;
}
auto newChildNode = progressState(childNode, baseChildNode);
if (newChildNode) {
if (!areChildrenChanged) {
// Making a copy before the first mutation.
newChildren = children;
}
newChildren[index] = newChildNode;
areChildrenChanged = true;
}
}
// Stage 2: Misaligned part.
for (; index < childrenSize; index++) {
auto newChildNode = progressState(*children.at(index));
if (newChildNode) {
if (!areChildrenChanged) {
// Making a copy before the first mutation.
newChildren = children;
}
newChildren[index] = newChildNode;
areChildrenChanged = true;
}
}
if (!areChildrenChanged && !isStateChanged) {
return nullptr;
}
return shadowNode.clone({
ShadowNodeFragment::propsPlaceholder(),
areChildrenChanged ? std::make_shared<ShadowNode::ListOfShared const>(
std::move(newChildren))
: ShadowNodeFragment::childrenPlaceholder(),
isStateChanged ? newState : ShadowNodeFragment::statePlaceholder(),
});
}
static void updateMountedFlag(
const SharedShadowNodeList &oldChildren,
const SharedShadowNodeList &newChildren) {
// This is a simplified version of Diffing algorithm that only updates
// `mounted` flag on `ShadowNode`s. The algorithm sets "mounted" flag before
// "unmounted" to allow `ShadowNode` detect a situation where the node was
// remounted.
if (&oldChildren == &newChildren) {
// Lists are identical, nothing to do.
return;
}
if (oldChildren.empty() && newChildren.empty()) {
// Both lists are empty, nothing to do.
return;
}
int index;
// Stage 1: Mount and unmount "updated" children.
for (index = 0; index < oldChildren.size() && index < newChildren.size();
index++) {
const auto &oldChild = oldChildren[index];
const auto &newChild = newChildren[index];
if (oldChild == newChild) {
// Nodes are identical, skipping the subtree.
continue;
}
if (!ShadowNode::sameFamily(*oldChild, *newChild)) {
// Totally different nodes, updating is impossible.
break;
}
newChild->setMounted(true);
oldChild->setMounted(false);
updateMountedFlag(oldChild->getChildren(), newChild->getChildren());
}
int lastIndexAfterFirstStage = index;
// State 2: Mount new children.
for (index = lastIndexAfterFirstStage; index < newChildren.size(); index++) {
const auto &newChild = newChildren[index];
newChild->setMounted(true);
updateMountedFlag({}, newChild->getChildren());
}
// State 3: Unmount old children.
for (index = lastIndexAfterFirstStage; index < oldChildren.size(); index++) {
const auto &oldChild = oldChildren[index];
oldChild->setMounted(false);
updateMountedFlag(oldChild->getChildren(), {});
}
}
ShadowTree::ShadowTree(
SurfaceId surfaceId,
LayoutConstraints const &layoutConstraints,
LayoutContext const &layoutContext,
ShadowTreeDelegate const &delegate)
: surfaceId_(surfaceId), delegate_(delegate) {
const auto noopEventEmitter = std::make_shared<const ViewEventEmitter>(
nullptr, -1, std::shared_ptr<const EventDispatcher>());
static auto globalRootComponentDescriptor =
std::make_unique<RootComponentDescriptor const>(
ComponentDescriptorParameters{
EventDispatcher::Shared{}, nullptr, nullptr});
const auto props = std::make_shared<const RootProps>(
*RootShadowNode::defaultSharedProps(), layoutConstraints, layoutContext);
auto const fragment =
ShadowNodeFamilyFragment{surfaceId, surfaceId, noopEventEmitter};
auto family = globalRootComponentDescriptor->createFamily(fragment, nullptr);
auto rootShadowNode = std::static_pointer_cast<const RootShadowNode>(
globalRootComponentDescriptor->createShadowNode(
ShadowNodeFragment{
/* .props = */ props,
},
family));
currentRevision_ = ShadowTreeRevision{
rootShadowNode, ShadowTreeRevision::Number{0}, TransactionTelemetry{}};
mountingCoordinator_ =
std::make_shared<MountingCoordinator const>(currentRevision_);
}
ShadowTree::~ShadowTree() {
mountingCoordinator_->revoke();
}
Tag ShadowTree::getSurfaceId() const {
return surfaceId_;
}
void ShadowTree::setCommitMode(CommitMode commitMode) const {
auto revision = ShadowTreeRevision{};
{
std::unique_lock<better::shared_mutex> lock(commitMutex_);
if (commitMode_ == commitMode) {
return;
}
commitMode_ = commitMode;
revision = currentRevision_;
}
if (commitMode == CommitMode::Normal) {
mount(revision);
}
}
CommitMode ShadowTree::getCommitMode() const {
std::shared_lock<better::shared_mutex> lock(commitMutex_);
return commitMode_;
}
MountingCoordinator::Shared ShadowTree::getMountingCoordinator() const {
return mountingCoordinator_;
}
CommitStatus ShadowTree::commit(
ShadowTreeCommitTransaction transaction,
CommitOptions commitOptions) const {
SystraceSection s("ShadowTree::commit");
int attempts = 0;
while (true) {
attempts++;
auto status = tryCommit(transaction, commitOptions);
if (status != CommitStatus::Failed) {
return status;
}
// After multiple attempts, we failed to commit the transaction.
// Something internally went terribly wrong.
assert(attempts < 1024);
}
}
CommitStatus ShadowTree::tryCommit(
ShadowTreeCommitTransaction transaction,
CommitOptions commitOptions) const {
SystraceSection s("ShadowTree::tryCommit");
auto telemetry = TransactionTelemetry{};
telemetry.willCommit();
CommitMode commitMode;
auto oldRevision = ShadowTreeRevision{};
auto newRevision = ShadowTreeRevision{};
{
// Reading `currentRevision_` in shared manner.
std::shared_lock<better::shared_mutex> lock(commitMutex_);
commitMode = commitMode_;
oldRevision = currentRevision_;
}
auto oldRootShadowNode = oldRevision.rootShadowNode;
auto newRootShadowNode = transaction(*oldRevision.rootShadowNode);
if (!newRootShadowNode ||
(commitOptions.shouldCancel && commitOptions.shouldCancel())) {
return CommitStatus::Cancelled;
}
if (commitOptions.enableStateReconciliation) {
auto updatedNewRootShadowNode =
progressState(*newRootShadowNode, *oldRevision.rootShadowNode);
if (updatedNewRootShadowNode) {
newRootShadowNode =
std::static_pointer_cast<RootShadowNode>(updatedNewRootShadowNode);
}
}
// Layout nodes.
std::vector<LayoutableShadowNode const *> affectedLayoutableNodes{};
affectedLayoutableNodes.reserve(1024);
telemetry.willLayout();
telemetry.setAsThreadLocal();
newRootShadowNode->layoutIfNeeded(&affectedLayoutableNodes);
telemetry.unsetAsThreadLocal();
telemetry.didLayout();
// Seal the shadow node so it can no longer be mutated
newRootShadowNode->sealRecursive();
{
// Updating `currentRevision_` in unique manner if it hasn't changed.
std::unique_lock<better::shared_mutex> lock(commitMutex_);
if (currentRevision_.number != oldRevision.number) {
return CommitStatus::Failed;
}
auto newRevisionNumber = oldRevision.number + 1;
newRootShadowNode = delegate_.shadowTreeWillCommit(
*this, oldRootShadowNode, newRootShadowNode);
if (!newRootShadowNode ||
(commitOptions.shouldCancel && commitOptions.shouldCancel())) {
return CommitStatus::Cancelled;
}
{
std::lock_guard<std::mutex> dispatchLock(EventEmitter::DispatchMutex());
updateMountedFlag(
currentRevision_.rootShadowNode->getChildren(),
newRootShadowNode->getChildren());
}
telemetry.didCommit();
telemetry.setRevisionNumber(newRevisionNumber);
newRevision =
ShadowTreeRevision{newRootShadowNode, newRevisionNumber, telemetry};
currentRevision_ = newRevision;
}
emitLayoutEvents(affectedLayoutableNodes);
if (commitMode == CommitMode::Normal) {
mount(newRevision);
}
return CommitStatus::Succeeded;
}
ShadowTreeRevision ShadowTree::getCurrentRevision() const {
std::shared_lock<better::shared_mutex> lock(commitMutex_);
return currentRevision_;
}
void ShadowTree::mount(ShadowTreeRevision const &revision) const {
mountingCoordinator_->push(revision);
delegate_.shadowTreeDidFinishTransaction(*this, mountingCoordinator_);
}
void ShadowTree::commitEmptyTree() const {
commit(
[](RootShadowNode const &oldRootShadowNode) -> RootShadowNode::Unshared {
return std::make_shared<RootShadowNode>(
oldRootShadowNode,
ShadowNodeFragment{
/* .props = */ ShadowNodeFragment::propsPlaceholder(),
/* .children = */ ShadowNode::emptySharedShadowNodeSharedList(),
});
});
}
void ShadowTree::emitLayoutEvents(
std::vector<LayoutableShadowNode const *> &affectedLayoutableNodes) const {
SystraceSection s("ShadowTree::emitLayoutEvents");
for (auto const *layoutableNode : affectedLayoutableNodes) {
// Only instances of `ViewShadowNode` (and subclasses) are supported.
auto const &viewShadowNode =
static_cast<ViewShadowNode const &>(*layoutableNode);
auto const &viewEventEmitter = static_cast<ViewEventEmitter const &>(
*viewShadowNode.getEventEmitter());
// Checking if the `onLayout` event was requested for the particular Shadow
// Node.
auto const &viewProps =
static_cast<ViewProps const &>(*viewShadowNode.getProps());
if (!viewProps.onLayout) {
continue;
}
viewEventEmitter.onLayout(layoutableNode->getLayoutMetrics());
}
}
void ShadowTree::notifyDelegatesOfUpdates() const {
delegate_.shadowTreeDidFinishTransaction(*this, mountingCoordinator_);
}
} // namespace react
} // namespace facebook
<|endoftext|>
|
<commit_before>/*
* libjingle
* Copyright 2004--2005, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 "xmppclient.h"
#include "xmpptask.h"
#include "talk/xmpp/xmppconstants.h"
#include "talk/base/sigslot.h"
#include "talk/xmpp/saslplainmechanism.h"
#include "talk/xmpp/saslhandler.h"
#include "talk/xmpp/prexmppauth.h"
#include "talk/base/scoped_ptr.h"
#include "talk/xmpp/plainsaslhandler.h"
namespace buzz {
talk_base::Task* XmppClient::GetParent(int code) {
if (code == XMPP_CLIENT_TASK_CODE)
return this;
else
return talk_base::Task::GetParent(code);
}
class XmppClient::Private :
public sigslot::has_slots<>,
public XmppSessionHandler,
public XmppOutputHandler {
public:
Private(XmppClient * client) :
client_(client),
socket_(NULL),
engine_(NULL),
proxy_port_(0),
pre_engine_error_(XmppEngine::ERROR_NONE),
pre_engine_subcode_(0),
signal_closed_(false),
allow_plain_(false) {}
// the owner
XmppClient * const client_;
// the two main objects
scoped_ptr<AsyncSocket> socket_;
scoped_ptr<XmppEngine> engine_;
scoped_ptr<PreXmppAuth> pre_auth_;
scoped_ptr<SaslHandler> sasl_handler_;
talk_base::CryptString pass_;
std::string auth_cookie_;
talk_base::SocketAddress server_;
std::string proxy_host_;
int proxy_port_;
XmppEngine::Error pre_engine_error_;
int pre_engine_subcode_;
CaptchaChallenge captcha_challenge_;
bool signal_closed_;
bool allow_plain_;
// implementations of interfaces
void OnStateChange(int state);
void WriteOutput(const char * bytes, size_t len);
void StartTls(const std::string & domainname);
void CloseConnection();
// slots for socket signals
void OnSocketConnected();
void OnSocketRead();
void OnSocketClosed();
};
XmppReturnStatus
XmppClient::Connect(const XmppClientSettings & settings,
const std::string & lang,
AsyncSocket * socket,
PreXmppAuth * pre_auth,
SaslHandler * sasl_handler) {
if (socket == NULL)
return XMPP_RETURN_BADARGUMENT;
if (d_->socket_.get() != NULL)
return XMPP_RETURN_BADSTATE;
d_->socket_.reset(socket);
d_->socket_->SignalConnected.connect(d_.get(), &Private::OnSocketConnected);
d_->socket_->SignalRead.connect(d_.get(), &Private::OnSocketRead);
d_->socket_->SignalClosed.connect(d_.get(), &Private::OnSocketClosed);
d_->engine_.reset(XmppEngine::Create());
d_->engine_->SetSessionHandler(d_.get());
d_->engine_->SetOutputHandler(d_.get());
if (!settings.resource().empty()) {
d_->engine_->SetRequestedResource(settings.resource());
}
d_->engine_->SetUseTls(settings.use_tls());
//
// The talk.google.com server expects you to use "gmail.com" in the
// stream, and expects the domain certificate to be "gmail.com" as well.
// For all other servers, we leave the strings empty, which causes
// the jid's domain to be used. "foo@example.com" -> stream to="example.com"
// tls certificate for "example.com"
//
// This is only true when using Gaia auth, so let's say if there's no preauth,
// we should use the actual server name
if ((settings.server().IPAsString() == buzz::STR_TALK_GOOGLE_COM ||
settings.server().IPAsString() == buzz::STR_TALKX_L_GOOGLE_COM) &&
pre_auth != NULL) {
d_->engine_->SetTlsServer(buzz::STR_GMAIL_COM, buzz::STR_GMAIL_COM);
}
// Set language
d_->engine_->SetLanguage(lang);
d_->engine_->SetUser(buzz::Jid(settings.user(), settings.host(), STR_EMPTY));
d_->pass_ = settings.pass();
d_->auth_cookie_ = settings.auth_cookie();
d_->server_ = settings.server();
d_->proxy_host_ = settings.proxy_host();
d_->proxy_port_ = settings.proxy_port();
d_->allow_plain_ = settings.allow_plain();
d_->pre_auth_.reset(pre_auth);
d_->sasl_handler_.reset(sasl_handler);
return XMPP_RETURN_OK;
}
XmppEngine::State
XmppClient::GetState() {
if (d_->engine_.get() == NULL)
return XmppEngine::STATE_NONE;
return d_->engine_->GetState();
}
XmppEngine::Error
XmppClient::GetError(int *subcode) {
if (subcode) {
*subcode = 0;
}
if (d_->engine_.get() == NULL)
return XmppEngine::ERROR_NONE;
if (d_->pre_engine_error_ != XmppEngine::ERROR_NONE) {
if (subcode) {
*subcode = d_->pre_engine_subcode_;
}
return d_->pre_engine_error_;
}
return d_->engine_->GetError(subcode);
}
const XmlElement *
XmppClient::GetStreamError() {
if (d_->engine_.get() == NULL) {
return NULL;
}
return d_->engine_->GetStreamError();
}
CaptchaChallenge XmppClient::GetCaptchaChallenge() {
if (d_->engine_.get() == NULL)
return CaptchaChallenge();
return d_->captcha_challenge_;
}
std::string
XmppClient::GetAuthCookie() {
if (d_->engine_.get() == NULL)
return "";
return d_->auth_cookie_;
}
static void
ForgetPassword(std::string & to_erase) {
size_t len = to_erase.size();
for (size_t i = 0; i < len; i++) {
// get rid of characters
to_erase[i] = 'x';
}
// get rid of length
to_erase.erase();
}
int
XmppClient::ProcessStart() {
if (d_->sasl_handler_.get()) {
d_->engine_->SetSaslHandler(d_->sasl_handler_.release());
}
else {
d_->engine_->SetSaslHandler(new PlainSaslHandler(
d_->engine_->GetUser(), d_->pass_, d_->allow_plain_));
}
if (d_->pre_auth_.get()) {
d_->pre_auth_->SignalAuthDone.connect(this, &XmppClient::OnAuthDone);
d_->pre_auth_->StartPreXmppAuth(
d_->engine_->GetUser(), d_->server_, d_->pass_, d_->auth_cookie_);
d_->pass_.Clear(); // done with this;
return STATE_PRE_XMPP_LOGIN;
}
else {
d_->pass_.Clear(); // done with this;
return STATE_START_XMPP_LOGIN;
}
}
void
XmppClient::OnAuthDone() {
Wake();
}
int
XmppClient::ProcessCookieLogin() {
// Don't know how this could happen, but crash reports show it as NULL
if (!d_->pre_auth_.get()) {
d_->pre_engine_error_ = XmppEngine::ERROR_AUTH;
EnsureClosed();
return STATE_ERROR;
}
// Wait until pre authentication is done is done
if (!d_->pre_auth_->IsAuthDone())
return STATE_BLOCKED;
if (!d_->pre_auth_->IsAuthorized()) {
// maybe split out a case when gaia is down?
if (d_->pre_auth_->HadError()) {
d_->pre_engine_error_ = XmppEngine::ERROR_AUTH;
d_->pre_engine_subcode_ = d_->pre_auth_->GetError();
}
else {
d_->pre_engine_error_ = XmppEngine::ERROR_UNAUTHORIZED;
d_->pre_engine_subcode_ = 0;
d_->captcha_challenge_ = d_->pre_auth_->GetCaptchaChallenge();
}
d_->pre_auth_.reset(NULL); // done with this
EnsureClosed();
return STATE_ERROR;
}
// Save auth cookie as a result
d_->auth_cookie_ = d_->pre_auth_->GetAuthCookie();
return STATE_START_XMPP_LOGIN;
}
int
XmppClient::ProcessStartXmppLogin() {
// Done with pre-connect tasks - connect!
if (!d_->socket_->Connect(d_->server_)) {
d_->pre_engine_error_ = XmppEngine::ERROR_SOCKET;
d_->pre_engine_subcode_ = d_->socket_->GetError();
EnsureClosed();
return STATE_ERROR;
}
return STATE_RESPONSE;
}
int
XmppClient::ProcessResponse() {
// Hang around while we are connected.
if (!delivering_signal_ && (d_->engine_.get() == NULL ||
d_->engine_->GetState() == XmppEngine::STATE_CLOSED))
return STATE_DONE;
return STATE_BLOCKED;
}
XmppReturnStatus
XmppClient::Disconnect() {
if (d_->socket_.get() == NULL)
return XMPP_RETURN_BADSTATE;
d_->engine_->Disconnect();
return XMPP_RETURN_OK;
}
XmppClient::XmppClient(Task * parent)
: Task(parent),
delivering_signal_(false),
valid_(false) {
d_.reset(new Private(this));
valid_ = true;
}
XmppClient::~XmppClient() {
valid_ = false;
}
const Jid &
XmppClient::jid() {
return d_->engine_->FullJid();
}
std::string
XmppClient::NextId() {
return d_->engine_->NextId();
}
XmppReturnStatus
XmppClient::SendStanza(const XmlElement * stanza) {
return d_->engine_->SendStanza(stanza);
}
XmppReturnStatus
XmppClient::SendStanzaError(const XmlElement * old_stanza, XmppStanzaError xse, const std::string & message) {
return d_->engine_->SendStanzaError(old_stanza, xse, message);
}
XmppReturnStatus
XmppClient::SendRaw(const std::string & text) {
return d_->engine_->SendRaw(text);
}
XmppEngine*
XmppClient::engine() {
return d_->engine_.get();
}
void
XmppClient::Private::OnSocketConnected() {
engine_->Connect();
}
void
XmppClient::Private::OnSocketRead() {
char bytes[4096];
size_t bytes_read;
for (;;) {
if (!socket_->Read(bytes, sizeof(bytes), &bytes_read)) {
// TODO: deal with error information
return;
}
if (bytes_read == 0)
return;
//#if !defined(NDEBUG)
client_->SignalLogInput(bytes, bytes_read);
//#endif
engine_->HandleInput(bytes, bytes_read);
}
}
void
XmppClient::Private::OnSocketClosed() {
int code = socket_->GetError();
engine_->ConnectionClosed(code);
}
void
XmppClient::Private::OnStateChange(int state) {
if (state == XmppEngine::STATE_CLOSED) {
client_->EnsureClosed();
}
else {
client_->SignalStateChange((XmppEngine::State)state);
}
client_->Wake();
}
void
XmppClient::Private::WriteOutput(const char * bytes, size_t len) {
//#if !defined(NDEBUG)
client_->SignalLogOutput(bytes, len);
//#endif
socket_->Write(bytes, len);
// TODO: deal with error information
}
void
XmppClient::Private::StartTls(const std::string & domain) {
#if defined(FEATURE_ENABLE_SSL)
socket_->StartTls(domain);
#endif
}
void
XmppClient::Private::CloseConnection() {
socket_->Close();
}
void
XmppClient::AddXmppTask(XmppTask * task, XmppEngine::HandlerLevel level) {
d_->engine_->AddStanzaHandler(task, level);
}
void
XmppClient::RemoveXmppTask(XmppTask * task) {
d_->engine_->RemoveStanzaHandler(task);
}
void
XmppClient::EnsureClosed() {
if (!d_->signal_closed_) {
d_->signal_closed_ = true;
delivering_signal_ = true;
SignalStateChange(XmppEngine::STATE_CLOSED);
delivering_signal_ = false;
}
}
}
<commit_msg>Quick fix for a problem introduced by 41865 which causes sync notifications to break for non-gmail.com accounts.<commit_after>/*
* libjingle
* Copyright 2004--2005, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 "xmppclient.h"
#include "xmpptask.h"
#include "talk/xmpp/xmppconstants.h"
#include "talk/base/sigslot.h"
#include "talk/xmpp/saslplainmechanism.h"
#include "talk/xmpp/saslhandler.h"
#include "talk/xmpp/prexmppauth.h"
#include "talk/base/scoped_ptr.h"
#include "talk/xmpp/plainsaslhandler.h"
namespace buzz {
talk_base::Task* XmppClient::GetParent(int code) {
if (code == XMPP_CLIENT_TASK_CODE)
return this;
else
return talk_base::Task::GetParent(code);
}
class XmppClient::Private :
public sigslot::has_slots<>,
public XmppSessionHandler,
public XmppOutputHandler {
public:
Private(XmppClient * client) :
client_(client),
socket_(NULL),
engine_(NULL),
proxy_port_(0),
pre_engine_error_(XmppEngine::ERROR_NONE),
pre_engine_subcode_(0),
signal_closed_(false),
allow_plain_(false) {}
// the owner
XmppClient * const client_;
// the two main objects
scoped_ptr<AsyncSocket> socket_;
scoped_ptr<XmppEngine> engine_;
scoped_ptr<PreXmppAuth> pre_auth_;
scoped_ptr<SaslHandler> sasl_handler_;
talk_base::CryptString pass_;
std::string auth_cookie_;
talk_base::SocketAddress server_;
std::string proxy_host_;
int proxy_port_;
XmppEngine::Error pre_engine_error_;
int pre_engine_subcode_;
CaptchaChallenge captcha_challenge_;
bool signal_closed_;
bool allow_plain_;
// implementations of interfaces
void OnStateChange(int state);
void WriteOutput(const char * bytes, size_t len);
void StartTls(const std::string & domainname);
void CloseConnection();
// slots for socket signals
void OnSocketConnected();
void OnSocketRead();
void OnSocketClosed();
};
XmppReturnStatus
XmppClient::Connect(const XmppClientSettings & settings,
const std::string & lang,
AsyncSocket * socket,
PreXmppAuth * pre_auth,
SaslHandler * sasl_handler) {
if (socket == NULL)
return XMPP_RETURN_BADARGUMENT;
if (d_->socket_.get() != NULL)
return XMPP_RETURN_BADSTATE;
d_->socket_.reset(socket);
d_->socket_->SignalConnected.connect(d_.get(), &Private::OnSocketConnected);
d_->socket_->SignalRead.connect(d_.get(), &Private::OnSocketRead);
d_->socket_->SignalClosed.connect(d_.get(), &Private::OnSocketClosed);
d_->engine_.reset(XmppEngine::Create());
d_->engine_->SetSessionHandler(d_.get());
d_->engine_->SetOutputHandler(d_.get());
if (!settings.resource().empty()) {
d_->engine_->SetRequestedResource(settings.resource());
}
d_->engine_->SetUseTls(settings.use_tls());
//
// The talk.google.com server expects you to use "gmail.com" in the
// stream, and expects the domain certificate to be "gmail.com" as well.
// For all other servers, we leave the strings empty, which causes
// the jid's domain to be used. "foo@example.com" -> stream to="example.com"
// tls certificate for "example.com"
//
// This is only true when using Gaia auth, so let's say if there's
// no sasl_handler, we should use the actual server name
// TODO(akalin): Do this in a less hackish way.
if ((settings.server().IPAsString() == buzz::STR_TALK_GOOGLE_COM ||
settings.server().IPAsString() == buzz::STR_TALKX_L_GOOGLE_COM) &&
sasl_handler != NULL) {
d_->engine_->SetTlsServer(buzz::STR_GMAIL_COM, buzz::STR_GMAIL_COM);
}
// Set language
d_->engine_->SetLanguage(lang);
d_->engine_->SetUser(buzz::Jid(settings.user(), settings.host(), STR_EMPTY));
d_->pass_ = settings.pass();
d_->auth_cookie_ = settings.auth_cookie();
d_->server_ = settings.server();
d_->proxy_host_ = settings.proxy_host();
d_->proxy_port_ = settings.proxy_port();
d_->allow_plain_ = settings.allow_plain();
d_->pre_auth_.reset(pre_auth);
d_->sasl_handler_.reset(sasl_handler);
return XMPP_RETURN_OK;
}
XmppEngine::State
XmppClient::GetState() {
if (d_->engine_.get() == NULL)
return XmppEngine::STATE_NONE;
return d_->engine_->GetState();
}
XmppEngine::Error
XmppClient::GetError(int *subcode) {
if (subcode) {
*subcode = 0;
}
if (d_->engine_.get() == NULL)
return XmppEngine::ERROR_NONE;
if (d_->pre_engine_error_ != XmppEngine::ERROR_NONE) {
if (subcode) {
*subcode = d_->pre_engine_subcode_;
}
return d_->pre_engine_error_;
}
return d_->engine_->GetError(subcode);
}
const XmlElement *
XmppClient::GetStreamError() {
if (d_->engine_.get() == NULL) {
return NULL;
}
return d_->engine_->GetStreamError();
}
CaptchaChallenge XmppClient::GetCaptchaChallenge() {
if (d_->engine_.get() == NULL)
return CaptchaChallenge();
return d_->captcha_challenge_;
}
std::string
XmppClient::GetAuthCookie() {
if (d_->engine_.get() == NULL)
return "";
return d_->auth_cookie_;
}
static void
ForgetPassword(std::string & to_erase) {
size_t len = to_erase.size();
for (size_t i = 0; i < len; i++) {
// get rid of characters
to_erase[i] = 'x';
}
// get rid of length
to_erase.erase();
}
int
XmppClient::ProcessStart() {
if (d_->sasl_handler_.get()) {
d_->engine_->SetSaslHandler(d_->sasl_handler_.release());
}
else {
d_->engine_->SetSaslHandler(new PlainSaslHandler(
d_->engine_->GetUser(), d_->pass_, d_->allow_plain_));
}
if (d_->pre_auth_.get()) {
d_->pre_auth_->SignalAuthDone.connect(this, &XmppClient::OnAuthDone);
d_->pre_auth_->StartPreXmppAuth(
d_->engine_->GetUser(), d_->server_, d_->pass_, d_->auth_cookie_);
d_->pass_.Clear(); // done with this;
return STATE_PRE_XMPP_LOGIN;
}
else {
d_->pass_.Clear(); // done with this;
return STATE_START_XMPP_LOGIN;
}
}
void
XmppClient::OnAuthDone() {
Wake();
}
int
XmppClient::ProcessCookieLogin() {
// Don't know how this could happen, but crash reports show it as NULL
if (!d_->pre_auth_.get()) {
d_->pre_engine_error_ = XmppEngine::ERROR_AUTH;
EnsureClosed();
return STATE_ERROR;
}
// Wait until pre authentication is done is done
if (!d_->pre_auth_->IsAuthDone())
return STATE_BLOCKED;
if (!d_->pre_auth_->IsAuthorized()) {
// maybe split out a case when gaia is down?
if (d_->pre_auth_->HadError()) {
d_->pre_engine_error_ = XmppEngine::ERROR_AUTH;
d_->pre_engine_subcode_ = d_->pre_auth_->GetError();
}
else {
d_->pre_engine_error_ = XmppEngine::ERROR_UNAUTHORIZED;
d_->pre_engine_subcode_ = 0;
d_->captcha_challenge_ = d_->pre_auth_->GetCaptchaChallenge();
}
d_->pre_auth_.reset(NULL); // done with this
EnsureClosed();
return STATE_ERROR;
}
// Save auth cookie as a result
d_->auth_cookie_ = d_->pre_auth_->GetAuthCookie();
return STATE_START_XMPP_LOGIN;
}
int
XmppClient::ProcessStartXmppLogin() {
// Done with pre-connect tasks - connect!
if (!d_->socket_->Connect(d_->server_)) {
d_->pre_engine_error_ = XmppEngine::ERROR_SOCKET;
d_->pre_engine_subcode_ = d_->socket_->GetError();
EnsureClosed();
return STATE_ERROR;
}
return STATE_RESPONSE;
}
int
XmppClient::ProcessResponse() {
// Hang around while we are connected.
if (!delivering_signal_ && (d_->engine_.get() == NULL ||
d_->engine_->GetState() == XmppEngine::STATE_CLOSED))
return STATE_DONE;
return STATE_BLOCKED;
}
XmppReturnStatus
XmppClient::Disconnect() {
if (d_->socket_.get() == NULL)
return XMPP_RETURN_BADSTATE;
d_->engine_->Disconnect();
return XMPP_RETURN_OK;
}
XmppClient::XmppClient(Task * parent)
: Task(parent),
delivering_signal_(false),
valid_(false) {
d_.reset(new Private(this));
valid_ = true;
}
XmppClient::~XmppClient() {
valid_ = false;
}
const Jid &
XmppClient::jid() {
return d_->engine_->FullJid();
}
std::string
XmppClient::NextId() {
return d_->engine_->NextId();
}
XmppReturnStatus
XmppClient::SendStanza(const XmlElement * stanza) {
return d_->engine_->SendStanza(stanza);
}
XmppReturnStatus
XmppClient::SendStanzaError(const XmlElement * old_stanza, XmppStanzaError xse, const std::string & message) {
return d_->engine_->SendStanzaError(old_stanza, xse, message);
}
XmppReturnStatus
XmppClient::SendRaw(const std::string & text) {
return d_->engine_->SendRaw(text);
}
XmppEngine*
XmppClient::engine() {
return d_->engine_.get();
}
void
XmppClient::Private::OnSocketConnected() {
engine_->Connect();
}
void
XmppClient::Private::OnSocketRead() {
char bytes[4096];
size_t bytes_read;
for (;;) {
if (!socket_->Read(bytes, sizeof(bytes), &bytes_read)) {
// TODO: deal with error information
return;
}
if (bytes_read == 0)
return;
//#if !defined(NDEBUG)
client_->SignalLogInput(bytes, bytes_read);
//#endif
engine_->HandleInput(bytes, bytes_read);
}
}
void
XmppClient::Private::OnSocketClosed() {
int code = socket_->GetError();
engine_->ConnectionClosed(code);
}
void
XmppClient::Private::OnStateChange(int state) {
if (state == XmppEngine::STATE_CLOSED) {
client_->EnsureClosed();
}
else {
client_->SignalStateChange((XmppEngine::State)state);
}
client_->Wake();
}
void
XmppClient::Private::WriteOutput(const char * bytes, size_t len) {
//#if !defined(NDEBUG)
client_->SignalLogOutput(bytes, len);
//#endif
socket_->Write(bytes, len);
// TODO: deal with error information
}
void
XmppClient::Private::StartTls(const std::string & domain) {
#if defined(FEATURE_ENABLE_SSL)
socket_->StartTls(domain);
#endif
}
void
XmppClient::Private::CloseConnection() {
socket_->Close();
}
void
XmppClient::AddXmppTask(XmppTask * task, XmppEngine::HandlerLevel level) {
d_->engine_->AddStanzaHandler(task, level);
}
void
XmppClient::RemoveXmppTask(XmppTask * task) {
d_->engine_->RemoveStanzaHandler(task);
}
void
XmppClient::EnsureClosed() {
if (!d_->signal_closed_) {
d_->signal_closed_ = true;
delivering_signal_ = true;
SignalStateChange(XmppEngine::STATE_CLOSED);
delivering_signal_ = false;
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/http/http_auth.h"
#include <algorithm>
#include "base/basictypes.h"
#include "base/string_util.h"
#include "net/base/net_errors.h"
#include "net/http/http_auth_handler_basic.h"
#include "net/http/http_auth_handler_digest.h"
#include "net/http/http_auth_handler_negotiate.h"
#include "net/http/http_auth_handler_ntlm.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
namespace net {
// static
void HttpAuth::ChooseBestChallenge(
HttpAuthHandlerFactory* http_auth_handler_factory,
const HttpResponseHeaders* headers,
Target target,
const GURL& origin,
const std::set<std::string>& disabled_schemes,
const BoundNetLog& net_log,
scoped_ptr<HttpAuthHandler>* handler) {
DCHECK(http_auth_handler_factory);
// A connection-based authentication scheme must continue to use the
// existing handler object in |*handler|.
if (handler->get() && (*handler)->is_connection_based()) {
const std::string header_name = GetChallengeHeaderName(target);
std::string challenge;
void* iter = NULL;
while (headers->EnumerateHeader(&iter, header_name, &challenge)) {
ChallengeTokenizer props(challenge.begin(), challenge.end());
if (LowerCaseEqualsASCII(props.scheme(), (*handler)->scheme().c_str()) &&
(*handler)->InitFromChallenge(&props, target, origin, net_log))
return;
}
}
// Choose the challenge whose authentication handler gives the maximum score.
scoped_ptr<HttpAuthHandler> best;
const std::string header_name = GetChallengeHeaderName(target);
std::string cur_challenge;
void* iter = NULL;
while (headers->EnumerateHeader(&iter, header_name, &cur_challenge)) {
scoped_ptr<HttpAuthHandler> cur;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
cur_challenge, target, origin, net_log, &cur);
if (rv != OK) {
LOG(WARNING) << "Unable to create AuthHandler. Status: "
<< ErrorToString(rv) << " Challenge: " << cur_challenge;
continue;
}
if (cur.get() && (!best.get() || best->score() < cur->score())) {
if (disabled_schemes.find(cur->scheme()) == disabled_schemes.end())
best.swap(cur);
}
}
handler->swap(best);
}
void HttpAuth::ChallengeTokenizer::Init(std::string::const_iterator begin,
std::string::const_iterator end) {
// The first space-separated token is the auth-scheme.
// NOTE: we are more permissive than RFC 2617 which says auth-scheme
// is separated by 1*SP.
StringTokenizer tok(begin, end, HTTP_LWS);
if (!tok.GetNext()) {
valid_ = false;
return;
}
// Save the scheme's position.
scheme_begin_ = tok.token_begin();
scheme_end_ = tok.token_end();
// Everything past scheme_end_ is a (comma separated) value list.
props_ = HttpUtil::ValuesIterator(scheme_end_, end, ',');
}
// We expect properties to be formatted as one of:
// name="value"
// name=value
// name=
// Due to buggy implementations found in some embedded devices, we also
// accept values with missing close quotemark (http://crbug.com/39836):
// name="value
bool HttpAuth::ChallengeTokenizer::GetNext() {
if (!props_.GetNext())
return false;
// Set the value as everything. Next we will split out the name.
value_begin_ = props_.value_begin();
value_end_ = props_.value_end();
name_begin_ = name_end_ = value_end_;
if (expect_base64_token_) {
expect_base64_token_ = false;
// Strip off any padding.
// (See https://bugzilla.mozilla.org/show_bug.cgi?id=230351.)
//
// Our base64 decoder requires that the length be a multiple of 4.
int encoded_length = value_end_ - value_begin_;
while (encoded_length > 0 && encoded_length % 4 != 0 &&
value_begin_[encoded_length - 1] == '=') {
--encoded_length;
--value_end_;
}
return true;
}
// Scan for the equals sign.
std::string::const_iterator equals = std::find(value_begin_, value_end_, '=');
if (equals == value_end_ || equals == value_begin_)
return valid_ = false; // Malformed
// Verify that the equals sign we found wasn't inside of quote marks.
for (std::string::const_iterator it = value_begin_; it != equals; ++it) {
if (HttpUtil::IsQuote(*it))
return valid_ = false; // Malformed
}
name_begin_ = value_begin_;
name_end_ = equals;
value_begin_ = equals + 1;
value_is_quoted_ = false;
if (value_begin_ != value_end_ && HttpUtil::IsQuote(*value_begin_)) {
// Trim surrounding quotemarks off the value
if (*value_begin_ != *(value_end_ - 1) || value_begin_ + 1 == value_end_)
value_begin_ = equals + 2; // Gracefully recover from mismatching quotes.
else
value_is_quoted_ = true;
}
return true;
}
// If value() has quotemarks, unquote it.
std::string HttpAuth::ChallengeTokenizer::unquoted_value() const {
return HttpUtil::Unquote(value_begin_, value_end_);
}
// static
std::string HttpAuth::GetChallengeHeaderName(Target target) {
switch (target) {
case AUTH_PROXY:
return "Proxy-Authenticate";
case AUTH_SERVER:
return "WWW-Authenticate";
default:
NOTREACHED();
return "";
}
}
// static
std::string HttpAuth::GetAuthorizationHeaderName(Target target) {
switch (target) {
case AUTH_PROXY:
return "Proxy-Authorization";
case AUTH_SERVER:
return "Authorization";
default:
NOTREACHED();
return "";
}
}
// static
std::string HttpAuth::GetAuthTargetString(
HttpAuth::Target target) {
return target == HttpAuth::AUTH_PROXY ? "proxy" : "server";
}
} // namespace net
<commit_msg>Fix for Proxy server authentication without credentials available.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/http/http_auth.h"
#include <algorithm>
#include "base/basictypes.h"
#include "base/string_util.h"
#include "net/base/net_errors.h"
#include "net/http/http_auth_handler_basic.h"
#include "net/http/http_auth_handler_digest.h"
#include "net/http/http_auth_handler_negotiate.h"
#include "net/http/http_auth_handler_ntlm.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
namespace net {
// static
void HttpAuth::ChooseBestChallenge(
HttpAuthHandlerFactory* http_auth_handler_factory,
const HttpResponseHeaders* headers,
Target target,
const GURL& origin,
const std::set<std::string>& disabled_schemes,
const BoundNetLog& net_log,
scoped_ptr<HttpAuthHandler>* handler) {
DCHECK(http_auth_handler_factory);
// A connection-based authentication scheme must continue to use the
// existing handler object in |*handler|.
if (handler->get() && (*handler)->is_connection_based() &&
(disabled_schemes.find((*handler)->scheme()) == disabled_schemes.end())) {
const std::string header_name = GetChallengeHeaderName(target);
std::string challenge;
void* iter = NULL;
while (headers->EnumerateHeader(&iter, header_name, &challenge)) {
ChallengeTokenizer props(challenge.begin(), challenge.end());
if (LowerCaseEqualsASCII(props.scheme(), (*handler)->scheme().c_str()) &&
(*handler)->InitFromChallenge(&props, target, origin, net_log))
return;
}
}
// Choose the challenge whose authentication handler gives the maximum score.
scoped_ptr<HttpAuthHandler> best;
const std::string header_name = GetChallengeHeaderName(target);
std::string cur_challenge;
void* iter = NULL;
while (headers->EnumerateHeader(&iter, header_name, &cur_challenge)) {
scoped_ptr<HttpAuthHandler> cur;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
cur_challenge, target, origin, net_log, &cur);
if (rv != OK) {
LOG(WARNING) << "Unable to create AuthHandler. Status: "
<< ErrorToString(rv) << " Challenge: " << cur_challenge;
continue;
}
if (cur.get() && (!best.get() || best->score() < cur->score()) &&
(disabled_schemes.find(cur->scheme()) == disabled_schemes.end()))
best.swap(cur);
}
handler->swap(best);
}
void HttpAuth::ChallengeTokenizer::Init(std::string::const_iterator begin,
std::string::const_iterator end) {
// The first space-separated token is the auth-scheme.
// NOTE: we are more permissive than RFC 2617 which says auth-scheme
// is separated by 1*SP.
StringTokenizer tok(begin, end, HTTP_LWS);
if (!tok.GetNext()) {
valid_ = false;
return;
}
// Save the scheme's position.
scheme_begin_ = tok.token_begin();
scheme_end_ = tok.token_end();
// Everything past scheme_end_ is a (comma separated) value list.
props_ = HttpUtil::ValuesIterator(scheme_end_, end, ',');
}
// We expect properties to be formatted as one of:
// name="value"
// name=value
// name=
// Due to buggy implementations found in some embedded devices, we also
// accept values with missing close quotemark (http://crbug.com/39836):
// name="value
bool HttpAuth::ChallengeTokenizer::GetNext() {
if (!props_.GetNext())
return false;
// Set the value as everything. Next we will split out the name.
value_begin_ = props_.value_begin();
value_end_ = props_.value_end();
name_begin_ = name_end_ = value_end_;
if (expect_base64_token_) {
expect_base64_token_ = false;
// Strip off any padding.
// (See https://bugzilla.mozilla.org/show_bug.cgi?id=230351.)
//
// Our base64 decoder requires that the length be a multiple of 4.
int encoded_length = value_end_ - value_begin_;
while (encoded_length > 0 && encoded_length % 4 != 0 &&
value_begin_[encoded_length - 1] == '=') {
--encoded_length;
--value_end_;
}
return true;
}
// Scan for the equals sign.
std::string::const_iterator equals = std::find(value_begin_, value_end_, '=');
if (equals == value_end_ || equals == value_begin_)
return valid_ = false; // Malformed
// Verify that the equals sign we found wasn't inside of quote marks.
for (std::string::const_iterator it = value_begin_; it != equals; ++it) {
if (HttpUtil::IsQuote(*it))
return valid_ = false; // Malformed
}
name_begin_ = value_begin_;
name_end_ = equals;
value_begin_ = equals + 1;
value_is_quoted_ = false;
if (value_begin_ != value_end_ && HttpUtil::IsQuote(*value_begin_)) {
// Trim surrounding quotemarks off the value
if (*value_begin_ != *(value_end_ - 1) || value_begin_ + 1 == value_end_)
value_begin_ = equals + 2; // Gracefully recover from mismatching quotes.
else
value_is_quoted_ = true;
}
return true;
}
// If value() has quotemarks, unquote it.
std::string HttpAuth::ChallengeTokenizer::unquoted_value() const {
return HttpUtil::Unquote(value_begin_, value_end_);
}
// static
std::string HttpAuth::GetChallengeHeaderName(Target target) {
switch (target) {
case AUTH_PROXY:
return "Proxy-Authenticate";
case AUTH_SERVER:
return "WWW-Authenticate";
default:
NOTREACHED();
return "";
}
}
// static
std::string HttpAuth::GetAuthorizationHeaderName(Target target) {
switch (target) {
case AUTH_PROXY:
return "Proxy-Authorization";
case AUTH_SERVER:
return "Authorization";
default:
NOTREACHED();
return "";
}
}
// static
std::string HttpAuth::GetAuthTargetString(
HttpAuth::Target target) {
return target == HttpAuth::AUTH_PROXY ? "proxy" : "server";
}
} // namespace net
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XALAN_RESULTNAMESPACESSTACK_HEADER_GUARD)
#define XALAN_RESULTNAMESPACESSTACK_HEADER_GUARD
// Base include file. Must be first.
#include <XSLT/XSLTDefinitions.hpp>
#include <vector>
#include <XalanDOM/XalanDOMString.hpp>
#include <XPath/XalanQName.hpp>
class XALAN_XSLT_EXPORT ResultNamespacesStack
{
public:
#if defined(XALAN_NO_NAMESPACES)
typedef vector<bool> BoolVectorType;
#else
typedef std::vector<bool> BoolVectorType;
#endif
typedef XalanQName::NamespaceVectorType NamespaceVectorType;
typedef XalanQName::NamespacesStackType NamespacesStackType;
typedef NamespacesStackType::size_type size_type;
explicit
ResultNamespacesStack();
~ResultNamespacesStack();
void
addDeclaration(
const XalanDOMString& thePrefix,
const XalanDOMString& theNamespaceURI);
void
pushContext();
void
popContext();
const XalanDOMString*
getNamespaceForPrefix(const XalanDOMString& thePrefix) const;
const XalanDOMString*
getPrefixForNamespace(const XalanDOMString& theNamespaceURI) const;
/**
* See if the prefix has been mapped to a namespace in the current
* context, without looking down the stack of namespaces.
*/
bool
prefixIsPresentLocal(const XalanDOMString& thePrefix);
void
clear();
size_type
size() const
{
return m_resultNamespaces.size();
}
private:
// not implemented
ResultNamespacesStack(const ResultNamespacesStack&);
bool
operator==(const ResultNamespacesStack&) const;
ResultNamespacesStack&
operator=(const ResultNamespacesStack&);
enum { eDefaultCreateNewContextStackSize = 100 };
/**
* A stack to keep track of the result tree namespaces.
*/
NamespacesStackType m_resultNamespaces;
BoolVectorType m_createNewContextStack;
};
#endif // XALAN_RESULTNAMESPACESSTACK_HEADER_GUARD
<commit_msg>Added empty() member function.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XALAN_RESULTNAMESPACESSTACK_HEADER_GUARD)
#define XALAN_RESULTNAMESPACESSTACK_HEADER_GUARD
// Base include file. Must be first.
#include <XSLT/XSLTDefinitions.hpp>
#include <vector>
#include <XalanDOM/XalanDOMString.hpp>
#include <XPath/XalanQName.hpp>
class XALAN_XSLT_EXPORT ResultNamespacesStack
{
public:
#if defined(XALAN_NO_NAMESPACES)
typedef vector<bool> BoolVectorType;
#else
typedef std::vector<bool> BoolVectorType;
#endif
typedef XalanQName::NamespaceVectorType NamespaceVectorType;
typedef XalanQName::NamespacesStackType NamespacesStackType;
typedef NamespacesStackType::size_type size_type;
explicit
ResultNamespacesStack();
~ResultNamespacesStack();
void
addDeclaration(
const XalanDOMString& thePrefix,
const XalanDOMString& theNamespaceURI);
void
pushContext();
void
popContext();
const XalanDOMString*
getNamespaceForPrefix(const XalanDOMString& thePrefix) const;
const XalanDOMString*
getPrefixForNamespace(const XalanDOMString& theNamespaceURI) const;
/**
* See if the prefix has been mapped to a namespace in the current
* context, without looking down the stack of namespaces.
*/
bool
prefixIsPresentLocal(const XalanDOMString& thePrefix);
void
clear();
size_type
size() const
{
return m_resultNamespaces.size();
}
bool
empty() const
{
return m_resultNamespaces.empty();
}
private:
// not implemented
ResultNamespacesStack(const ResultNamespacesStack&);
bool
operator==(const ResultNamespacesStack&) const;
ResultNamespacesStack&
operator=(const ResultNamespacesStack&);
enum { eDefaultCreateNewContextStackSize = 100 };
/**
* A stack to keep track of the result tree namespaces.
*/
NamespacesStackType m_resultNamespaces;
BoolVectorType m_createNewContextStack;
};
#endif // XALAN_RESULTNAMESPACESSTACK_HEADER_GUARD
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#include "b_string.hpp"
#include "draft_journal.hpp"
#include "draft_journal_impl.hpp"
#include "draft_journal_reader.hpp"
#include "entry.hpp"
#include "phatbooks_database_connection.hpp"
#include "phatbooks_persistent_object.hpp"
#include "proto_journal.hpp"
#include <sqloxx/handle.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <ostream>
#include <string>
using boost::lexical_cast;
using boost::shared_ptr;
using std::endl;
using std::ostream;
using std::string;
using std::vector;
using sqloxx::Handle;
namespace phatbooks
{
void
DraftJournal::setup_tables(PhatbooksDatabaseConnection& dbc)
{
DraftJournalImpl::setup_tables(dbc);
return;
}
DraftJournal::DraftJournal
( PhatbooksDatabaseConnection& p_database_connection
):
PhatbooksPersistentObject(p_database_connection)
{
}
DraftJournal::DraftJournal
( PhatbooksDatabaseConnection& p_database_connection,
Id p_id
):
PhatbooksPersistentObject(p_database_connection, p_id)
{
}
DraftJournal
DraftJournal::create_unchecked
( PhatbooksDatabaseConnection& p_database_connection,
Id p_id
)
{
return DraftJournal
( Handle<DraftJournalImpl>::create_unchecked
( p_database_connection,
p_id
)
);
}
bool
DraftJournal::exists
( PhatbooksDatabaseConnection& p_database_connection,
BString const& p_name
)
{
return DraftJournalImpl::exists
( p_database_connection,
p_name
);
}
bool
DraftJournal::no_user_draft_journals_saved
( PhatbooksDatabaseConnection& p_database_connection
)
{
return DraftJournalImpl::no_user_draft_journals_saved
( p_database_connection
);
}
void
DraftJournal::set_name(BString const& p_name)
{
impl().set_name(p_name);
return;
}
void
DraftJournal::push_repeater(Repeater& repeater)
{
impl().push_repeater(repeater);
return;
}
bool
DraftJournal::has_repeaters() const
{
return impl().has_repeaters();
}
void
DraftJournal::clear_repeaters()
{
impl().clear_repeaters();
return;
}
void
DraftJournal::do_clear_entries()
{
impl().clear_entries();
return;
}
void
DraftJournal::do_set_whether_actual(bool p_is_actual)
{
impl().set_whether_actual(p_is_actual);
return;
}
void
DraftJournal::do_set_comment(BString const& p_comment)
{
impl().set_comment(p_comment);
return;
}
void
DraftJournal::do_push_entry(Entry& entry)
{
impl().push_entry(entry);
return;
}
void
DraftJournal::do_remove_entry(Entry& entry)
{
impl().remove_entry(entry);
return;
}
bool
DraftJournal::do_get_whether_actual() const
{
return impl().is_actual();
}
BString
DraftJournal::do_get_comment() const
{
return impl().comment();
}
BString
DraftJournal::name() const
{
return impl().name();
}
vector<Entry> const&
DraftJournal::do_get_entries() const
{
return impl().entries();
}
vector<Repeater> const&
DraftJournal::repeaters() const
{
return impl().repeaters();
}
BString
DraftJournal::repeater_description() const
{
return impl().repeater_description();
}
DraftJournal::DraftJournal
( sqloxx::Handle<DraftJournalImpl> const& p_handle
):
PhatbooksPersistentObject(p_handle)
{
}
void
DraftJournal::mimic(ProtoJournal const& rhs)
{
impl().mimic(rhs);
return;
}
void
DraftJournal::mimic(DraftJournal const& rhs)
{
impl().mimic(rhs.impl());
return;
}
void
DraftJournal::do_output(ostream& os) const
{
os << "DRAFT JOURNAL";
if (has_id())
{
os << " ID " << lexical_cast<string>(id());
}
os << " NAME " << name() << " ";
PersistentJournal::do_output(os);
os << endl << repeater_description() << endl;
return;
}
} // namespace phatbooks
<commit_msg>Fixed glitch in spacing of output to stream of DraftJournal.<commit_after>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#include "b_string.hpp"
#include "draft_journal.hpp"
#include "draft_journal_impl.hpp"
#include "draft_journal_reader.hpp"
#include "entry.hpp"
#include "phatbooks_database_connection.hpp"
#include "phatbooks_persistent_object.hpp"
#include "proto_journal.hpp"
#include <sqloxx/handle.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <ostream>
#include <string>
using boost::lexical_cast;
using boost::shared_ptr;
using std::endl;
using std::ostream;
using std::string;
using std::vector;
using sqloxx::Handle;
namespace phatbooks
{
void
DraftJournal::setup_tables(PhatbooksDatabaseConnection& dbc)
{
DraftJournalImpl::setup_tables(dbc);
return;
}
DraftJournal::DraftJournal
( PhatbooksDatabaseConnection& p_database_connection
):
PhatbooksPersistentObject(p_database_connection)
{
}
DraftJournal::DraftJournal
( PhatbooksDatabaseConnection& p_database_connection,
Id p_id
):
PhatbooksPersistentObject(p_database_connection, p_id)
{
}
DraftJournal
DraftJournal::create_unchecked
( PhatbooksDatabaseConnection& p_database_connection,
Id p_id
)
{
return DraftJournal
( Handle<DraftJournalImpl>::create_unchecked
( p_database_connection,
p_id
)
);
}
bool
DraftJournal::exists
( PhatbooksDatabaseConnection& p_database_connection,
BString const& p_name
)
{
return DraftJournalImpl::exists
( p_database_connection,
p_name
);
}
bool
DraftJournal::no_user_draft_journals_saved
( PhatbooksDatabaseConnection& p_database_connection
)
{
return DraftJournalImpl::no_user_draft_journals_saved
( p_database_connection
);
}
void
DraftJournal::set_name(BString const& p_name)
{
impl().set_name(p_name);
return;
}
void
DraftJournal::push_repeater(Repeater& repeater)
{
impl().push_repeater(repeater);
return;
}
bool
DraftJournal::has_repeaters() const
{
return impl().has_repeaters();
}
void
DraftJournal::clear_repeaters()
{
impl().clear_repeaters();
return;
}
void
DraftJournal::do_clear_entries()
{
impl().clear_entries();
return;
}
void
DraftJournal::do_set_whether_actual(bool p_is_actual)
{
impl().set_whether_actual(p_is_actual);
return;
}
void
DraftJournal::do_set_comment(BString const& p_comment)
{
impl().set_comment(p_comment);
return;
}
void
DraftJournal::do_push_entry(Entry& entry)
{
impl().push_entry(entry);
return;
}
void
DraftJournal::do_remove_entry(Entry& entry)
{
impl().remove_entry(entry);
return;
}
bool
DraftJournal::do_get_whether_actual() const
{
return impl().is_actual();
}
BString
DraftJournal::do_get_comment() const
{
return impl().comment();
}
BString
DraftJournal::name() const
{
return impl().name();
}
vector<Entry> const&
DraftJournal::do_get_entries() const
{
return impl().entries();
}
vector<Repeater> const&
DraftJournal::repeaters() const
{
return impl().repeaters();
}
BString
DraftJournal::repeater_description() const
{
return impl().repeater_description();
}
DraftJournal::DraftJournal
( sqloxx::Handle<DraftJournalImpl> const& p_handle
):
PhatbooksPersistentObject(p_handle)
{
}
void
DraftJournal::mimic(ProtoJournal const& rhs)
{
impl().mimic(rhs);
return;
}
void
DraftJournal::mimic(DraftJournal const& rhs)
{
impl().mimic(rhs.impl());
return;
}
void
DraftJournal::do_output(ostream& os) const
{
os << "DRAFT JOURNAL ";
if (has_id())
{
os << "ID " << lexical_cast<string>(id()) << " ";
}
os << "NAME " << name() << " ";
PersistentJournal::do_output(os);
os << endl << repeater_description() << endl;
return;
}
} // namespace phatbooks
<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "gin/arguments.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/per_isolate_data.h"
#include "gin/public/isolate_holder.h"
#include "gin/test/v8_test.h"
#include "gin/try_catch.h"
#include "gin/wrappable.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gin {
class BaseClass {
public:
BaseClass() : value_(23) {}
virtual ~BaseClass() {}
private:
int value_;
DISALLOW_COPY_AND_ASSIGN(BaseClass);
};
class MyObject : public BaseClass,
public Wrappable<MyObject> {
public:
static WrapperInfo kWrapperInfo;
static gin::Handle<MyObject> Create(v8::Isolate* isolate) {
return CreateHandle(isolate, new MyObject());
}
int value() const { return value_; }
void set_value(int value) { value_ = value; }
protected:
MyObject() : value_(0) {}
virtual ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) OVERRIDE;
virtual ~MyObject() {}
private:
int value_;
};
class MyObjectSubclass : public MyObject {
public:
static gin::Handle<MyObjectSubclass> Create(v8::Isolate* isolate) {
return CreateHandle(isolate, new MyObjectSubclass());
}
void SayHello(const std::string& name) {
result = std::string("Hello, ") + name;
}
std::string result;
private:
virtual ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) OVERRIDE {
return MyObject::GetObjectTemplateBuilder(isolate)
.SetMethod("sayHello", &MyObjectSubclass::SayHello);
}
MyObjectSubclass() {
}
virtual ~MyObjectSubclass() {
}
};
class MyCallableObject : public Wrappable<MyCallableObject> {
public:
static WrapperInfo kWrapperInfo;
static gin::Handle<MyCallableObject> Create(v8::Isolate* isolate) {
return CreateHandle(isolate, new MyCallableObject());
}
int result() { return result_; }
private:
virtual ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) OVERRIDE {
return Wrappable<MyCallableObject>::GetObjectTemplateBuilder(isolate)
.SetCallAsFunctionHandler(&MyCallableObject::Call);
}
MyCallableObject() : result_(0) {
}
virtual ~MyCallableObject() {
}
void Call(int val) {
result_ = val;
}
int result_;
};
class MyObject2 : public Wrappable<MyObject2> {
public:
static WrapperInfo kWrapperInfo;
};
class MyObjectBlink : public Wrappable<MyObjectBlink> {
public:
static WrapperInfo kWrapperInfo;
};
WrapperInfo MyObject::kWrapperInfo = { kEmbedderNativeGin };
ObjectTemplateBuilder MyObject::GetObjectTemplateBuilder(v8::Isolate* isolate) {
return Wrappable<MyObject>::GetObjectTemplateBuilder(isolate)
.SetProperty("value", &MyObject::value, &MyObject::set_value);
}
WrapperInfo MyCallableObject::kWrapperInfo = { kEmbedderNativeGin };
WrapperInfo MyObject2::kWrapperInfo = { kEmbedderNativeGin };
WrapperInfo MyObjectBlink::kWrapperInfo = { kEmbedderNativeGin };
typedef V8Test WrappableTest;
TEST_F(WrappableTest, WrapAndUnwrap) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
Handle<MyObject> obj = MyObject::Create(isolate);
v8::Handle<v8::Value> wrapper = ConvertToV8(isolate, obj.get());
EXPECT_FALSE(wrapper.IsEmpty());
MyObject* unwrapped = NULL;
EXPECT_TRUE(ConvertFromV8(isolate, wrapper, &unwrapped));
EXPECT_EQ(obj.get(), unwrapped);
}
TEST_F(WrappableTest, UnwrapFailures) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
// Something that isn't an object.
v8::Handle<v8::Value> thing = v8::Number::New(isolate, 42);
MyObject* unwrapped = NULL;
EXPECT_FALSE(ConvertFromV8(isolate, thing, &unwrapped));
EXPECT_FALSE(unwrapped);
// An object that's not wrapping anything.
thing = v8::Object::New(isolate);
EXPECT_FALSE(ConvertFromV8(isolate, thing, &unwrapped));
EXPECT_FALSE(unwrapped);
// An object that's wrapping a C++ object from Blink.
thing.Clear();
thing = ConvertToV8(isolate, new MyObjectBlink());
EXPECT_FALSE(ConvertFromV8(isolate, thing, &unwrapped));
EXPECT_FALSE(unwrapped);
// An object that's wrapping a C++ object of the wrong type.
thing.Clear();
thing = ConvertToV8(isolate, new MyObject2());
EXPECT_FALSE(ConvertFromV8(isolate, thing, &unwrapped));
EXPECT_FALSE(unwrapped);
}
TEST_F(WrappableTest, GetAndSetProperty) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<MyObject> obj = MyObject::Create(isolate);
obj->set_value(42);
EXPECT_EQ(42, obj->value());
v8::Handle<v8::String> source = StringToV8(isolate,
"(function (obj) {"
" if (obj.value !== 42) throw 'FAIL';"
" else obj.value = 191; })");
EXPECT_FALSE(source.IsEmpty());
gin::TryCatch try_catch;
v8::Handle<v8::Script> script = v8::Script::Compile(source);
EXPECT_FALSE(script.IsEmpty());
v8::Handle<v8::Value> val = script->Run();
EXPECT_FALSE(val.IsEmpty());
v8::Handle<v8::Function> func;
EXPECT_TRUE(ConvertFromV8(isolate, val, &func));
v8::Handle<v8::Value> argv[] = {
ConvertToV8(isolate, obj.get()),
};
func->Call(v8::Undefined(isolate), 1, argv);
EXPECT_FALSE(try_catch.HasCaught());
EXPECT_EQ("", try_catch.GetStackTrace());
EXPECT_EQ(191, obj->value());
}
TEST_F(WrappableTest, WrappableSubclass) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<MyObjectSubclass> object(MyObjectSubclass::Create(isolate));
v8::Handle<v8::String> source = StringToV8(isolate,
"(function(obj) {"
"obj.sayHello('Lily');"
"})");
gin::TryCatch try_catch;
v8::Handle<v8::Script> script = v8::Script::Compile(source);
v8::Handle<v8::Value> val = script->Run();
v8::Handle<v8::Function> func;
EXPECT_TRUE(ConvertFromV8(isolate, val, &func));
v8::Handle<v8::Value> argv[] = {
ConvertToV8(isolate, object.get())
};
func->Call(v8::Undefined(isolate), 1, argv);
EXPECT_FALSE(try_catch.HasCaught());
EXPECT_EQ("Hello, Lily", object->result);
}
TEST_F(WrappableTest, ErrorInObjectConstructorProperty) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::String> source = StringToV8(
isolate,
"(function() {"
" Object.defineProperty(Object.prototype, 'constructor', {"
" get: function() { throw 'Error'; },"
" set: function() { throw 'Error'; }"
" });"
"})();");
EXPECT_FALSE(source.IsEmpty());
v8::Handle<v8::Script> script = v8::Script::New(source);
script->Run();
gin::TryCatch try_catch;
gin::Handle<MyObject> obj = MyObject::Create(isolate);
EXPECT_TRUE(obj.IsEmpty());
EXPECT_TRUE(try_catch.HasCaught());
}
TEST_F(WrappableTest, CallAsFunction) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<MyCallableObject> object(MyCallableObject::Create(isolate));
EXPECT_EQ(0, object->result());
v8::Handle<v8::String> source = StringToV8(isolate,
"(function(obj) {"
"obj(42);"
"})");
gin::TryCatch try_catch;
v8::Handle<v8::Script> script = v8::Script::Compile(source);
v8::Handle<v8::Value> val = script->Run();
v8::Handle<v8::Function> func;
EXPECT_TRUE(ConvertFromV8(isolate, val, &func));
v8::Handle<v8::Value> argv[] = {
ConvertToV8(isolate, object.get())
};
func->Call(v8::Undefined(isolate), 1, argv);
EXPECT_FALSE(try_catch.HasCaught());
EXPECT_EQ(42, object->result());
}
} // namespace gin
<commit_msg>Get rid of even more Script::New calls in Chromium.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "gin/arguments.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/per_isolate_data.h"
#include "gin/public/isolate_holder.h"
#include "gin/test/v8_test.h"
#include "gin/try_catch.h"
#include "gin/wrappable.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gin {
class BaseClass {
public:
BaseClass() : value_(23) {}
virtual ~BaseClass() {}
private:
int value_;
DISALLOW_COPY_AND_ASSIGN(BaseClass);
};
class MyObject : public BaseClass,
public Wrappable<MyObject> {
public:
static WrapperInfo kWrapperInfo;
static gin::Handle<MyObject> Create(v8::Isolate* isolate) {
return CreateHandle(isolate, new MyObject());
}
int value() const { return value_; }
void set_value(int value) { value_ = value; }
protected:
MyObject() : value_(0) {}
virtual ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) OVERRIDE;
virtual ~MyObject() {}
private:
int value_;
};
class MyObjectSubclass : public MyObject {
public:
static gin::Handle<MyObjectSubclass> Create(v8::Isolate* isolate) {
return CreateHandle(isolate, new MyObjectSubclass());
}
void SayHello(const std::string& name) {
result = std::string("Hello, ") + name;
}
std::string result;
private:
virtual ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) OVERRIDE {
return MyObject::GetObjectTemplateBuilder(isolate)
.SetMethod("sayHello", &MyObjectSubclass::SayHello);
}
MyObjectSubclass() {
}
virtual ~MyObjectSubclass() {
}
};
class MyCallableObject : public Wrappable<MyCallableObject> {
public:
static WrapperInfo kWrapperInfo;
static gin::Handle<MyCallableObject> Create(v8::Isolate* isolate) {
return CreateHandle(isolate, new MyCallableObject());
}
int result() { return result_; }
private:
virtual ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) OVERRIDE {
return Wrappable<MyCallableObject>::GetObjectTemplateBuilder(isolate)
.SetCallAsFunctionHandler(&MyCallableObject::Call);
}
MyCallableObject() : result_(0) {
}
virtual ~MyCallableObject() {
}
void Call(int val) {
result_ = val;
}
int result_;
};
class MyObject2 : public Wrappable<MyObject2> {
public:
static WrapperInfo kWrapperInfo;
};
class MyObjectBlink : public Wrappable<MyObjectBlink> {
public:
static WrapperInfo kWrapperInfo;
};
WrapperInfo MyObject::kWrapperInfo = { kEmbedderNativeGin };
ObjectTemplateBuilder MyObject::GetObjectTemplateBuilder(v8::Isolate* isolate) {
return Wrappable<MyObject>::GetObjectTemplateBuilder(isolate)
.SetProperty("value", &MyObject::value, &MyObject::set_value);
}
WrapperInfo MyCallableObject::kWrapperInfo = { kEmbedderNativeGin };
WrapperInfo MyObject2::kWrapperInfo = { kEmbedderNativeGin };
WrapperInfo MyObjectBlink::kWrapperInfo = { kEmbedderNativeGin };
typedef V8Test WrappableTest;
TEST_F(WrappableTest, WrapAndUnwrap) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
Handle<MyObject> obj = MyObject::Create(isolate);
v8::Handle<v8::Value> wrapper = ConvertToV8(isolate, obj.get());
EXPECT_FALSE(wrapper.IsEmpty());
MyObject* unwrapped = NULL;
EXPECT_TRUE(ConvertFromV8(isolate, wrapper, &unwrapped));
EXPECT_EQ(obj.get(), unwrapped);
}
TEST_F(WrappableTest, UnwrapFailures) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
// Something that isn't an object.
v8::Handle<v8::Value> thing = v8::Number::New(isolate, 42);
MyObject* unwrapped = NULL;
EXPECT_FALSE(ConvertFromV8(isolate, thing, &unwrapped));
EXPECT_FALSE(unwrapped);
// An object that's not wrapping anything.
thing = v8::Object::New(isolate);
EXPECT_FALSE(ConvertFromV8(isolate, thing, &unwrapped));
EXPECT_FALSE(unwrapped);
// An object that's wrapping a C++ object from Blink.
thing.Clear();
thing = ConvertToV8(isolate, new MyObjectBlink());
EXPECT_FALSE(ConvertFromV8(isolate, thing, &unwrapped));
EXPECT_FALSE(unwrapped);
// An object that's wrapping a C++ object of the wrong type.
thing.Clear();
thing = ConvertToV8(isolate, new MyObject2());
EXPECT_FALSE(ConvertFromV8(isolate, thing, &unwrapped));
EXPECT_FALSE(unwrapped);
}
TEST_F(WrappableTest, GetAndSetProperty) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<MyObject> obj = MyObject::Create(isolate);
obj->set_value(42);
EXPECT_EQ(42, obj->value());
v8::Handle<v8::String> source = StringToV8(isolate,
"(function (obj) {"
" if (obj.value !== 42) throw 'FAIL';"
" else obj.value = 191; })");
EXPECT_FALSE(source.IsEmpty());
gin::TryCatch try_catch;
v8::Handle<v8::Script> script = v8::Script::Compile(source);
EXPECT_FALSE(script.IsEmpty());
v8::Handle<v8::Value> val = script->Run();
EXPECT_FALSE(val.IsEmpty());
v8::Handle<v8::Function> func;
EXPECT_TRUE(ConvertFromV8(isolate, val, &func));
v8::Handle<v8::Value> argv[] = {
ConvertToV8(isolate, obj.get()),
};
func->Call(v8::Undefined(isolate), 1, argv);
EXPECT_FALSE(try_catch.HasCaught());
EXPECT_EQ("", try_catch.GetStackTrace());
EXPECT_EQ(191, obj->value());
}
TEST_F(WrappableTest, WrappableSubclass) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<MyObjectSubclass> object(MyObjectSubclass::Create(isolate));
v8::Handle<v8::String> source = StringToV8(isolate,
"(function(obj) {"
"obj.sayHello('Lily');"
"})");
gin::TryCatch try_catch;
v8::Handle<v8::Script> script = v8::Script::Compile(source);
v8::Handle<v8::Value> val = script->Run();
v8::Handle<v8::Function> func;
EXPECT_TRUE(ConvertFromV8(isolate, val, &func));
v8::Handle<v8::Value> argv[] = {
ConvertToV8(isolate, object.get())
};
func->Call(v8::Undefined(isolate), 1, argv);
EXPECT_FALSE(try_catch.HasCaught());
EXPECT_EQ("Hello, Lily", object->result);
}
TEST_F(WrappableTest, ErrorInObjectConstructorProperty) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::String> source = StringToV8(
isolate,
"(function() {"
" Object.defineProperty(Object.prototype, 'constructor', {"
" get: function() { throw 'Error'; },"
" set: function() { throw 'Error'; }"
" });"
"})();");
EXPECT_FALSE(source.IsEmpty());
v8::Handle<v8::Script> script = v8::Script::Compile(source);
script->Run();
gin::TryCatch try_catch;
gin::Handle<MyObject> obj = MyObject::Create(isolate);
EXPECT_TRUE(obj.IsEmpty());
EXPECT_TRUE(try_catch.HasCaught());
}
TEST_F(WrappableTest, CallAsFunction) {
v8::Isolate* isolate = instance_->isolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<MyCallableObject> object(MyCallableObject::Create(isolate));
EXPECT_EQ(0, object->result());
v8::Handle<v8::String> source = StringToV8(isolate,
"(function(obj) {"
"obj(42);"
"})");
gin::TryCatch try_catch;
v8::Handle<v8::Script> script = v8::Script::Compile(source);
v8::Handle<v8::Value> val = script->Run();
v8::Handle<v8::Function> func;
EXPECT_TRUE(ConvertFromV8(isolate, val, &func));
v8::Handle<v8::Value> argv[] = {
ConvertToV8(isolate, object.get())
};
func->Call(v8::Undefined(isolate), 1, argv);
EXPECT_FALSE(try_catch.HasCaught());
EXPECT_EQ(42, object->result());
}
} // namespace gin
<|endoftext|>
|
<commit_before>#include "pcl/console/parse.h"
#include "boost/filesystem.hpp"
#include "pcl/io/io.h"
#include "pcl/io/ply_io.h"
#include "pcl/common/common.h"
int subsample( int argc, char** argv )
{
typedef Eigen::Vector4f Position;
bool valid_input = true;
std::string cloud_path = "./cloud.ply";
float N = 1000.;
// cloud
if ( (pcl::console::parse_argument( argc, argv, "--cloud", cloud_path) < 0)
|| !boost::filesystem::exists( cloud_path ) )
{
std::cerr << "[" << __func__ << "]: " << "--cloud does not exist: " << cloud_path << std::endl;
valid_input = false;
}
if ( pcl::console::parse_argument( argc, argv, "--N", N) < 0 )
{
std::cerr << "[" << __func__ << "]: " << "Need N to work" << std::endl;
valid_input = false;
}
float scene_size = 1.f;
if ( pcl::console::parse_argument( argc, argv, "--scene-size", scene_size) < 0 )
{
std::cerr << "[" << __func__ << "]: " << "\"--scene-size 1\" assumed to normalize scene to" << std::endl;
}
Position sceneSize; sceneSize << scene_size, scene_size, scene_size, 1;
if ( !valid_input || (pcl::console::find_switch(argc,argv,"-h")) || (pcl::console::find_switch(argc,argv,"--help")) )
{
std::cout << "[" << __func__ << "]: " << "Usage: " << argv[0] << "--subsample\n"
<< "\t--cloud " << cloud_path << "\n"
<< "\t--N " << N
<< "\t--scene-size " << scene_size
<< "\n";
return EXIT_FAILURE;
}
srand( 123456 );
pcl::PointCloud<pcl::PointXYZ> cloud, out_cloud;
out_cloud.reserve( cloud.size() );
std::cout << "reading " << cloud_path << std::endl;
pcl::io::loadPLYFile( cloud_path, cloud );
Position min_pt, max_pt;
pcl::getMinMax3D( cloud, min_pt, max_pt );
std::cout << "min: " << min_pt.transpose() << ", max: " << max_pt.transpose() << std::endl;
Position div = (max_pt - min_pt);
div.setConstant( div.maxCoeff() );
if ( scene_size > 0.f )
{
div(0) = sceneSize(0) / div(0);
div(1) = sceneSize(1) / div(1);
if ( div(2) > 0.f )
div(2) = sceneSize(2) / div(2);
}
#if 1
float chance = N / (float)cloud.size();
for ( size_t pid = 0; pid != cloud.size(); ++pid )
{
if ( (rand() / (float)RAND_MAX) < chance )
{
auto pnt = cloud.at(pid);
if ( scene_size > 0.f )
{
pnt.getVector4fMap() -= min_pt;
pnt.getVector4fMap()(0) *= div(0);
pnt.getVector4fMap()(1) *= div(1);
pnt.getVector4fMap()(2) *= div(2);
}
// std::cout << "adding " << pnt.getVector3fMap().transpose() << " from " << cloud.at(pid).getVector3fMap().transpose() << std::endl;
out_cloud.push_back( pnt );
}
}
#else
out_cloud.push_back( pcl::PointXYZ(5,5,0) );
out_cloud.push_back( pcl::PointXYZ(5,6,0) );
out_cloud.push_back( pcl::PointXYZ(6,5,0) );
out_cloud.push_back( pcl::PointXYZ(6,6,0) );
#endif
std::stringstream ss;
ss << cloud_path.substr( 0, cloud_path.find(".ply") ) << "_" << (int)N << ".ply";
pcl::io::savePLYFile( ss.str(), out_cloud );
return EXIT_SUCCESS;
}
<commit_msg>subsample.cpp - fixed maxCoeff(0,0,0,inf) issue<commit_after>#include "pcl/console/parse.h"
#include "boost/filesystem.hpp"
#include "pcl/io/io.h"
#include "pcl/io/ply_io.h"
#include "pcl/common/common.h"
int subsample( int argc, char** argv )
{
typedef Eigen::Vector4f Position;
bool valid_input = true;
std::string cloud_path = "./cloud.ply";
float N = 1000.;
// cloud
if ( (pcl::console::parse_argument( argc, argv, "--cloud", cloud_path) < 0)
|| !boost::filesystem::exists( cloud_path ) )
{
std::cerr << "[" << __func__ << "]: " << "--cloud does not exist: " << cloud_path << std::endl;
valid_input = false;
}
if ( pcl::console::parse_argument( argc, argv, "--N", N) < 0 )
{
std::cerr << "[" << __func__ << "]: " << "Need N to work" << std::endl;
valid_input = false;
}
float scene_size = 1.f;
if ( pcl::console::parse_argument( argc, argv, "--scene-size", scene_size) < 0 )
{
std::cerr << "[" << __func__ << "]: " << "\"--scene-size 1\" assumed to normalize scene to" << std::endl;
}
Position sceneSize; sceneSize << scene_size, scene_size, scene_size, 1;
if ( !valid_input || (pcl::console::find_switch(argc,argv,"-h")) || (pcl::console::find_switch(argc,argv,"--help")) )
{
std::cout << "[" << __func__ << "]: " << "Usage: " << argv[0] << "--subsample\n"
<< "\t--cloud " << cloud_path << "\n"
<< "\t--N " << N
<< "\t--scene-size " << scene_size
<< "\n";
return EXIT_FAILURE;
}
srand( 123456 );
pcl::PointCloud<pcl::PointXYZ> cloud, out_cloud;
out_cloud.reserve( cloud.size() );
std::cout << "reading " << cloud_path << std::endl;
pcl::io::loadPLYFile( cloud_path, cloud );
Position min_pt, max_pt;
pcl::getMinMax3D( cloud, min_pt, max_pt );
Position div = (max_pt - min_pt);
div.setConstant( div.head<3>().maxCoeff() );
std::cout << "min: " << min_pt.transpose() << ", max: " << max_pt.transpose() << ", div: " << div.transpose() << std::endl;
if ( scene_size > 0.f )
{
div(0) = sceneSize(0) / div(0);
div(1) = sceneSize(1) / div(1);
if ( div(2) > 0.f )
div(2) = sceneSize(2) / div(2);
}
#if 1
float chance = N / (float)cloud.size();
for ( size_t pid = 0; pid != cloud.size(); ++pid )
{
if ( (rand() / (float)RAND_MAX) < chance )
{
auto pnt = cloud.at(pid);
if ( scene_size > 0.f )
{
pnt.getVector4fMap() -= min_pt;
pnt.getVector4fMap()(0) *= div(0);
pnt.getVector4fMap()(1) *= div(1);
pnt.getVector4fMap()(2) *= div(2);
}
// std::cout << "adding " << pnt.getVector3fMap().transpose() << " from " << cloud.at(pid).getVector3fMap().transpose() << std::endl;
out_cloud.push_back( pnt );
}
}
#else
out_cloud.push_back( pcl::PointXYZ(5,5,0) );
out_cloud.push_back( pcl::PointXYZ(5,6,0) );
out_cloud.push_back( pcl::PointXYZ(6,5,0) );
out_cloud.push_back( pcl::PointXYZ(6,6,0) );
#endif
std::stringstream ss;
ss << cloud_path.substr( 0, cloud_path.find(".ply") ) << "_" << (int)N << ".ply";
pcl::io::savePLYFile( ss.str(), out_cloud );
return EXIT_SUCCESS;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.