text stringlengths 54 60.6k |
|---|
<commit_before>/*
===========================================================================
daemon gpl source code
copyright (c) 2013 unvanquished developers
this file is part of the daemon gpl source code (daemon source code).
daemon source code is free software: you can redistribute it and/or modify
it under the terms of the gnu general public license as published by
the free software foundation, either version 3 of the license, or
(at your option) any later version.
daemon source code is distributed in the hope that it will be useful,
but without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose. see the
gnu general public license for more details.
you should have received a copy of the gnu general public license
along with daemon source code. if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
#include "AudioPrivate.h"
namespace Audio {
//TODO nice usecase for Cvar::Range
//TODO lazily check for the values
static Cvar::Cvar<float> effectsVolume("audio.volume.effects", "the volume of the effects", Cvar::ARCHIVE, 0.8f);
static Cvar::Cvar<float> musicVolume("audio.volume.music", "the volume of the music", Cvar::ARCHIVE, 0.8f);
// We have a big, fixed number of source to avoid rendering too many sounds and slowing down the rest of the engine.
struct sourceRecord_t {
AL::Source source;
std::shared_ptr<Sound> usingSound;
bool active;
int priority;
};
static sourceRecord_t* sources = nullptr;
static constexpr int nSources = 128; //TODO see what's the limit for OpenAL soft
sourceRecord_t* GetSource(int priority);
static bool initialized = false;
void InitSounds() {
if (initialized) {
return;
}
sources = new sourceRecord_t[nSources];
for (int i = 0; i < nSources; i++) {
sources[i].active = false;
}
initialized = true;
}
void ShutdownSounds() {
if (not initialized) {
return;
}
delete[] sources;
sources = nullptr;
initialized = false;
}
void UpdateSounds() {
for (int i = 0; i < nSources; i++) {
if (sources[i].active) {
auto sound = sources[i].usingSound;
// Update and Emitter::UpdateSound can call Sound::Stop
if (not sound->IsStopped()) {
sound->Update();
}
if (not sound->IsStopped()) {
sound->GetEmitter()->UpdateSound(*sound);
}
if (sound->IsStopped()) {
sources[i].active = false;
sources[i].usingSound = nullptr;
}
}
}
}
void AddSound(std::shared_ptr<Emitter> emitter, std::shared_ptr<Sound> sound, int priority) {
sourceRecord_t* source = GetSource(priority);
if (source) {
// Make the source forget if it was a "static" or a "streaming" source.
source->source.ResetBuffer();
sound->SetEmitter(emitter);
sound->AcquireSource(source->source);
source->usingSound = sound;
source->priority = priority;
source->active = true;
sound->FinishSetup();
sound->Play();
}
}
// Finds a inactive or low-priority source to play a new sound.
sourceRecord_t* GetSource(int priority) {
//TODO make a better heuristic? (take into account the distance / the volume /... ?)
int best = -1;
int bestPriority = priority;
// Gets the minimum sound by comparing activity first then priority
for (int i = 0; i < nSources; i++) {
sourceRecord_t& source = sources[i];
if (not source.active) {
return &source;
}
if (best < 0 && source.priority <= priority) {
best = i;
bestPriority = source.priority;
continue;
}
if (source.priority < bestPriority) {
best = i;
bestPriority = source.priority;
continue;
}
}
if (best >= 0) {
sourceRecord_t& source = sources[best];
source.source.Stop();
source.source.RemoveAllQueuedBuffers();
source.usingSound = nullptr;
return &source;
} else {
return nullptr;
}
}
// Implementation of Sound
Sound::Sound(): positionalGain(1.0f), soundGain(1.0f), currentGain(1.0f) {
}
Sound::~Sound() {
}
void Sound::Play() {
source->Play();
playing = true;
}
void Sound::Stop() {
source->Stop();
playing = false;
}
bool Sound::IsStopped() {
return not playing;
}
void Sound::SetPositionalGain(float gain) {
positionalGain = gain;
}
void Sound::SetSoundGain(float gain) {
soundGain = gain;
}
float Sound::GetCurrentGain() {
return currentGain;
}
void Sound::SetEmitter(std::shared_ptr<Emitter> emitter) {
this->emitter = emitter;
}
std::shared_ptr<Emitter> Sound::GetEmitter() {
return emitter;
}
void Sound::AcquireSource(AL::Source& source) {
this->source = &source;
source.SetLooping(false);
SetupSource(source);
emitter->SetupSound(*this);
}
AL::Source& Sound::GetSource() {
return *source;
}
// Set the gain before the source is started to avoid having a few milliseconds of very lound sound
void Sound::FinishSetup() {
currentGain = positionalGain * soundGain * effectsVolume.Get();
source->SetGain(currentGain);
}
void Sound::Update() {
// Fade the Gain update to avoid "ticking" sounds when there is a gain discontinuity
float targetGain = positionalGain * soundGain * effectsVolume.Get();
//TODO make it framerate independant and fade out in about 1/8 seconds ?
if (currentGain > targetGain) {
currentGain = std::max(currentGain - 0.02f, targetGain);
//currentGain = std::max(currentGain * 1.05f, targetGain);
} else if (currentGain < targetGain) {
currentGain = std::min(currentGain + 0.02f, targetGain);
//currentGain = std::min(currentGain / 1.05f - 0.01f, targetGain);
}
source->SetGain(currentGain);
InternalUpdate();
}
// Implementation of OneShotSound
OneShotSound::OneShotSound(Sample* sample): sample(sample) {
}
OneShotSound::~OneShotSound() {
}
void OneShotSound::SetupSource(AL::Source& source) {
source.SetBuffer(sample->GetBuffer());
SetSoundGain(effectsVolume.Get());
}
void OneShotSound::InternalUpdate() {
if (GetSource().IsStopped()) {
Stop();
return;
}
SetSoundGain(effectsVolume.Get());
}
// Implementation of LoopingSound
LoopingSound::LoopingSound(Sample* sample): sample(sample), fadingOut(false) {
}
LoopingSound::~LoopingSound() {
}
void LoopingSound::FadeOutAndDie() {
fadingOut = true;
SetSoundGain(0.0f);
}
void LoopingSound::SetupSource(AL::Source& source) {
source.SetLooping(true);
source.SetBuffer(sample->GetBuffer());
SetSoundGain(effectsVolume.Get());
}
void LoopingSound::InternalUpdate() {
if (fadingOut and GetCurrentGain() == 0.0f) {
Stop();
}
if (not fadingOut) {
SetSoundGain(effectsVolume.Get());
}
}
// Implementation of MusicSound
MusicSound::MusicSound(Str::StringRef leadingStreamName, Str::StringRef loopStreamName)
: leadingStream(S_CodecOpenStream(leadingStreamName.c_str())),
loopStreamName(loopStreamName), loopStream(nullptr), playingLeadingSound(true){
}
MusicSound::~MusicSound() {
if (leadingStream) {
S_CodecCloseStream(leadingStream);
}
if (loopStream) {
S_CodecCloseStream(loopStream);
}
}
void MusicSound::SetupSource(AL::Source& source) {
for (int i = 0; i < NUM_BUFFERS; i++) {
AppendBuffer(source, std::move(AL::Buffer()));
}
SetSoundGain(musicVolume.Get());
}
void MusicSound::InternalUpdate() {
AL::Source& source = GetSource();
// Fill processed buffers and queue them back in the source
while (source.GetNumProcessedBuffers() > 0) {
AppendBuffer(source, std::move(source.PopBuffer()));
}
// If we don't have any more buffers queued it means we have to stop the music
if (source.GetNumQueuedBuffers() == 0) {
Stop();
// If the source stopped because of a lack of buffer but we still have data to play we start the source again
} else if (source.IsStopped()) {
Play();
}
SetSoundGain(musicVolume.Get());
}
void MusicSound::AppendBuffer(AL::Source& source, AL::Buffer buffer) {
snd_stream_t* streamToRead;
if (playingLeadingSound and leadingStream) {
streamToRead = leadingStream;
} else if (loopStream) {
streamToRead = loopStream;
} else {
return;
}
static char tempBuffer[CHUNK_SIZE];
int lengthRead = S_CodecReadStream(streamToRead, CHUNK_SIZE, tempBuffer);
// if a stream is finished, we start playing the loop again, if possible
if (lengthRead == 0) {
S_CodecCloseStream(streamToRead);
playingLeadingSound = false;
// either the stream was the leadin stream and we null it
leadingStream = nullptr;
// either it is the loop stream and we overwrite it
loopStream = S_CodecOpenStream(loopStreamName.c_str());
AppendBuffer(source, std::move(buffer));
return;
}
snd_info_t streamInfo = streamToRead->info;
streamInfo.size = lengthRead; // this isn't set by Codec
buffer.Feed(streamInfo, tempBuffer);
source.QueueBuffer(std::move(buffer));
}
// Implementation of StreamingSound
StreamingSound::StreamingSound() {
}
StreamingSound::~StreamingSound() {
}
void StreamingSound::SetupSource(AL::Source&) {
}
void StreamingSound::InternalUpdate() {
AL::Source& source = GetSource();
while (source.GetNumProcessedBuffers() > 0) {
source.PopBuffer();
}
if (source.GetNumQueuedBuffers() == 0) {
Stop();
}
}
//TODO somehow try to catch back when data is coming faster than we consume (e.g. capture data)
void StreamingSound::AppendBuffer(AL::Buffer buffer) {
if (IsStopped()) {
return;
}
AL::Source& source = GetSource();
source.QueueBuffer(std::move(buffer));
if (source.IsStopped()) {
source.Play();
}
}
void StreamingSound::SetGain(float gain) {
SetSoundGain(gain);
}
}
<commit_msg>Fully initialise instances of class Sound.<commit_after>/*
===========================================================================
daemon gpl source code
copyright (c) 2013 unvanquished developers
this file is part of the daemon gpl source code (daemon source code).
daemon source code is free software: you can redistribute it and/or modify
it under the terms of the gnu general public license as published by
the free software foundation, either version 3 of the license, or
(at your option) any later version.
daemon source code is distributed in the hope that it will be useful,
but without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose. see the
gnu general public license for more details.
you should have received a copy of the gnu general public license
along with daemon source code. if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
#include "AudioPrivate.h"
namespace Audio {
//TODO nice usecase for Cvar::Range
//TODO lazily check for the values
static Cvar::Cvar<float> effectsVolume("audio.volume.effects", "the volume of the effects", Cvar::ARCHIVE, 0.8f);
static Cvar::Cvar<float> musicVolume("audio.volume.music", "the volume of the music", Cvar::ARCHIVE, 0.8f);
// We have a big, fixed number of source to avoid rendering too many sounds and slowing down the rest of the engine.
struct sourceRecord_t {
AL::Source source;
std::shared_ptr<Sound> usingSound;
bool active;
int priority;
};
static sourceRecord_t* sources = nullptr;
static constexpr int nSources = 128; //TODO see what's the limit for OpenAL soft
sourceRecord_t* GetSource(int priority);
static bool initialized = false;
void InitSounds() {
if (initialized) {
return;
}
sources = new sourceRecord_t[nSources];
for (int i = 0; i < nSources; i++) {
sources[i].active = false;
}
initialized = true;
}
void ShutdownSounds() {
if (not initialized) {
return;
}
delete[] sources;
sources = nullptr;
initialized = false;
}
void UpdateSounds() {
for (int i = 0; i < nSources; i++) {
if (sources[i].active) {
auto sound = sources[i].usingSound;
// Update and Emitter::UpdateSound can call Sound::Stop
if (not sound->IsStopped()) {
sound->Update();
}
if (not sound->IsStopped()) {
sound->GetEmitter()->UpdateSound(*sound);
}
if (sound->IsStopped()) {
sources[i].active = false;
sources[i].usingSound = nullptr;
}
}
}
}
void AddSound(std::shared_ptr<Emitter> emitter, std::shared_ptr<Sound> sound, int priority) {
sourceRecord_t* source = GetSource(priority);
if (source) {
// Make the source forget if it was a "static" or a "streaming" source.
source->source.ResetBuffer();
sound->SetEmitter(emitter);
sound->AcquireSource(source->source);
source->usingSound = sound;
source->priority = priority;
source->active = true;
sound->FinishSetup();
sound->Play();
}
}
// Finds a inactive or low-priority source to play a new sound.
sourceRecord_t* GetSource(int priority) {
//TODO make a better heuristic? (take into account the distance / the volume /... ?)
int best = -1;
int bestPriority = priority;
// Gets the minimum sound by comparing activity first then priority
for (int i = 0; i < nSources; i++) {
sourceRecord_t& source = sources[i];
if (not source.active) {
return &source;
}
if (best < 0 && source.priority <= priority) {
best = i;
bestPriority = source.priority;
continue;
}
if (source.priority < bestPriority) {
best = i;
bestPriority = source.priority;
continue;
}
}
if (best >= 0) {
sourceRecord_t& source = sources[best];
source.source.Stop();
source.source.RemoveAllQueuedBuffers();
source.usingSound = nullptr;
return &source;
} else {
return nullptr;
}
}
// Implementation of Sound
Sound::Sound(): positionalGain(1.0f), soundGain(1.0f), currentGain(1.0f), playing(false), source(nullptr) {
}
Sound::~Sound() {
}
void Sound::Play() {
source->Play();
playing = true;
}
void Sound::Stop() {
source->Stop();
playing = false;
}
bool Sound::IsStopped() {
return not playing;
}
void Sound::SetPositionalGain(float gain) {
positionalGain = gain;
}
void Sound::SetSoundGain(float gain) {
soundGain = gain;
}
float Sound::GetCurrentGain() {
return currentGain;
}
void Sound::SetEmitter(std::shared_ptr<Emitter> emitter) {
this->emitter = emitter;
}
std::shared_ptr<Emitter> Sound::GetEmitter() {
return emitter;
}
void Sound::AcquireSource(AL::Source& source) {
this->source = &source;
source.SetLooping(false);
SetupSource(source);
emitter->SetupSound(*this);
}
AL::Source& Sound::GetSource() {
return *source;
}
// Set the gain before the source is started to avoid having a few milliseconds of very lound sound
void Sound::FinishSetup() {
currentGain = positionalGain * soundGain * effectsVolume.Get();
source->SetGain(currentGain);
}
void Sound::Update() {
// Fade the Gain update to avoid "ticking" sounds when there is a gain discontinuity
float targetGain = positionalGain * soundGain * effectsVolume.Get();
//TODO make it framerate independant and fade out in about 1/8 seconds ?
if (currentGain > targetGain) {
currentGain = std::max(currentGain - 0.02f, targetGain);
//currentGain = std::max(currentGain * 1.05f, targetGain);
} else if (currentGain < targetGain) {
currentGain = std::min(currentGain + 0.02f, targetGain);
//currentGain = std::min(currentGain / 1.05f - 0.01f, targetGain);
}
source->SetGain(currentGain);
InternalUpdate();
}
// Implementation of OneShotSound
OneShotSound::OneShotSound(Sample* sample): sample(sample) {
}
OneShotSound::~OneShotSound() {
}
void OneShotSound::SetupSource(AL::Source& source) {
source.SetBuffer(sample->GetBuffer());
SetSoundGain(effectsVolume.Get());
}
void OneShotSound::InternalUpdate() {
if (GetSource().IsStopped()) {
Stop();
return;
}
SetSoundGain(effectsVolume.Get());
}
// Implementation of LoopingSound
LoopingSound::LoopingSound(Sample* sample): sample(sample), fadingOut(false) {
}
LoopingSound::~LoopingSound() {
}
void LoopingSound::FadeOutAndDie() {
fadingOut = true;
SetSoundGain(0.0f);
}
void LoopingSound::SetupSource(AL::Source& source) {
source.SetLooping(true);
source.SetBuffer(sample->GetBuffer());
SetSoundGain(effectsVolume.Get());
}
void LoopingSound::InternalUpdate() {
if (fadingOut and GetCurrentGain() == 0.0f) {
Stop();
}
if (not fadingOut) {
SetSoundGain(effectsVolume.Get());
}
}
// Implementation of MusicSound
MusicSound::MusicSound(Str::StringRef leadingStreamName, Str::StringRef loopStreamName)
: leadingStream(S_CodecOpenStream(leadingStreamName.c_str())),
loopStreamName(loopStreamName), loopStream(nullptr), playingLeadingSound(true){
}
MusicSound::~MusicSound() {
if (leadingStream) {
S_CodecCloseStream(leadingStream);
}
if (loopStream) {
S_CodecCloseStream(loopStream);
}
}
void MusicSound::SetupSource(AL::Source& source) {
for (int i = 0; i < NUM_BUFFERS; i++) {
AppendBuffer(source, std::move(AL::Buffer()));
}
SetSoundGain(musicVolume.Get());
}
void MusicSound::InternalUpdate() {
AL::Source& source = GetSource();
// Fill processed buffers and queue them back in the source
while (source.GetNumProcessedBuffers() > 0) {
AppendBuffer(source, std::move(source.PopBuffer()));
}
// If we don't have any more buffers queued it means we have to stop the music
if (source.GetNumQueuedBuffers() == 0) {
Stop();
// If the source stopped because of a lack of buffer but we still have data to play we start the source again
} else if (source.IsStopped()) {
Play();
}
SetSoundGain(musicVolume.Get());
}
void MusicSound::AppendBuffer(AL::Source& source, AL::Buffer buffer) {
snd_stream_t* streamToRead;
if (playingLeadingSound and leadingStream) {
streamToRead = leadingStream;
} else if (loopStream) {
streamToRead = loopStream;
} else {
return;
}
static char tempBuffer[CHUNK_SIZE];
int lengthRead = S_CodecReadStream(streamToRead, CHUNK_SIZE, tempBuffer);
// if a stream is finished, we start playing the loop again, if possible
if (lengthRead == 0) {
S_CodecCloseStream(streamToRead);
playingLeadingSound = false;
// either the stream was the leadin stream and we null it
leadingStream = nullptr;
// either it is the loop stream and we overwrite it
loopStream = S_CodecOpenStream(loopStreamName.c_str());
AppendBuffer(source, std::move(buffer));
return;
}
snd_info_t streamInfo = streamToRead->info;
streamInfo.size = lengthRead; // this isn't set by Codec
buffer.Feed(streamInfo, tempBuffer);
source.QueueBuffer(std::move(buffer));
}
// Implementation of StreamingSound
StreamingSound::StreamingSound() {
}
StreamingSound::~StreamingSound() {
}
void StreamingSound::SetupSource(AL::Source&) {
}
void StreamingSound::InternalUpdate() {
AL::Source& source = GetSource();
while (source.GetNumProcessedBuffers() > 0) {
source.PopBuffer();
}
if (source.GetNumQueuedBuffers() == 0) {
Stop();
}
}
//TODO somehow try to catch back when data is coming faster than we consume (e.g. capture data)
void StreamingSound::AppendBuffer(AL::Buffer buffer) {
if (IsStopped()) {
return;
}
AL::Source& source = GetSource();
source.QueueBuffer(std::move(buffer));
if (source.IsStopped()) {
source.Play();
}
}
void StreamingSound::SetGain(float gain) {
SetSoundGain(gain);
}
}
<|endoftext|> |
<commit_before>#include "scene/Scene.hpp"
#include "scene/Sky.hpp"
#include "system/TextUtilities.hpp"
#include <map>
#include <sstream>
Scene::Scene(const std::string & name) {
// Append the extension if needed.
std::string fullName = name;
if(!TextUtilities::hasSuffix(name, ".scene")) {
fullName += ".scene";
}
_name = fullName;
}
void printToken(const KeyValues & tk, const std::string & shift) {
Log::Info() << shift << tk.key << ": " << std::endl;
if(!tk.values.empty()) {
Log::Info() << shift << "\t";
for(const auto & val : tk.values) {
Log::Info() << val << " | ";
}
Log::Info() << std::endl;
}
for(const auto & subtk : tk.elements) {
printToken(subtk, shift + "\t");
}
}
void Scene::init(Storage mode) {
if(_loaded) {
return;
}
const auto start = std::chrono::steady_clock::now();
// Define loaders for each keyword.
std::map<std::string, void (Scene::*)(const KeyValues &, Storage)> loaders = {
{"scene", &Scene::loadScene}, {"object", &Scene::loadObject}, {"point", &Scene::loadLight}, {"directional", &Scene::loadLight}, {"spot", &Scene::loadLight}, {"camera", &Scene::loadCamera}, {"background", &Scene::loadBackground}};
// Parse the file.
const std::string sceneFile = Resources::manager().getString(_name);
const std::vector<KeyValues> allParams = Codable::parse(sceneFile);
// Process each group of keyvalues.
for(const auto & element : allParams) {
const std::string key = element.key;
// By construction (see above), all keys should have a loader.
(this->*loaders[key])(element, mode);
}
// Update all objects poses.
for(auto & object : objects) {
const glm::mat4 newModel = _sceneModel * object.model();
object.set(newModel);
}
// The scene model matrix has been applied to all objects, we can reset it.
_sceneModel = glm::mat4(1.0f);
// Update all lights bounding box infos.
_bbox = computeBoundingBox(true);
for(auto & light : lights) {
light->setScene(_bbox);
}
_loaded = true;
const auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start);
Log::Info() << Log::Resources << "Loading took " << duration.count() << "ms." << std::endl;
}
void Scene::loadObject(const KeyValues & params, Storage mode) {
objects.emplace_back();
objects.back().decode(params, mode);
}
void Scene::loadLight(const KeyValues & params, Storage) {
const auto light = Light::decode(params);
if(light) {
lights.push_back(light);
}
}
void Scene::loadCamera(const KeyValues & params, Storage) {
_camera.decode(params);
}
void Scene::loadBackground(const KeyValues & params, Storage mode) {
background = std::unique_ptr<Object>(new Object(Object::Type::Common, Resources::manager().getMesh("plane", mode), false));
for(const auto & param : params.elements) {
if(param.key == "color") {
backgroundMode = Background::COLOR;
// Background is a plane, store the color.
backgroundColor = Codable::decodeVec3(param);
} else if(param.key == "image" && !param.elements.empty()) {
backgroundMode = Background::IMAGE;
// Load image described as sub-element.
const auto texInfos = Codable::decodeTexture(param.elements[0]);
const Texture * tex = Resources::manager().getTexture(texInfos.first, texInfos.second, mode);
background->addTexture(tex);
} else if(param.key == "cube" && !param.elements.empty()) {
backgroundMode = Background::SKYBOX;
// Object is a textured skybox.
background = std::unique_ptr<Object>(new Object(Object::Type::Common, Resources::manager().getMesh("skybox", mode), false));
background->decode(params, mode);
// Load cubemap described as subelement.
const auto texInfos = Codable::decodeTexture(param.elements[0]);
const Texture * tex = Resources::manager().getTexture(texInfos.first, texInfos.second, mode);
background->addTexture(tex);
} else if(param.key == "sun") {
// In that case the background is a sky object.
backgroundMode = Background::ATMOSPHERE;
background = std::unique_ptr<Sky>(new Sky(mode));
background->decode(params, mode);
// Load the scattering table.
const Texture * tex = Resources::manager().getTexture("scattering-precomputed", {Layout::RGB32F, Filter::LINEAR_LINEAR, Wrap::CLAMP}, mode);
background->addTexture(tex);
}
}
}
void Scene::loadScene(const KeyValues & params, Storage mode) {
backgroundIrradiance = std::vector<glm::vec3>(9, glm::vec3(0.0f));
for(const auto & param : params.elements) {
if(param.key == "irradiance" && !param.values.empty()) {
// Load the SH coefficients from the corresponding text file.
const std::string coeffsRaw = Resources::manager().getString(param.values[0]);
std::stringstream coeffsStream(coeffsRaw);
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
for(int i = 0; i < 9; ++i) {
coeffsStream >> x >> y >> z;
backgroundIrradiance[i] = glm::vec3(x, y, z);
}
} else if(param.key == "probe" && !param.elements.empty()) {
// Load cubemap described as sub-element.
const auto texInfos = Codable::decodeTexture(param.elements[0]);
backgroundReflection = Resources::manager().getTexture(texInfos.first, texInfos.second, mode);
}
}
// Update matrix, there is at most one transformation in the scene object.
_sceneModel = Codable::decodeTransformation(params.elements);
}
BoundingBox Scene::computeBoundingBox(bool onlyShadowCasters) {
BoundingBox bbox;
if(objects.empty()) {
return bbox;
}
for(const auto & obj : objects) {
if(onlyShadowCasters && !obj.castsShadow()) {
continue;
}
bbox.merge(obj.boundingBox());
}
Log::Info() << Log::Resources << "Scene bounding box:" << std::endl
<< "mini: " << bbox.minis << std::endl
<< "maxi: " << bbox.maxis << "." << std::endl;
return bbox;
}
void Scene::update(double fullTime, double frameTime) {
for(auto & light : lights) {
light->update(fullTime, frameTime);
}
for(auto & object : objects) {
object.update(fullTime, frameTime);
}
background->update(fullTime, frameTime);
}
void Scene::clean() {
for(auto & light : lights) {
light->clean();
}
}
<commit_msg>Scene: fix missing include.<commit_after>#include "scene/Scene.hpp"
#include "scene/Sky.hpp"
#include "system/TextUtilities.hpp"
#include <map>
#include <sstream>
#include <chrono>
Scene::Scene(const std::string & name) {
// Append the extension if needed.
std::string fullName = name;
if(!TextUtilities::hasSuffix(name, ".scene")) {
fullName += ".scene";
}
_name = fullName;
}
void printToken(const KeyValues & tk, const std::string & shift) {
Log::Info() << shift << tk.key << ": " << std::endl;
if(!tk.values.empty()) {
Log::Info() << shift << "\t";
for(const auto & val : tk.values) {
Log::Info() << val << " | ";
}
Log::Info() << std::endl;
}
for(const auto & subtk : tk.elements) {
printToken(subtk, shift + "\t");
}
}
void Scene::init(Storage mode) {
if(_loaded) {
return;
}
const auto start = std::chrono::steady_clock::now();
// Define loaders for each keyword.
std::map<std::string, void (Scene::*)(const KeyValues &, Storage)> loaders = {
{"scene", &Scene::loadScene}, {"object", &Scene::loadObject}, {"point", &Scene::loadLight}, {"directional", &Scene::loadLight}, {"spot", &Scene::loadLight}, {"camera", &Scene::loadCamera}, {"background", &Scene::loadBackground}};
// Parse the file.
const std::string sceneFile = Resources::manager().getString(_name);
const std::vector<KeyValues> allParams = Codable::parse(sceneFile);
// Process each group of keyvalues.
for(const auto & element : allParams) {
const std::string key = element.key;
// By construction (see above), all keys should have a loader.
(this->*loaders[key])(element, mode);
}
// Update all objects poses.
for(auto & object : objects) {
const glm::mat4 newModel = _sceneModel * object.model();
object.set(newModel);
}
// The scene model matrix has been applied to all objects, we can reset it.
_sceneModel = glm::mat4(1.0f);
// Update all lights bounding box infos.
_bbox = computeBoundingBox(true);
for(auto & light : lights) {
light->setScene(_bbox);
}
_loaded = true;
const auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start);
Log::Info() << Log::Resources << "Loading took " << duration.count() << "ms." << std::endl;
}
void Scene::loadObject(const KeyValues & params, Storage mode) {
objects.emplace_back();
objects.back().decode(params, mode);
}
void Scene::loadLight(const KeyValues & params, Storage) {
const auto light = Light::decode(params);
if(light) {
lights.push_back(light);
}
}
void Scene::loadCamera(const KeyValues & params, Storage) {
_camera.decode(params);
}
void Scene::loadBackground(const KeyValues & params, Storage mode) {
background = std::unique_ptr<Object>(new Object(Object::Type::Common, Resources::manager().getMesh("plane", mode), false));
for(const auto & param : params.elements) {
if(param.key == "color") {
backgroundMode = Background::COLOR;
// Background is a plane, store the color.
backgroundColor = Codable::decodeVec3(param);
} else if(param.key == "image" && !param.elements.empty()) {
backgroundMode = Background::IMAGE;
// Load image described as sub-element.
const auto texInfos = Codable::decodeTexture(param.elements[0]);
const Texture * tex = Resources::manager().getTexture(texInfos.first, texInfos.second, mode);
background->addTexture(tex);
} else if(param.key == "cube" && !param.elements.empty()) {
backgroundMode = Background::SKYBOX;
// Object is a textured skybox.
background = std::unique_ptr<Object>(new Object(Object::Type::Common, Resources::manager().getMesh("skybox", mode), false));
background->decode(params, mode);
// Load cubemap described as subelement.
const auto texInfos = Codable::decodeTexture(param.elements[0]);
const Texture * tex = Resources::manager().getTexture(texInfos.first, texInfos.second, mode);
background->addTexture(tex);
} else if(param.key == "sun") {
// In that case the background is a sky object.
backgroundMode = Background::ATMOSPHERE;
background = std::unique_ptr<Sky>(new Sky(mode));
background->decode(params, mode);
// Load the scattering table.
const Texture * tex = Resources::manager().getTexture("scattering-precomputed", {Layout::RGB32F, Filter::LINEAR_LINEAR, Wrap::CLAMP}, mode);
background->addTexture(tex);
}
}
}
void Scene::loadScene(const KeyValues & params, Storage mode) {
backgroundIrradiance = std::vector<glm::vec3>(9, glm::vec3(0.0f));
for(const auto & param : params.elements) {
if(param.key == "irradiance" && !param.values.empty()) {
// Load the SH coefficients from the corresponding text file.
const std::string coeffsRaw = Resources::manager().getString(param.values[0]);
std::stringstream coeffsStream(coeffsRaw);
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
for(int i = 0; i < 9; ++i) {
coeffsStream >> x >> y >> z;
backgroundIrradiance[i] = glm::vec3(x, y, z);
}
} else if(param.key == "probe" && !param.elements.empty()) {
// Load cubemap described as sub-element.
const auto texInfos = Codable::decodeTexture(param.elements[0]);
backgroundReflection = Resources::manager().getTexture(texInfos.first, texInfos.second, mode);
}
}
// Update matrix, there is at most one transformation in the scene object.
_sceneModel = Codable::decodeTransformation(params.elements);
}
BoundingBox Scene::computeBoundingBox(bool onlyShadowCasters) {
BoundingBox bbox;
if(objects.empty()) {
return bbox;
}
for(const auto & obj : objects) {
if(onlyShadowCasters && !obj.castsShadow()) {
continue;
}
bbox.merge(obj.boundingBox());
}
Log::Info() << Log::Resources << "Scene bounding box:" << std::endl
<< "mini: " << bbox.minis << std::endl
<< "maxi: " << bbox.maxis << "." << std::endl;
return bbox;
}
void Scene::update(double fullTime, double frameTime) {
for(auto & light : lights) {
light->update(fullTime, frameTime);
}
for(auto & object : objects) {
object.update(fullTime, frameTime);
}
background->update(fullTime, frameTime);
}
void Scene::clean() {
for(auto & light : lights) {
light->clean();
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2020 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.
*
****************************************************************************/
#include "autopilot_tester.h"
#include <chrono>
TEST_CASE("Takeoff and Land", "[multicopter][vtol]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
tester.arm();
tester.takeoff();
tester.wait_until_hovering();
tester.land();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(180);
tester.wait_until_disarmed(until_disarmed_timeout);
}
TEST_CASE("Fly square Multicopter Missions including RTL", "[multicopter][vtol]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
AutopilotTester::MissionOptions mission_options;
mission_options.rtl_at_end = true;
tester.prepare_square_mission(mission_options);
tester.arm();
tester.execute_mission();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(180);
tester.wait_until_disarmed(until_disarmed_timeout);
}
TEST_CASE("Fly square Multicopter Missions with manual RTL", "[multicopter][vtol]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
AutopilotTester::MissionOptions mission_options;
mission_options.rtl_at_end = false;
tester.prepare_square_mission(mission_options);
tester.check_tracks_mission();
tester.arm();
tester.execute_mission();
tester.wait_until_hovering();
tester.execute_rtl();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(180);
tester.wait_until_disarmed(until_disarmed_timeout);
}
TEST_CASE("Fly straight Multicopter Mission", "[multicopter]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
AutopilotTester::MissionOptions mission_options;
mission_options.rtl_at_end = false;
mission_options.fly_through = true;
tester.prepare_straight_mission(mission_options);
tester.check_mission_item_speed_above(2, 4.5);
tester.check_tracks_mission();
tester.arm();
tester.execute_mission();
tester.wait_until_hovering();
tester.execute_rtl();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(180);
tester.wait_until_disarmed(until_disarmed_timeout);
}
<commit_msg>Increase corridor check thresholds for mission tests<commit_after>/****************************************************************************
*
* Copyright (c) 2020 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.
*
****************************************************************************/
#include "autopilot_tester.h"
#include <chrono>
TEST_CASE("Takeoff and Land", "[multicopter][vtol]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
tester.arm();
tester.takeoff();
tester.wait_until_hovering();
tester.land();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(180);
tester.wait_until_disarmed(until_disarmed_timeout);
}
TEST_CASE("Fly square Multicopter Missions including RTL", "[multicopter][vtol]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
AutopilotTester::MissionOptions mission_options;
mission_options.rtl_at_end = true;
tester.prepare_square_mission(mission_options);
tester.arm();
tester.execute_mission();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(180);
tester.wait_until_disarmed(until_disarmed_timeout);
}
TEST_CASE("Fly square Multicopter Missions with manual RTL", "[multicopter][vtol]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
AutopilotTester::MissionOptions mission_options;
mission_options.rtl_at_end = false;
tester.prepare_square_mission(mission_options);
tester.check_tracks_mission(5.f);
tester.arm();
tester.execute_mission();
tester.wait_until_hovering();
tester.execute_rtl();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(180);
tester.wait_until_disarmed(until_disarmed_timeout);
}
TEST_CASE("Fly straight Multicopter Mission", "[multicopter]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
AutopilotTester::MissionOptions mission_options;
mission_options.rtl_at_end = false;
mission_options.fly_through = true;
tester.prepare_straight_mission(mission_options);
tester.check_mission_item_speed_above(2, 4.5);
tester.check_tracks_mission(5.f);
tester.arm();
tester.execute_mission();
tester.wait_until_hovering();
tester.execute_rtl();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(180);
tester.wait_until_disarmed(until_disarmed_timeout);
}
<|endoftext|> |
<commit_before>#pragma once
#define ENABLE_WAWL_WINDOWBASETYPE
#include "BaseType.hpp"
#include "MenuBaseType.hpp"
namespace wawl {
namespace wnd {
enum class ImageLoadOption : Uint {
DefaultColor = LR_DEFAULTCOLOR,
UseDIBSection = LR_CREATEDIBSECTION,
SysDefaultSize = LR_DEFAULTSIZE,
Monochrome = LR_MONOCHROME,
ShareHandle = LR_SHARED,
UseVGA = LR_VGACOLOR
};
// window show mode
enum class ShowMode : Uint16 {
ForceMinimize = SW_FORCEMINIMIZE,
Hide = SW_HIDE,
Maximize = SW_MAXIMIZE,
Minimize = SW_MINIMIZE,
Restore = SW_RESTORE,
Show = SW_SHOW,
DefaultShow = SW_SHOWDEFAULT,
MaximizedShow = SW_SHOWMAXIMIZED,
MinimizedShow = SW_SHOWMINIMIZED,
InactivateMinimized = SW_SHOWMINNOACTIVE,
NoactivateShow = SW_SHOWNA,
NormalShow = SW_SHOWNORMAL,
NoactivateNormalShow = SW_SHOWNOACTIVATE
};
// window property option
enum class PropOption : unsigned int {
AlignClientByByte = CS_BYTEALIGNCLIENT,
AlignWndByByte = CS_BYTEALIGNWINDOW,
VRedraw = CS_HREDRAW,
HRedraw = CS_VREDRAW,
CallOnDoubleClick = CS_DBLCLKS,
NoClose = CS_NOCLOSE,
ShareDC = CS_CLASSDC,
OriginalDC = CS_OWNDC,
ParentDC = CS_PARENTDC,
Global = CS_GLOBALCLASS,
SaveBitmap = CS_SAVEBITS,
DropShadow = CS_DROPSHADOW
};
// gdi color brushes
enum class ColorBrush : int {
White = WHITE_BRUSH,
Black = BLACK_BRUSH,
DarkGray = DKGRAY_BRUSH,
LightGray = LTGRAY_BRUSH,
Hollow = HOLLOW_BRUSH
};
// window procedure message
// ToDo: need more
enum class Msg : unsigned int {
Activate = WM_ACTIVATE,
ActivateApp = WM_ACTIVATEAPP,
Create = WM_CREATE,
Timer = WM_TIMER,
Destroy = WM_DESTROY,
LClick = WM_LBUTTONDOWN,
MClick = WM_MBUTTONDOWN,
RClick = WM_RBUTTONDOWN,
MouseLDoubleClick = WM_LBUTTONDBLCLK,
MouseMDoubleClick = WM_MBUTTONDBLCLK,
MouseRDoubleClick = WM_RBUTTONDBLCLK,
MouseLUp = WM_LBUTTONUP,
MouseMUp = WM_MBUTTONUP,
MouseRUp = WM_RBUTTONUP,
Close = WM_CLOSE,
Enable = WM_ENABLE,
Resize = WM_SIZE,
Resizing = WM_SIZING,
Move = WM_MOVE,
Quit = WM_QUIT,
Null = WM_NULL,
Paint = WM_PAINT,
// and more...
};
using Message = ::MSG;
// window option
enum class Option : Uint32 {
Bordered = WS_BORDER,
Caption = WS_CAPTION,
Child = WS_CHILD,
NotDrawChildrenRegion = WS_CLIPCHILDREN,
NotDrawBroserRegion = WS_CLIPSIBLINGS,
Disabled = WS_DISABLED,
ControlGroup = WS_GROUP,
UseHorizontalScroll = WS_HSCROLL,
UseVerticalScroll = WS_VSCROLL,
Maxmize = WS_MAXIMIZE,
EnableMaximize = WS_MAXIMIZEBOX,
Minimize = WS_MINIMIZE,
EnableMinimize = WS_MINIMIZEBOX,
Tiled = WS_TILED,
Overlapped = WS_OVERLAPPEDWINDOW,
Popup = WS_POPUP,
PopupSet = WS_POPUPWINDOW,
EnableSizeChange = WS_SIZEBOX,
SysMenu = WS_SYSMENU,
AcceptTab = WS_TABSTOP,
Visible = WS_VISIBLE
};
// extended window option
enum class ExtOption : Uint32 {
EnableFileDD = WS_EX_ACCEPTFILES,
ShowToTaskbar = WS_EX_APPWINDOW,
UseEdgeFrame = WS_EX_CLIENTEDGE,
EnableHelp = WS_EX_CONTEXTHELP,
DistinguishChild = WS_EX_CONTROLPARENT,
EmphasisDialog = WS_EX_DLGMODALFRAME,
Layered = WS_EX_LAYERED,
LeftOrder = WS_EX_LEFT,
LeftScrollBar = WS_EX_LEFTSCROLLBAR,
ReadFromLeft = WS_EX_LTRREADING,
MdiChiled = WS_EX_MDICHILD,
NoParentNotify = WS_EX_NOPARENTNOTIFY,
Overlapped = WS_EX_OVERLAPPEDWINDOW,
Palette = WS_EX_PALETTEWINDOW,
RightOrder = WS_EX_RIGHT,
RightScrollBar = WS_EX_RIGHTSCROLLBAR,
ReadFromRight = WS_EX_RTLREADING,
UseFloatFrame = WS_EX_STATICEDGE,
ToolWindow = WS_EX_TOOLWINDOW,
TopMost = WS_EX_TOPMOST,
Transparent = WS_EX_TRANSPARENT
};
// window procedure function
using ProcFunc = std::remove_pointer_t<::WNDPROC>;
using WindowHandle = ::HWND;
using ChildID = MenuHandle;
using CreateStruct = ::CREATESTRUCT;
} // ::wawl::wnd
} // ::wawl<commit_msg>Add some window messages<commit_after>#pragma once
#define ENABLE_WAWL_WINDOWBASETYPE
#include "BaseType.hpp"
#include "MenuBaseType.hpp"
namespace wawl {
namespace wnd {
enum class ImageLoadOption : Uint {
DefaultColor = LR_DEFAULTCOLOR,
UseDIBSection = LR_CREATEDIBSECTION,
SysDefaultSize = LR_DEFAULTSIZE,
Monochrome = LR_MONOCHROME,
ShareHandle = LR_SHARED,
UseVGA = LR_VGACOLOR
};
// window show mode
enum class ShowMode : Uint16 {
ForceMinimize = SW_FORCEMINIMIZE,
Hide = SW_HIDE,
Maximize = SW_MAXIMIZE,
Minimize = SW_MINIMIZE,
Restore = SW_RESTORE,
Show = SW_SHOW,
DefaultShow = SW_SHOWDEFAULT,
MaximizedShow = SW_SHOWMAXIMIZED,
MinimizedShow = SW_SHOWMINIMIZED,
InactivateMinimized = SW_SHOWMINNOACTIVE,
NoactivateShow = SW_SHOWNA,
NormalShow = SW_SHOWNORMAL,
NoactivateNormalShow = SW_SHOWNOACTIVATE
};
// window property option
enum class PropOption : unsigned int {
AlignClientByByte = CS_BYTEALIGNCLIENT,
AlignWndByByte = CS_BYTEALIGNWINDOW,
VRedraw = CS_HREDRAW,
HRedraw = CS_VREDRAW,
CallOnDoubleClick = CS_DBLCLKS,
NoClose = CS_NOCLOSE,
ShareDC = CS_CLASSDC,
OriginalDC = CS_OWNDC,
ParentDC = CS_PARENTDC,
Global = CS_GLOBALCLASS,
SaveBitmap = CS_SAVEBITS,
DropShadow = CS_DROPSHADOW
};
// gdi color brushes
enum class ColorBrush : int {
White = WHITE_BRUSH,
Black = BLACK_BRUSH,
DarkGray = DKGRAY_BRUSH,
LightGray = LTGRAY_BRUSH,
Hollow = HOLLOW_BRUSH
};
// window procedure message
// ToDo: need more
enum class Msg : unsigned int {
Activate = WM_ACTIVATE,
ActivateApp = WM_ACTIVATEAPP,
ChildActivate = WM_CHILDACTIVATE,
Close = WM_CLOSE,
Command = WM_COMMAND,
Create = WM_CREATE,
Destroy = WM_DESTROY,
ToggleState = WM_ENABLE,
Timer = WM_TIMER,
LClick = WM_LBUTTONDOWN,
MClick = WM_MBUTTONDOWN,
RClick = WM_RBUTTONDOWN,
MouseLDoubleClick = WM_LBUTTONDBLCLK,
MouseMDoubleClick = WM_MBUTTONDBLCLK,
MouseRDoubleClick = WM_RBUTTONDBLCLK,
MouseLUp = WM_LBUTTONUP,
MouseMUp = WM_MBUTTONUP,
MouseRUp = WM_RBUTTONUP,
Resize = WM_SIZE,
Resizing = WM_SIZING,
Move = WM_MOVE,
Quit = WM_QUIT,
Null = WM_NULL,
Paint = WM_PAINT,
CharInput = WM_CHAR,
CharInputDetail = WM_CHARTOITEM,
GetFocus = WM_SETFOCUS,
LostFocus = WM_KILLFOCUS,
GetClipboardFormats = WM_ASKCBFORMATNAME,
CancelJaurnal = WM_CANCELJOURNAL,
MouseCaptureChanged = WM_CAPTURECHANGED,
ClipboardChainChanged = WM_CHANGECBCHAIN,
DestroyClipboard = WM_DESTROYCLIPBOARD,
Disable = WM_CANCELMODE,
FontChoose = WM_CHOOSEFONT_GETLOGFONT,
ClearText = WM_CLEAR,
CopyText = WM_COPY,
CutText = WM_CUT,
DeviceChanged = WM_DEVICECHANGE,
DisplayChanged = WM_DISPLAYCHANGE,
ClipboardUpdated = WM_DRAWCLIPBOARD,
SystemShutdown = WM_ENDSESSION,
SystemFontChanged = WM_FONTCHANGE,
Help = WM_HELP,
HotkeyPushed = WM_HOTKEY,
// and more...
};
using Message = ::MSG;
// window option
enum class Option : Uint32 {
Bordered = WS_BORDER,
Caption = WS_CAPTION,
Child = WS_CHILD,
NotDrawChildrenRegion = WS_CLIPCHILDREN,
NotDrawBroserRegion = WS_CLIPSIBLINGS,
Disabled = WS_DISABLED,
ControlGroup = WS_GROUP,
UseHorizontalScroll = WS_HSCROLL,
UseVerticalScroll = WS_VSCROLL,
Maxmize = WS_MAXIMIZE,
EnableMaximize = WS_MAXIMIZEBOX,
Minimize = WS_MINIMIZE,
EnableMinimize = WS_MINIMIZEBOX,
Tiled = WS_TILED,
Overlapped = WS_OVERLAPPEDWINDOW,
Popup = WS_POPUP,
PopupSet = WS_POPUPWINDOW,
EnableSizeChange = WS_SIZEBOX,
SysMenu = WS_SYSMENU,
AcceptTab = WS_TABSTOP,
Visible = WS_VISIBLE
};
// extended window option
enum class ExtOption : Uint32 {
EnableFileDD = WS_EX_ACCEPTFILES,
ShowToTaskbar = WS_EX_APPWINDOW,
UseEdgeFrame = WS_EX_CLIENTEDGE,
EnableHelp = WS_EX_CONTEXTHELP,
DistinguishChild = WS_EX_CONTROLPARENT,
EmphasisDialog = WS_EX_DLGMODALFRAME,
Layered = WS_EX_LAYERED,
LeftOrder = WS_EX_LEFT,
LeftScrollBar = WS_EX_LEFTSCROLLBAR,
ReadFromLeft = WS_EX_LTRREADING,
MdiChiled = WS_EX_MDICHILD,
NoParentNotify = WS_EX_NOPARENTNOTIFY,
Overlapped = WS_EX_OVERLAPPEDWINDOW,
Palette = WS_EX_PALETTEWINDOW,
RightOrder = WS_EX_RIGHT,
RightScrollBar = WS_EX_RIGHTSCROLLBAR,
ReadFromRight = WS_EX_RTLREADING,
UseFloatFrame = WS_EX_STATICEDGE,
ToolWindow = WS_EX_TOOLWINDOW,
TopMost = WS_EX_TOPMOST,
Transparent = WS_EX_TRANSPARENT
};
// window procedure function
using ProcFunc = std::remove_pointer_t<::WNDPROC>;
using WindowHandle = ::HWND;
using ChildID = MenuHandle;
using CreateStruct = ::CREATESTRUCT;
} // ::wawl::wnd
} // ::wawl<|endoftext|> |
<commit_before>// $Id$
//
// Ported from JTS junit/linearref/AbstractIndexedLineTest.java rev. 1.10
// and junit/linearref/LengthIndexedLineTest.java rev. 1.10
#include <tut.hpp>
#include <utility.h>
// geos
#include <geos/platform.h>
#include <geos/io/WKTReader.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h> // required for use in auto_ptr
#include <geos/geom/LineString.h>
#include <geos/geom/Coordinate.h>
#include <geos/linearref/LengthIndexedLine.h>
// std
#include <cmath>
#include <sstream>
#include <string>
#include <memory>
using namespace geos::geom;
using namespace geos::linearref;
using namespace std;
/**
* Tests the {@link LocationIndexedLine} class
*/
namespace tut {
typedef auto_ptr<Geometry> GeomPtr;
static const double TOLERANCE_DIST = 0.001;
struct test_lengthindexedline_data
{
test_lengthindexedline_data()
: pm(), gf(&pm), reader(&gf)
{}
PrecisionModel pm;
GeometryFactory gf;
geos::io::WKTReader reader;
void checkExpected(Geometry* result, string const& expected)
{
GeomPtr subLine(reader.read(expected));
ensure_equals_geometry(subLine.get(), result);
}
void checkExpected(Geometry* result, const Geometry* expected)
{
ensure_equals_geometry(expected, result);
}
void runIndicesOfThenExtract(string const& inputStr, string const& subLineStr)
{
GeomPtr input(reader.read(inputStr));
GeomPtr subLine(reader.read(subLineStr));
GeomPtr result(indicesOfThenExtract(input.get(), subLine.get()));
checkExpected(result.get(), subLine.get());
}
bool indexOfAfterCheck(Geometry* linearGeom, Coordinate testPt)
{
LengthIndexedLine indexedLine(linearGeom);
// check locations are consecutive
double loc1 = indexedLine.indexOf(testPt);
double loc2 = indexedLine.indexOfAfter(testPt, loc1);
if (loc2 <= loc1) return false;
// check extracted points are the same as the input
Coordinate pt1 = indexedLine.extractPoint(loc1);
Coordinate pt2 = indexedLine.extractPoint(loc2);
if (! pt1.equals2D(testPt)) return false;
if (! pt2.equals2D(testPt)) return false;
return true;
}
void runIndexOfAfterTest(string const& inputStr, string const& testPtWKT)
{
GeomPtr input(reader.read(inputStr));
GeomPtr testPoint(reader.read(testPtWKT));
const Coordinate* testPt = testPoint->getCoordinate();
bool resultOK = indexOfAfterCheck(input.get(), *testPt);
ensure(resultOK);
}
void runOffsetTest(string const& inputWKT, string const& testPtWKT,
double offsetDistance, string const& expectedPtWKT)
{
GeomPtr input(reader.read(inputWKT));
GeomPtr testPoint(reader.read(testPtWKT));
GeomPtr expectedPoint(reader.read(expectedPtWKT));
const Coordinate* testPt = testPoint->getCoordinate();
const Coordinate* expectedPt = expectedPoint->getCoordinate();
Coordinate offsetPt = extractOffsetAt(input.get(), *testPt, offsetDistance);
bool isOk = offsetPt.distance(*expectedPt) < TOLERANCE_DIST;
if (! isOk)
cout << "Expected = " << *expectedPoint << " Actual = " << offsetPt << endl;
ensure(isOk);
}
Coordinate extractOffsetAt(Geometry* linearGeom, Coordinate testPt, double offsetDistance)
{
LengthIndexedLine indexedLine(linearGeom);
double index = indexedLine.indexOf(testPt);
return indexedLine.extractPoint(index, offsetDistance);
}
void checkExtractLine(const char* wkt, double start, double end, const char* expected)
{
string wktstr(wkt);
GeomPtr linearGeom(reader.read(wktstr));
LengthIndexedLine indexedLine(linearGeom.get());
GeomPtr result(indexedLine.extractLine(start, end));
checkExpected(result.get(), expected);
}
Geometry* indicesOfThenExtract(Geometry* linearGeom, Geometry* subLine)
{
LengthIndexedLine indexedLine(linearGeom);
double* loc = indexedLine.indicesOf(subLine);
Geometry* result = indexedLine.extractLine(loc[0], loc[1]);
delete [] loc;
return result;
}
}; // struct test_lengthindexedline_data
typedef test_group<test_lengthindexedline_data> group;
typedef group::object object;
group test_lengthindexedline_group("geos::linearref::LocationIndexedLine");
//1 - testML
template<>
template<>
void object::test<1>()
{
runIndicesOfThenExtract("MULTILINESTRING ((0 0, 10 10), (20 20, 30 30))",
"MULTILINESTRING ((1 1, 10 10), (20 20, 25 25))");
}
//2 - testPartOfSegmentNoVertex
template<>
template<>
void object::test<2>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 20 20)",
"LINESTRING (1 1, 9 9)");
}
//3 - testPartOfSegmentContainingVertex()
template<>
template<>
void object::test<3>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 20 20)",
"LINESTRING (5 5, 10 10, 15 15)");
}
/**
* Tests that duplicate coordinates are handled correctly.
*
* @throws Exception
*/
// 4 - testPartOfSegmentContainingDuplicateCoords
template<>
template<>
void object::test<4>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 10 10, 20 20)",
"LINESTRING (5 5, 10 10, 10 10, 15 15)");
}
/**
* Following tests check that correct portion of loop is identified.
* This requires that the correct vertex for (0,0) is selected.
*/
//5 - testLoopWithStartSubLine
template<>
template<>
void object::test<5>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"LINESTRING (0 0, 0 10, 10 10)");
}
//6 - testLoopWithEndingSubLine()
template<>
template<>
void object::test<6>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"LINESTRING (10 10, 10 0, 0 0)");
}
// test a subline equal to the parent loop
//7 - testLoopWithIdenticalSubLine()
template<>
template<>
void object::test<7>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)");
}
// test a zero-length subline equal to the start point
//8 - testZeroLenSubLineAtStart()
template<>
template<>
void object::test<8>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"LINESTRING (0 0, 0 0)");
}
// test a zero-length subline equal to a mid point
//9 - testZeroLenSubLineAtMidVertex()
template<>
template<>
void object::test<9>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"LINESTRING (10 10, 10 10)");
}
//10 - testIndexOfAfterSquare()
template<>
template<>
void object::test<10>()
{
runIndexOfAfterTest("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"POINT (0 0)");
}
//11 - testIndexOfAfterRibbon()
template<>
template<>
void object::test<11>()
{
runIndexOfAfterTest("LINESTRING (0 0, 0 60, 50 60, 50 20, -20 20)",
"POINT (0 20)");
}
//12 - testOffsetStartPoint()
template<>
template<>
void object::test<12>()
{
runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(0 0)", 1.0, "POINT (-0.7071067811865475 0.7071067811865475)");
runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(0 0)", -1.0, "POINT (0.7071067811865475 -0.7071067811865475)");
runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(10 10)", 5.0, "POINT (6.464466094067262 13.535533905932738)");
runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(10 10)", -5.0, "POINT (13.535533905932738 6.464466094067262)");
}
//13 - testExtractLineBeyondRange()
template<>
template<>
void object::test<13>()
{
checkExtractLine("LINESTRING (0 0, 10 10)", -100, 100, "LINESTRING (0 0, 10 10)");
}
//14 - testExtractLineReverse()
template<>
template<>
void object::test<14>()
{
checkExtractLine("LINESTRING (0 0, 10 0)", 9, 1, "LINESTRING (9 0, 1 0)");
}
//15 - testExtractLineReverseMulti()
template<>
template<>
void object::test<15>()
{
checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
19, 1, "MULTILINESTRING ((29 0, 25 0, 20 0), (10 0, 1 0))");
}
//16 - testExtractLineNegative()
template<>
template<>
void object::test<16>()
{
checkExtractLine("LINESTRING (0 0, 10 0)", -9, -1, "LINESTRING (1 0, 9 0)");
}
//17 - testExtractLineNegativeReverse()
template<>
template<>
void object::test<17>()
{
checkExtractLine("LINESTRING (0 0, 10 0)", -1, -9, "LINESTRING (9 0, 1 0)");
}
//18 - testExtractLineIndexAtEndpoint()
template<>
template<>
void object::test<18>()
{
checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
10, -1, "LINESTRING (20 0, 25 0, 29 0)");
}
//19 - testExtractLineBothIndicesAtEndpoint()
template<>
template<>
void object::test<19>()
{
checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
10, 10, "LINESTRING (20 0, 20 0)");
}
//20 - testExtractLineBothIndicesAtEndpointNegative()
template<>
template<>
void object::test<20>()
{
checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
-10, 10, "LINESTRING (20 0, 20 0)");
}
//21 - testExtractPointBeyondRange()
template<>
template<>
void object::test<21>()
{
GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 10)"));
LengthIndexedLine indexedLine(linearGeom.get());
Coordinate pt = indexedLine.extractPoint(100);
ensure(pt == Coordinate(10, 10));
Coordinate pt2 = indexedLine.extractPoint(0);
ensure(pt2 == Coordinate(0, 0));
}
//22 - testProjectPointWithDuplicateCoords()
template<>
template<>
void object::test<22>()
{
GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 0, 10 0, 20 0)"));
LengthIndexedLine indexedLine(linearGeom.get());
double projIndex = indexedLine.project(Coordinate(10, 1));
ensure(projIndex == 10.0);
}
/**
* Tests that z values are interpolated
*
*/
//23 - testComputeZ()
template<>
template<>
void object::test<23>()
{
GeomPtr linearGeom(reader.read("LINESTRING (0 0 0, 10 10 10)"));
LengthIndexedLine indexedLine(linearGeom.get());
double projIndex = indexedLine.project(Coordinate(5, 5));
Coordinate projPt = indexedLine.extractPoint(projIndex);
// System.out.println(projPt);
ensure(projPt.equals3D(Coordinate(5, 5, 5)));
}
/**
* Tests that if the input does not have Z ordinates, neither does the output.
*
*/
//24 - testComputeZNaN()
template<>
template<>
void object::test<24>()
{
GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 10 10)"));
LengthIndexedLine indexedLine(linearGeom.get());
double projIndex = indexedLine.project(Coordinate(5, 5));
Coordinate projPt = indexedLine.extractPoint(projIndex);
ensure(0 != ISNAN(projPt.z));
}
}
<commit_msg>Tidy up messy code in tests/unit/linearref<commit_after>// $Id$
//
// Ported from JTS junit/linearref/AbstractIndexedLineTest.java rev. 1.10
// and junit/linearref/LengthIndexedLineTest.java rev. 1.10
#include <tut.hpp>
#include <utility.h>
// geos
#include <geos/platform.h>
#include <geos/io/WKTReader.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h> // required for use in auto_ptr
#include <geos/geom/LineString.h>
#include <geos/geom/Coordinate.h>
#include <geos/linearref/LengthIndexedLine.h>
// std
#include <cmath>
#include <sstream>
#include <string>
#include <memory>
using namespace geos::geom;
using namespace geos::linearref;
using namespace std;
/**
* Tests the {@link LocationIndexedLine} class
*/
namespace tut {
typedef auto_ptr<Geometry> GeomPtr;
static const double TOLERANCE_DIST = 0.001;
struct test_lengthindexedline_data
{
test_lengthindexedline_data()
: pm(), gf(&pm), reader(&gf)
{}
PrecisionModel pm;
GeometryFactory gf;
geos::io::WKTReader reader;
void checkExpected(Geometry* result, string const& expected)
{
GeomPtr subLine(reader.read(expected));
ensure_equals_geometry(subLine.get(), result);
}
void checkExpected(Geometry* result, const Geometry* expected)
{
ensure_equals_geometry(expected, result);
}
void runIndicesOfThenExtract(string const& inputStr, string const& subLineStr)
{
GeomPtr input(reader.read(inputStr));
GeomPtr subLine(reader.read(subLineStr));
GeomPtr result(indicesOfThenExtract(input.get(), subLine.get()));
checkExpected(result.get(), subLine.get());
}
bool indexOfAfterCheck(Geometry* linearGeom, Coordinate testPt)
{
LengthIndexedLine indexedLine(linearGeom);
// check locations are consecutive
double loc1 = indexedLine.indexOf(testPt);
double loc2 = indexedLine.indexOfAfter(testPt, loc1);
if (loc2 <= loc1) return false;
// check extracted points are the same as the input
Coordinate pt1 = indexedLine.extractPoint(loc1);
Coordinate pt2 = indexedLine.extractPoint(loc2);
if (! pt1.equals2D(testPt)) return false;
if (! pt2.equals2D(testPt)) return false;
return true;
}
void runIndexOfAfterTest(string const& inputStr, string const& testPtWKT)
{
GeomPtr input(reader.read(inputStr));
GeomPtr testPoint(reader.read(testPtWKT));
const Coordinate* testPt = testPoint->getCoordinate();
bool resultOK = indexOfAfterCheck(input.get(), *testPt);
ensure(resultOK);
}
void runOffsetTest(string const& inputWKT, string const& testPtWKT,
double offsetDistance, string const& expectedPtWKT)
{
GeomPtr input(reader.read(inputWKT));
GeomPtr testPoint(reader.read(testPtWKT));
GeomPtr expectedPoint(reader.read(expectedPtWKT));
const Coordinate* testPt = testPoint->getCoordinate();
const Coordinate* expectedPt = expectedPoint->getCoordinate();
Coordinate offsetPt = extractOffsetAt(input.get(), *testPt, offsetDistance);
bool isOk = offsetPt.distance(*expectedPt) < TOLERANCE_DIST;
if (! isOk)
cout << "Expected = " << *expectedPoint << " Actual = " << offsetPt << endl;
ensure(isOk);
}
Coordinate extractOffsetAt(Geometry* linearGeom, Coordinate testPt, double offsetDistance)
{
LengthIndexedLine indexedLine(linearGeom);
double index = indexedLine.indexOf(testPt);
return indexedLine.extractPoint(index, offsetDistance);
}
void checkExtractLine(const char* wkt, double start, double end, const char* expected)
{
string wktstr(wkt);
GeomPtr linearGeom(reader.read(wktstr));
LengthIndexedLine indexedLine(linearGeom.get());
GeomPtr result(indexedLine.extractLine(start, end));
checkExpected(result.get(), expected);
}
Geometry* indicesOfThenExtract(Geometry* linearGeom, Geometry* subLine)
{
LengthIndexedLine indexedLine(linearGeom);
double* loc = indexedLine.indicesOf(subLine);
Geometry* result = indexedLine.extractLine(loc[0], loc[1]);
delete [] loc;
return result;
}
}; // struct test_lengthindexedline_data
typedef test_group<test_lengthindexedline_data> group;
typedef group::object object;
group test_lengthindexedline_group("geos::linearref::LocationIndexedLine");
//1 - testML
template<>
template<>
void object::test<1>()
{
runIndicesOfThenExtract("MULTILINESTRING ((0 0, 10 10), (20 20, 30 30))",
"MULTILINESTRING ((1 1, 10 10), (20 20, 25 25))");
}
//2 - testPartOfSegmentNoVertex
template<>
template<>
void object::test<2>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 20 20)",
"LINESTRING (1 1, 9 9)");
}
//3 - testPartOfSegmentContainingVertex()
template<>
template<>
void object::test<3>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 20 20)",
"LINESTRING (5 5, 10 10, 15 15)");
}
/**
* Tests that duplicate coordinates are handled correctly.
*
* @throws Exception
*/
// 4 - testPartOfSegmentContainingDuplicateCoords
template<>
template<>
void object::test<4>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 10 10, 20 20)",
"LINESTRING (5 5, 10 10, 10 10, 15 15)");
}
/**
* Following tests check that correct portion of loop is identified.
* This requires that the correct vertex for (0,0) is selected.
*/
//5 - testLoopWithStartSubLine
template<>
template<>
void object::test<5>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"LINESTRING (0 0, 0 10, 10 10)");
}
//6 - testLoopWithEndingSubLine()
template<>
template<>
void object::test<6>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"LINESTRING (10 10, 10 0, 0 0)");
}
// test a subline equal to the parent loop
//7 - testLoopWithIdenticalSubLine()
template<>
template<>
void object::test<7>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)");
}
// test a zero-length subline equal to the start point
//8 - testZeroLenSubLineAtStart()
template<>
template<>
void object::test<8>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"LINESTRING (0 0, 0 0)");
}
// test a zero-length subline equal to a mid point
//9 - testZeroLenSubLineAtMidVertex()
template<>
template<>
void object::test<9>()
{
runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"LINESTRING (10 10, 10 10)");
}
//10 - testIndexOfAfterSquare()
template<>
template<>
void object::test<10>()
{
runIndexOfAfterTest("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
"POINT (0 0)");
}
//11 - testIndexOfAfterRibbon()
template<>
template<>
void object::test<11>()
{
runIndexOfAfterTest("LINESTRING (0 0, 0 60, 50 60, 50 20, -20 20)",
"POINT (0 20)");
}
//12 - testOffsetStartPoint()
template<>
template<>
void object::test<12>()
{
runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(0 0)", 1.0, "POINT (-0.7071067811865475 0.7071067811865475)");
runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(0 0)", -1.0, "POINT (0.7071067811865475 -0.7071067811865475)");
runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(10 10)", 5.0, "POINT (6.464466094067262 13.535533905932738)");
runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(10 10)", -5.0, "POINT (13.535533905932738 6.464466094067262)");
}
//13 - testExtractLineBeyondRange()
template<>
template<>
void object::test<13>()
{
checkExtractLine("LINESTRING (0 0, 10 10)", -100, 100, "LINESTRING (0 0, 10 10)");
}
//14 - testExtractLineReverse()
template<>
template<>
void object::test<14>()
{
checkExtractLine("LINESTRING (0 0, 10 0)", 9, 1, "LINESTRING (9 0, 1 0)");
}
//15 - testExtractLineReverseMulti()
template<>
template<>
void object::test<15>()
{
checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
19, 1, "MULTILINESTRING ((29 0, 25 0, 20 0), (10 0, 1 0))");
}
//16 - testExtractLineNegative()
template<>
template<>
void object::test<16>()
{
checkExtractLine("LINESTRING (0 0, 10 0)", -9, -1, "LINESTRING (1 0, 9 0)");
}
//17 - testExtractLineNegativeReverse()
template<>
template<>
void object::test<17>()
{
checkExtractLine("LINESTRING (0 0, 10 0)", -1, -9, "LINESTRING (9 0, 1 0)");
}
//18 - testExtractLineIndexAtEndpoint()
template<>
template<>
void object::test<18>()
{
checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
10, -1, "LINESTRING (20 0, 25 0, 29 0)");
}
//19 - testExtractLineBothIndicesAtEndpoint()
template<>
template<>
void object::test<19>()
{
checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
10, 10, "LINESTRING (20 0, 20 0)");
}
//20 - testExtractLineBothIndicesAtEndpointNegative()
template<>
template<>
void object::test<20>()
{
checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
-10, 10, "LINESTRING (20 0, 20 0)");
}
//21 - testExtractPointBeyondRange()
template<>
template<>
void object::test<21>()
{
GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 10)"));
LengthIndexedLine indexedLine(linearGeom.get());
Coordinate pt = indexedLine.extractPoint(100);
ensure(pt == Coordinate(10, 10));
Coordinate pt2 = indexedLine.extractPoint(0);
ensure(pt2 == Coordinate(0, 0));
}
//22 - testProjectPointWithDuplicateCoords()
template<>
template<>
void object::test<22>()
{
GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 0, 10 0, 20 0)"));
LengthIndexedLine indexedLine(linearGeom.get());
double projIndex = indexedLine.project(Coordinate(10, 1));
ensure(projIndex == 10.0);
}
/**
* Tests that z values are interpolated
*
*/
//23 - testComputeZ()
template<>
template<>
void object::test<23>()
{
GeomPtr linearGeom(reader.read("LINESTRING (0 0 0, 10 10 10)"));
LengthIndexedLine indexedLine(linearGeom.get());
double projIndex = indexedLine.project(Coordinate(5, 5));
Coordinate projPt = indexedLine.extractPoint(projIndex);
// System.out.println(projPt);
ensure(projPt.equals3D(Coordinate(5, 5, 5)));
}
/**
* Tests that if the input does not have Z ordinates, neither does the output.
*
*/
//24 - testComputeZNaN()
template<>
template<>
void object::test<24>()
{
GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 10 10)"));
LengthIndexedLine indexedLine(linearGeom.get());
double projIndex = indexedLine.project(Coordinate(5, 5));
Coordinate projPt = indexedLine.extractPoint(projIndex);
ensure(0 != ISNAN(projPt.z));
}
} // namespace tut
<|endoftext|> |
<commit_before>#include <dirent.h>
#include "../InternalTypes.h"
void DirectoryType::__constructor__() {
auto file_path = Program::argument<TextInstance>();
auto self = Program::create<DirectoryInstance>();
self->file_path = file_path->text();
Program::push(self);
}
void DirectoryType::contents() {
auto self = Program::argument<DirectoryInstance>();
auto contents = Program::create<ListInstance>();
auto directory = opendir(self->file_path.c_str());
if (directory != nullptr) { // TODO: Throw exception
while(auto entry = readdir(directory)) {
contents->val.push_back(Program::intern(new DirectoryEntryInstance(std::string(entry->d_name), entry->d_type)));
}
}
Program::push(contents);
}
std::string DirectoryInstance::text() {
return "Directory(" + this->file_path + ")";
}
bool DirectoryInstance::boolean() {
return true;
}
<commit_msg>Thorw user mode exception in Directory.contents<commit_after>#include <dirent.h>
#include "../InternalTypes.h"
void DirectoryType::__constructor__() {
auto file_path = Program::argument<TextInstance>();
auto self = Program::create<DirectoryInstance>();
self->file_path = file_path->text();
Program::push(self);
}
void DirectoryType::contents() {
auto self = Program::argument<DirectoryInstance>();
auto contents = Program::create<ListInstance>();
auto directory = opendir(self->file_path.c_str());
if (directory == nullptr) {
throw ExceptionInstance(Program::create<TextInstance>("Cannot read directory contents"));
}
while(auto entry = readdir(directory)) {
contents->val.push_back(Program::intern(new DirectoryEntryInstance(std::string(entry->d_name), entry->d_type)));
}
Program::push(contents);
}
std::string DirectoryInstance::text() {
return "Directory(" + this->file_path + ")";
}
bool DirectoryInstance::boolean() {
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: testtoolloader.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 01:05:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#include "testtoolloader.hxx"
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _SOLAR_H
#include "solar.h"
#endif
#ifndef _STRING_HXX
#include "string.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include "debug.hxx"
#endif
using namespace rtl;
namespace tools
{
typedef void ( *pfunc_CreateRemoteControl)();
typedef void ( *pfunc_DestroyRemoteControl)();
static oslModule aTestToolModule = 0;
sal_uInt32 GetCommandLineParamCount()
{
NAMESPACE_VOS( OStartupInfo ) aStartInfo;
return aStartInfo.getCommandArgCount();
}
String GetCommandLineParam( sal_uInt32 nParam )
{
NAMESPACE_VOS( OStartupInfo ) aStartInfo;
::rtl::OUString aParam;
NAMESPACE_VOS( OStartupInfo )::TStartupError eError = aStartInfo.getCommandArg( nParam, aParam );
if ( eError == NAMESPACE_VOS( OStartupInfo )::E_None )
return String( aParam );
else
{
DBG_ERROR( "Unable to get CommandLineParam" );
return String();
}
}
void InitTestToolLib()
{
RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::InitTestToolLib" );
sal_uInt32 i;
// are we to be automated at all?
bool bAutomate = false;
for ( i = 0 ; i < GetCommandLineParamCount() ; i++ )
{
if ( GetCommandLineParam( i ).EqualsIgnoreCaseAscii("/enableautomation")
|| GetCommandLineParam( i ).EqualsIgnoreCaseAscii("-enableautomation"))
{
bAutomate = true;
break;
}
}
if ( !bAutomate )
return;
OUString aFuncName( RTL_CONSTASCII_USTRINGPARAM( "CreateRemoteControl" ));
OUString aModulePath;
::vos::OStartupInfo().getExecutableFile( aModulePath );
sal_uInt32 lastIndex = aModulePath.lastIndexOf('/');
if ( lastIndex > 0 )
aModulePath = aModulePath.copy( 0, lastIndex+1 );
aModulePath += OUString::createFromAscii( SVLIBRARY( "sts" ) );
// Shortcut for Performance: We expect that the test tool library is not installed
// (only for testing purpose). It should be located beside our executable.
// We don't want to pay for searching through LD_LIBRARY_PATH so we check for
// existence only in our executable path!!
osl::DirectoryItem aItem;
osl::FileBase::RC nResult = osl::DirectoryItem::get( aModulePath, aItem );
if ( nResult == osl::FileBase::E_None )
{
aTestToolModule = osl_loadModule( aModulePath.pData, SAL_LOADMODULE_DEFAULT );
if ( aTestToolModule )
{
oslGenericFunction pInitFunc = osl_getFunctionSymbol(
aTestToolModule, aFuncName.pData );
if ( pInitFunc )
(reinterpret_cast< pfunc_CreateRemoteControl >(pInitFunc))();
else
{
DBG_ERROR1( "Unable to get Symbol 'CreateRemoteControl' from library %s while loading testtool support.", SVLIBRARY( "sts" ) );
}
}
else
{
DBG_ERROR1( "Error loading library %s while loading testtool support.", SVLIBRARY( "sts" ) );
}
}
else
{
DBG_ERROR1( "Unable to access library %s while loading testtool support.", SVLIBRARY( "sts" ) );
}
}
void DeInitTestToolLib()
{
if ( aTestToolModule )
{
OUString aFuncName( RTL_CONSTASCII_USTRINGPARAM( "DestroyRemoteControl" ));
oslGenericFunction pDeInitFunc = osl_getFunctionSymbol(
aTestToolModule, aFuncName.pData );
if ( pDeInitFunc )
(reinterpret_cast< pfunc_DestroyRemoteControl >(pDeInitFunc))();
osl_unloadModule( aTestToolModule );
}
}
} // namespace tools
<commit_msg>INTEGRATION: CWS hedaburemove01 (1.6.50); FILE MERGED 2006/12/12 16:28:12 vg 1.6.50.1: #i72503# get rid of hedabu<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: testtoolloader.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2007-04-11 20:22:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#include "tools/testtoolloader.hxx"
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _SOLAR_H
#include "tools/solar.h"
#endif
#ifndef _STRING_HXX
#include "tools/string.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include "tools/debug.hxx"
#endif
using namespace rtl;
namespace tools
{
typedef void ( *pfunc_CreateRemoteControl)();
typedef void ( *pfunc_DestroyRemoteControl)();
static oslModule aTestToolModule = 0;
sal_uInt32 GetCommandLineParamCount()
{
NAMESPACE_VOS( OStartupInfo ) aStartInfo;
return aStartInfo.getCommandArgCount();
}
String GetCommandLineParam( sal_uInt32 nParam )
{
NAMESPACE_VOS( OStartupInfo ) aStartInfo;
::rtl::OUString aParam;
NAMESPACE_VOS( OStartupInfo )::TStartupError eError = aStartInfo.getCommandArg( nParam, aParam );
if ( eError == NAMESPACE_VOS( OStartupInfo )::E_None )
return String( aParam );
else
{
DBG_ERROR( "Unable to get CommandLineParam" );
return String();
}
}
void InitTestToolLib()
{
RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::InitTestToolLib" );
sal_uInt32 i;
// are we to be automated at all?
bool bAutomate = false;
for ( i = 0 ; i < GetCommandLineParamCount() ; i++ )
{
if ( GetCommandLineParam( i ).EqualsIgnoreCaseAscii("/enableautomation")
|| GetCommandLineParam( i ).EqualsIgnoreCaseAscii("-enableautomation"))
{
bAutomate = true;
break;
}
}
if ( !bAutomate )
return;
OUString aFuncName( RTL_CONSTASCII_USTRINGPARAM( "CreateRemoteControl" ));
OUString aModulePath;
::vos::OStartupInfo().getExecutableFile( aModulePath );
sal_uInt32 lastIndex = aModulePath.lastIndexOf('/');
if ( lastIndex > 0 )
aModulePath = aModulePath.copy( 0, lastIndex+1 );
aModulePath += OUString::createFromAscii( SVLIBRARY( "sts" ) );
// Shortcut for Performance: We expect that the test tool library is not installed
// (only for testing purpose). It should be located beside our executable.
// We don't want to pay for searching through LD_LIBRARY_PATH so we check for
// existence only in our executable path!!
osl::DirectoryItem aItem;
osl::FileBase::RC nResult = osl::DirectoryItem::get( aModulePath, aItem );
if ( nResult == osl::FileBase::E_None )
{
aTestToolModule = osl_loadModule( aModulePath.pData, SAL_LOADMODULE_DEFAULT );
if ( aTestToolModule )
{
oslGenericFunction pInitFunc = osl_getFunctionSymbol(
aTestToolModule, aFuncName.pData );
if ( pInitFunc )
(reinterpret_cast< pfunc_CreateRemoteControl >(pInitFunc))();
else
{
DBG_ERROR1( "Unable to get Symbol 'CreateRemoteControl' from library %s while loading testtool support.", SVLIBRARY( "sts" ) );
}
}
else
{
DBG_ERROR1( "Error loading library %s while loading testtool support.", SVLIBRARY( "sts" ) );
}
}
else
{
DBG_ERROR1( "Unable to access library %s while loading testtool support.", SVLIBRARY( "sts" ) );
}
}
void DeInitTestToolLib()
{
if ( aTestToolModule )
{
OUString aFuncName( RTL_CONSTASCII_USTRINGPARAM( "DestroyRemoteControl" ));
oslGenericFunction pDeInitFunc = osl_getFunctionSymbol(
aTestToolModule, aFuncName.pData );
if ( pDeInitFunc )
(reinterpret_cast< pfunc_DestroyRemoteControl >(pDeInitFunc))();
osl_unloadModule( aTestToolModule );
}
}
} // namespace tools
<|endoftext|> |
<commit_before>/*
* LCALifLayer.cpp
*
* Created on: Jun 26, 2012
* Author: slundquist & dpaiton
*/
#include "LCALIFLayer.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
//////////////////////////////////////////////////////
// implementation of LIF kernels
//////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif
#ifndef PV_USE_OPENCL
# include "../kernels/LCALIF_update_state.cl"
#else
# undef PV_USE_OPENCL
# undef USE_CLRANDOM
# include "../kernels/LCALIF_update_state.cl"
# define PV_USE_OPENCL
#endif
#ifdef __cplusplus
}
#endif
//Kernel update state implementation receives all necessary variables
//for required computation. File is included above.
#ifdef __cplusplus
extern "C" {
#endif
void LCALIF_update_state(
const int numNeurons,
const float time,
const float dt,
const int nx,
const int ny,
const int nf,
const int nb,
pvdata_t dynVthScale,
pvdata_t * dynVthRest,
const float tauLCA,
const float tauTHR,
const float targetRate,
pvdata_t * integratedSpikeCount,
CL_MEM_CONST LIF_params * params,
CL_MEM_GLOBAL uint4 * rnd,
CL_MEM_GLOBAL float * V,
CL_MEM_GLOBAL float * Vth,
CL_MEM_GLOBAL float * G_E,
CL_MEM_GLOBAL float * G_I,
CL_MEM_GLOBAL float * G_IB,
CL_MEM_GLOBAL float * GSynHead,
CL_MEM_GLOBAL float * activity,
const float sum_gap,
CL_MEM_GLOBAL float * G_Gap
);
#ifdef __cplusplus
}
#endif
namespace PV {
LCALIFLayer::LCALIFLayer() {
initialize_base();
// initialize(arguments) should *not* be called by the protected constructor.
}
LCALIFLayer::LCALIFLayer(const char * name, HyPerCol * hc) {
initialize_base();
initialize(name, hc, MAX_CHANNELS + 1, "LCALIF_update_state");
}
int LCALIFLayer::initialize_base(){
tauLCA = 200;
tauTHR = 1000;
targetRate = 50;
dynVthScale = DEFAULT_DYNVTHSCALE;
dynVthRest = NULL;
integratedSpikeCount = NULL;
return PV_SUCCESS;
}
int LCALIFLayer::initialize(const char * name, HyPerCol * hc, int num_channels, const char * kernel_name){
LIFGap::initialize(name, hc, TypeLCA, num_channels, kernel_name);
PVParams * params = hc->parameters();
tauLCA = params->value(name, "tauLCA", tauLCA);
tauTHR = params->value(name, "tauTHR", tauTHR);
targetRate = params->value(name, "targetRate", targetRate);
//Initialize dynVthRest to vthRest
for (int i = 0; i < (int)getNumNeurons(); i++){
//std::cout << "VthRest: " << VthRest << "\n";
dynVthRest[i] = lParams.VthRest;
}
float defaultDynVthScale = lParams.VthRest-lParams.Vrest;
dynVthScale = defaultDynVthScale > 0 ? dynVthScale : DEFAULT_DYNVTHSCALE;
dynVthScale = params->value(name, "dynVthScale", dynVthScale);
if (dynVthScale <= 0) {
if (hc->columnId()==0) {
fprintf(stderr,"LCALIFLayer \"%s\": dynVthScale must be positive (value in params is %f).\n", name, dynVthScale);
}
abort();
}
return PV_SUCCESS;
}
LCALIFLayer::~LCALIFLayer()
{
free(integratedSpikeCount);
free(dynVthRest);
}
int LCALIFLayer::allocateBuffers() {
const size_t numNeurons = getNumNeurons();
//Allocate data to keep track of trace
integratedSpikeCount = (pvdata_t *) calloc(numNeurons, sizeof(pvdata_t));
assert(integratedSpikeCount != NULL);
dynVthRest = (pvdata_t *) calloc(numNeurons, sizeof(pvdata_t));
assert(dynVthRest != NULL);
return LIFGap::allocateBuffers();
}
int LCALIFLayer::updateState(float time, float dt)
{
//Call update_state kernel
// std::cout << clayer->activity->data[1000] << " " << integratedSpikeCount[1000] << "\n";
LCALIF_update_state(getNumNeurons(), time, dt, clayer->loc.nx, clayer->loc.ny, clayer->loc.nf,
clayer->loc.nb, dynVthScale, dynVthRest, tauLCA, tauTHR, targetRate, integratedSpikeCount, &lParams,
rand_state, clayer->V, Vth, G_E, G_I, G_IB, GSyn[0], clayer->activity->data, sumGap, G_Gap);
return PV_SUCCESS;
}
}
<commit_msg>Fixed a bug for write step in LCALIFLayer<commit_after>/*
* LCALifLayer.cpp
*
* Created on: Jun 26, 2012
* Author: slundquist & dpaiton
*/
#include "LCALIFLayer.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
//////////////////////////////////////////////////////
// implementation of LIF kernels
//////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif
#ifndef PV_USE_OPENCL
# include "../kernels/LCALIF_update_state.cl"
#else
# undef PV_USE_OPENCL
# undef USE_CLRANDOM
# include "../kernels/LCALIF_update_state.cl"
# define PV_USE_OPENCL
#endif
#ifdef __cplusplus
}
#endif
//Kernel update state implementation receives all necessary variables
//for required computation. File is included above.
#ifdef __cplusplus
extern "C" {
#endif
void LCALIF_update_state(
const int numNeurons,
const float time,
const float dt,
const int nx,
const int ny,
const int nf,
const int nb,
pvdata_t dynVthScale,
pvdata_t * dynVthRest,
const float tauLCA,
const float tauTHR,
const float targetRate,
pvdata_t * integratedSpikeCount,
CL_MEM_CONST LIF_params * params,
CL_MEM_GLOBAL uint4 * rnd,
CL_MEM_GLOBAL float * V,
CL_MEM_GLOBAL float * Vth,
CL_MEM_GLOBAL float * G_E,
CL_MEM_GLOBAL float * G_I,
CL_MEM_GLOBAL float * G_IB,
CL_MEM_GLOBAL float * GSynHead,
CL_MEM_GLOBAL float * activity,
const float sum_gap,
CL_MEM_GLOBAL float * G_Gap
);
#ifdef __cplusplus
}
#endif
namespace PV {
LCALIFLayer::LCALIFLayer() {
initialize_base();
// initialize(arguments) should *not* be called by the protected constructor.
}
LCALIFLayer::LCALIFLayer(const char * name, HyPerCol * hc) {
initialize_base();
initialize(name, hc, MAX_CHANNELS + 1, "LCALIF_update_state");
}
int LCALIFLayer::initialize_base(){
tauLCA = 200;
tauTHR = 1000;
targetRate = 50;
dynVthScale = DEFAULT_DYNVTHSCALE;
dynVthRest = NULL;
integratedSpikeCount = NULL;
return PV_SUCCESS;
}
int LCALIFLayer::initialize(const char * name, HyPerCol * hc, int num_channels, const char * kernel_name){
LIFGap::initialize(name, hc, TypeLCA, num_channels, kernel_name);
PVParams * params = hc->parameters();
tauLCA = params->value(name, "tauLCA", tauLCA);
tauTHR = params->value(name, "tauTHR", tauTHR);
targetRate = params->value(name, "targetRate", targetRate);
//Initialize dynVthRest to vthRest
for (int i = 0; i < (int)getNumNeurons(); i++){
//std::cout << "VthRest: " << VthRest << "\n";
dynVthRest[i] = lParams.VthRest;
}
float defaultDynVthScale = lParams.VthRest-lParams.Vrest;
dynVthScale = defaultDynVthScale > 0 ? dynVthScale : DEFAULT_DYNVTHSCALE;
dynVthScale = params->value(name, "dynVthScale", dynVthScale);
if (dynVthScale <= 0) {
if (hc->columnId()==0) {
fprintf(stderr,"LCALIFLayer \"%s\": dynVthScale must be positive (value in params is %f).\n", name, dynVthScale);
}
abort();
}
return PV_SUCCESS;
}
LCALIFLayer::~LCALIFLayer()
{
free(integratedSpikeCount);
free(dynVthRest);
}
int LCALIFLayer::allocateBuffers() {
const size_t numNeurons = getNumNeurons();
//Allocate data to keep track of trace
integratedSpikeCount = (pvdata_t *) calloc(numNeurons, sizeof(pvdata_t));
assert(integratedSpikeCount != NULL);
dynVthRest = (pvdata_t *) calloc(numNeurons, sizeof(pvdata_t));
assert(dynVthRest != NULL);
return LIFGap::allocateBuffers();
}
int LCALIFLayer::updateState(float time, float dt)
{
//Call update_state kernel
// std::cout << clayer->activity->data[1000] << " " << integratedSpikeCount[1000] << "\n";
LCALIF_update_state(getNumNeurons(), time, dt, clayer->loc.nx, clayer->loc.ny, clayer->loc.nf,
clayer->loc.nb, dynVthScale, dynVthRest, tauLCA, tauTHR, targetRate, integratedSpikeCount, &lParams,
rand_state, clayer->V, Vth, G_E, G_I, G_IB, GSyn[0], clayer->activity->data, sumGap, G_Gap);
updateActiveIndices();
return PV_SUCCESS;
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Source: http://svn.mplayerhq.hu/nut/docs/nut.txt?view=markup
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_NUT_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Nut.h"
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Const
//***************************************************************************
//---------------------------------------------------------------------------
namespace Elements
{
const int64u main =0x4E4D7A561F5F04ADLL;
const int64u stream =0x4E5311405BF2F9DBLL;
const int64u syncpoint =0x4E4BE4ADEECA4569LL;
const int64u index =0x4E58DD672F23E64ELL;
const int64u info =0x4E49AB68B596BA78LL;
}
//***************************************************************************
// Buffer
//***************************************************************************
//---------------------------------------------------------------------------
void File_Nut::FileHeader_Parse()
{
//Parsing
Element_Begin1("Nut header");
std::string file_id_string;
int8u file_id_string_zero;
Get_String(24, file_id_string, "file_id_string");
Get_B1 (file_id_string_zero, "file_id_string zero");
Element_End0();
FILLING_BEGIN();
//Integrity
if (file_id_string!="nut/multimedia container" || file_id_string_zero)
{
Reject("Nut");
return;
}
//Filling
Accept("Nut");
Fill(Stream_General, 0, General_Format, "Nut");
FILLING_END();
}
//***************************************************************************
// Elements
//***************************************************************************
//---------------------------------------------------------------------------
void File_Nut::Header_Parse()
{
//Parsing
int8u N;
Peek_B1(N);
if (N==0x4E) //'N'
{
//Header
int64u startcode, forward_ptr;
Get_B8(startcode, "startcode");
Get_VS(forward_ptr, "forward_ptr");
if (forward_ptr>4096)
Skip_B4( "header_checksum");
Header_Fill_Code(startcode, Ztring().From_Number(startcode, 16)); //Quick filling for CC8 with text
Header_Fill_Size(Element_Offset+forward_ptr); //4 for cheksum
}
else
{
//Frame
Header_Fill_Code(0, "Frame");
Header_Fill_Size(0);
Finish();
}
}
//---------------------------------------------------------------------------
void File_Nut::Data_Parse()
{
#define ELEMENT_CASE(_NAME) \
case Elements::_NAME : _NAME(); break;
//Parsing
if (Element_Size < 4)
{
Skip_XX(Element_Size, "Unknown");
return;
}
Element_Size-=4;
#ifndef __BORLANDC__
switch (Element_Code)
#else //__BORLANDC__
switch (Element_Code&0xFFFFFFFF) //Borland does not like int64u for const?
#endif //__BORLANDC__
{
ELEMENT_CASE(main);
ELEMENT_CASE(stream);
ELEMENT_CASE(syncpoint);
ELEMENT_CASE(index);
ELEMENT_CASE(info);
default : Skip_XX(Element_Size, "Data");
}
Element_Size+=4;
if (Element_Offset+4!=Element_Size)
Skip_XX(Element_Size - 4 - Element_Offset, "Unknown");
Skip_B4( "cheksum");
}
//***************************************************************************
// Elements
//***************************************************************************
//---------------------------------------------------------------------------
void File_Nut::main()
{
Element_Name("main");
//Parsing
int64u time_base_count;
Skip_VS( "version");
Skip_VS( "stream_count");
Skip_VS( "max_distance");
Get_VS (time_base_count, "time_base_count");
for(int64u i=0; i<time_base_count; i++)
{
Skip_VS( "time_base_num");
Skip_VS( "time_base_denom");
//time_base[i]= time_base_num/time_base_denom
}
int64u tmp_mul=1;
for(int16u i=0; i<256;)
{
int64u tmp_fields, tmp_size, tmp_res, count;
Skip_VS( "tmp_flag");
Get_VS (tmp_fields, "tmp_fields");
if(tmp_fields>0)
Skip_VS( "tmp_pts"); //TODO: signed
if(tmp_fields>1)
Skip_VS( "tmp_mul");
if(tmp_fields>2)
Skip_VS( "tmp_stream");
if(tmp_fields>3)
Get_VS (tmp_size, "tmp_size");
else
tmp_size=0;
if(tmp_fields>4)
Get_VS (tmp_res, "tmp_res");
else
tmp_res=0;
if(tmp_fields>5)
Get_VS(count, "count");
else
count=tmp_mul-tmp_size;
for(int64u j=6; j<tmp_fields; j++)
Skip_VS( "tmp_reserved[i]");
for(int64u j=0; j<count && i<256; j++, i++)
{
if (i == 'N')
{
//flags[i]= FLAG_INVALID;
j--;
continue;
}
//flags[i]= tmp_flag;
//stream_id[i]= tmp_stream;
//data_size_mul[i]= tmp_mul;
//data_size_lsb[i]= tmp_size + j;
//pts_delta[i]= tmp_pts;
//reserved_count[i]= tmp_res;
}
}
}
//---------------------------------------------------------------------------
void File_Nut::stream()
{
Element_Name("stream");
//Parsing
int64u stream_class, fourcc_length, codec_specific_data_length;
Skip_VS( "stream_id");
Get_VS (stream_class, "stream_class");
Get_VS (fourcc_length, "fourcc length");
switch (fourcc_length)
{
case 2 : Skip_C2( "fourcc"); break;
case 4 : Skip_C4( "fourcc"); break;
default: Skip_XX(fourcc_length, "fourcc");
}
Skip_VS( "time_base_id");
Skip_VS( "msb_pts_shift");
Skip_VS( "max_pts_distance");
Skip_VS( "decode_delay");
Skip_VS( "stream_flags");
Get_VS (codec_specific_data_length, "codec_specific_data length");
Skip_XX(codec_specific_data_length, "codec_specific_data");
switch (stream_class)
{
case 0 : //video
{
Skip_VS( "width");
Skip_VS( "height");
Skip_VS( "sample_width");
Skip_VS( "sample_height");
Skip_VS( "colorspace_type");
}
break;
case 1 : //audio
{
Skip_VS( "samplerate_num");
Skip_VS( "samplerate_denom");
Skip_VS( "channel_count");
}
break;
case 2 : //subtitles
{
}
break;
case 3 : //userdata
{
}
break;
default: ;
}
if (Element_Offset!=Element_Size)
Skip_XX(Element_Size - Element_Offset, "Data");
}
//---------------------------------------------------------------------------
void File_Nut::syncpoint()
{
Element_Name("syncpoint");
//Parsing
Skip_XX(Element_Size, "Data");
}
//---------------------------------------------------------------------------
void File_Nut::index()
{
Element_Name("index");
//Parsing
Skip_XX(Element_Size, "Data");
}
//---------------------------------------------------------------------------
void File_Nut::info()
{
Element_Name("info");
//Parsing
Skip_XX(Element_Size, "Data");
}
}
#endif //MEDIAINFO_NUT_YES
<commit_msg>x Nut: fix crash with some files<commit_after>/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Source: http://svn.mplayerhq.hu/nut/docs/nut.txt?view=markup
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_NUT_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Nut.h"
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Const
//***************************************************************************
//---------------------------------------------------------------------------
namespace Elements
{
const int64u main =0x4E4D7A561F5F04ADLL;
const int64u stream =0x4E5311405BF2F9DBLL;
const int64u syncpoint =0x4E4BE4ADEECA4569LL;
const int64u index =0x4E58DD672F23E64ELL;
const int64u info =0x4E49AB68B596BA78LL;
}
//***************************************************************************
// Buffer
//***************************************************************************
//---------------------------------------------------------------------------
void File_Nut::FileHeader_Parse()
{
//Parsing
Element_Begin1("Nut header");
std::string file_id_string;
int8u file_id_string_zero;
Get_String(24, file_id_string, "file_id_string");
Get_B1 (file_id_string_zero, "file_id_string zero");
Element_End0();
FILLING_BEGIN();
//Integrity
if (file_id_string!="nut/multimedia container" || file_id_string_zero)
{
Reject("Nut");
return;
}
//Filling
Accept("Nut");
Fill(Stream_General, 0, General_Format, "Nut");
FILLING_END();
}
//***************************************************************************
// Elements
//***************************************************************************
//---------------------------------------------------------------------------
void File_Nut::Header_Parse()
{
//Parsing
int8u N;
Peek_B1(N);
if (N==0x4E) //'N'
{
//Header
int64u startcode, forward_ptr;
Get_B8(startcode, "startcode");
Get_VS(forward_ptr, "forward_ptr");
if (forward_ptr>4096)
Skip_B4( "header_checksum");
Header_Fill_Code(startcode, Ztring().From_Number(startcode, 16)); //Quick filling for CC8 with text
Header_Fill_Size(Element_Offset+forward_ptr); //4 for cheksum
}
else
{
//Frame
Header_Fill_Code(0, "Frame");
Header_Fill_Size(File_Size-(File_Offset+Buffer_Offset+Element_Offset));
}
}
//---------------------------------------------------------------------------
void File_Nut::Data_Parse()
{
#define ELEMENT_CASE(_NAME) \
case Elements::_NAME : _NAME(); break;
//Parsing
if (Element_Size < 4)
{
Skip_XX(Element_Size, "Unknown");
return;
}
Element_Size-=4;
#ifndef __BORLANDC__
switch (Element_Code)
#else //__BORLANDC__
switch (Element_Code&0xFFFFFFFF) //Borland does not like int64u for const?
#endif //__BORLANDC__
{
ELEMENT_CASE(main);
ELEMENT_CASE(stream);
ELEMENT_CASE(syncpoint);
ELEMENT_CASE(index);
ELEMENT_CASE(info);
default : Skip_XX(Element_Size, "Data");
}
Element_Size+=4;
if (Element_Offset+4!=Element_Size)
Skip_XX(Element_Size - 4 - Element_Offset, "Unknown");
Skip_B4( "cheksum");
}
//***************************************************************************
// Elements
//***************************************************************************
//---------------------------------------------------------------------------
void File_Nut::main()
{
Element_Name("main");
//Parsing
int64u time_base_count;
Skip_VS( "version");
Skip_VS( "stream_count");
Skip_VS( "max_distance");
Get_VS (time_base_count, "time_base_count");
for(int64u i=0; i<time_base_count; i++)
{
Skip_VS( "time_base_num");
Skip_VS( "time_base_denom");
//time_base[i]= time_base_num/time_base_denom
}
int64u tmp_mul=1;
for(int16u i=0; i<256;)
{
int64u tmp_fields, tmp_size, tmp_res, count;
Skip_VS( "tmp_flag");
Get_VS (tmp_fields, "tmp_fields");
if(tmp_fields>0)
Skip_VS( "tmp_pts"); //TODO: signed
if(tmp_fields>1)
Skip_VS( "tmp_mul");
if(tmp_fields>2)
Skip_VS( "tmp_stream");
if(tmp_fields>3)
Get_VS (tmp_size, "tmp_size");
else
tmp_size=0;
if(tmp_fields>4)
Get_VS (tmp_res, "tmp_res");
else
tmp_res=0;
if(tmp_fields>5)
Get_VS(count, "count");
else
count=tmp_mul-tmp_size;
for(int64u j=6; j<tmp_fields; j++)
Skip_VS( "tmp_reserved[i]");
for(int64u j=0; j<count && i<256; j++, i++)
{
if (i == 'N')
{
//flags[i]= FLAG_INVALID;
j--;
continue;
}
//flags[i]= tmp_flag;
//stream_id[i]= tmp_stream;
//data_size_mul[i]= tmp_mul;
//data_size_lsb[i]= tmp_size + j;
//pts_delta[i]= tmp_pts;
//reserved_count[i]= tmp_res;
}
}
}
//---------------------------------------------------------------------------
void File_Nut::stream()
{
Element_Name("stream");
//Parsing
int64u stream_class, fourcc_length, codec_specific_data_length;
Skip_VS( "stream_id");
Get_VS (stream_class, "stream_class");
Get_VS (fourcc_length, "fourcc length");
switch (fourcc_length)
{
case 2 : Skip_C2( "fourcc"); break;
case 4 : Skip_C4( "fourcc"); break;
default: Skip_XX(fourcc_length, "fourcc");
}
Skip_VS( "time_base_id");
Skip_VS( "msb_pts_shift");
Skip_VS( "max_pts_distance");
Skip_VS( "decode_delay");
Skip_VS( "stream_flags");
Get_VS (codec_specific_data_length, "codec_specific_data length");
Skip_XX(codec_specific_data_length, "codec_specific_data");
switch (stream_class)
{
case 0 : //video
{
Skip_VS( "width");
Skip_VS( "height");
Skip_VS( "sample_width");
Skip_VS( "sample_height");
Skip_VS( "colorspace_type");
}
break;
case 1 : //audio
{
Skip_VS( "samplerate_num");
Skip_VS( "samplerate_denom");
Skip_VS( "channel_count");
}
break;
case 2 : //subtitles
{
}
break;
case 3 : //userdata
{
}
break;
default: ;
}
if (Element_Offset!=Element_Size)
Skip_XX(Element_Size - Element_Offset, "Data");
}
//---------------------------------------------------------------------------
void File_Nut::syncpoint()
{
Element_Name("syncpoint");
//Parsing
Skip_XX(Element_Size, "Data");
}
//---------------------------------------------------------------------------
void File_Nut::index()
{
Element_Name("index");
//Parsing
Skip_XX(Element_Size, "Data");
}
//---------------------------------------------------------------------------
void File_Nut::info()
{
Element_Name("info");
//Parsing
Skip_XX(Element_Size, "Data");
}
}
#endif //MEDIAINFO_NUT_YES
<|endoftext|> |
<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <time.h>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/globals.h"
#include "common/sem.h"
#include "serviceRoutines/versionTreat.h" // For orionInit()
#include "mongoBackend/MongoGlobal.h" // For orionInit()
#include "ngsiNotify/onTimeIntervalThread.h" // For orionInit()
/* ****************************************************************************
*
* Globals
*/
static Timer* timer = NULL;
int startTime = -1;
int statisticsTime = -1;
OrionExitFunction orionExitFunction = NULL;
/* ****************************************************************************
*
* orionInit -
*/
void orionInit(OrionExitFunction exitFunction, const char* version)
{
// Give the rest library the correct version string of this executable
versionSet(version);
// The function to call on fatal error
orionExitFunction = exitFunction;
/* Initialize the semaphore used by mongoBackend */
semInit();
/* Set timer object (singleton) */
setTimer(new Timer());
/* Set notifier object (singleton) */
setNotifier(new Notifier());
/* Set start time */
startTime = getCurrentTime();
statisticsTime = startTime;
}
/* ****************************************************************************
*
* isTrue -
*/
bool isTrue(const std::string& s)
{
if (strcasecmp(s.c_str(), "true") == 0)
return true;
if (strcasecmp(s.c_str(), "yes") == 0)
return true;
return false;
}
/* ****************************************************************************
*
* isFalse -
*/
bool isFalse(const std::string& s)
{
if (strcasecmp(s.c_str(), "false") == 0)
return true;
if (strcasecmp(s.c_str(), "no") == 0)
return true;
return false;
}
/*****************************************************************************
*
* getTimer -
*/
Timer* getTimer() {
return timer;
}
/*****************************************************************************
*
* setTimer -
*/
void setTimer(Timer* t) {
timer = t;
}
/* ****************************************************************************
*
* getCurrentTime -
*/
int getCurrentTime(void)
{
if (getTimer() == NULL)
{
LM_E(("getTimer() == NULL - calling exit function for library user"));
orionExitFunction(1, "getTimer() == NULL");
return -1;
}
return getTimer()->getCurrentTime();
}
/* ****************************************************************************
*
* toSeconds -
*/
long long toSeconds(int value, char what, bool dayPart)
{
long long result = -1;
if (dayPart == true)
{
if (what == 'Y')
result = 365L * 24 * 3600 * value;
else if (what == 'M')
result = 30 * 24 * 3600 * value;
else if (what == 'W')
result = 7 * 24 * 3600 * value;
else if (what == 'D')
result = 24 * 3600 * value;
}
else
{
if (what == 'H')
result = 3600 * value;
else if (what == 'M')
result = 60 * value;
else if (what == 'S')
result = value;
}
if (result == -1)
LM_E(("ERROR in duration string!"));
return result;
}
/*****************************************************************************
*
* parse8601 -
*
* This is common code for Duration and Throttling (at least)
*
*/
long long parse8601(std::string s)
{
if (s == "")
return 0;
char* duration = strdup(s.c_str());
char* toFree = duration;
bool dayPart = true;
long long accumulated = 0;
char* start;
if (*duration != 'P')
{
free(toFree);
return -1;
}
++duration;
start = duration;
while (*duration != 0)
{
if (isdigit(*duration))
++duration;
else if ((dayPart == true) && ((*duration == 'Y') || (*duration == 'M') || (*duration == 'D') || (*duration == 'W')))
{
char what = *duration;
*duration = 0;
int value = atoi(start);
accumulated += toSeconds(value, what, dayPart);
++duration;
start = duration;
}
else if ((dayPart == true) && (*duration == 'T'))
{
dayPart = false;
++duration;
start = duration;
}
else if ((dayPart == false) && ((*duration == 'H') || (*duration == 'M') || (*duration == 'S')))
{
char what = *duration;
*duration = 0;
int value = atoi(start);
accumulated += toSeconds(value, what, dayPart);
++duration;
start = duration;
}
else
{
free(toFree);
return -1; // ParseError
}
}
free(toFree);
return accumulated;
}
<commit_msg>Fixed a indentation error and some more 'L's for long<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <time.h>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/globals.h"
#include "common/sem.h"
#include "serviceRoutines/versionTreat.h" // For orionInit()
#include "mongoBackend/MongoGlobal.h" // For orionInit()
#include "ngsiNotify/onTimeIntervalThread.h" // For orionInit()
/* ****************************************************************************
*
* Globals
*/
static Timer* timer = NULL;
int startTime = -1;
int statisticsTime = -1;
OrionExitFunction orionExitFunction = NULL;
/* ****************************************************************************
*
* orionInit -
*/
void orionInit(OrionExitFunction exitFunction, const char* version)
{
// Give the rest library the correct version string of this executable
versionSet(version);
// The function to call on fatal error
orionExitFunction = exitFunction;
/* Initialize the semaphore used by mongoBackend */
semInit();
/* Set timer object (singleton) */
setTimer(new Timer());
/* Set notifier object (singleton) */
setNotifier(new Notifier());
/* Set start time */
startTime = getCurrentTime();
statisticsTime = startTime;
}
/* ****************************************************************************
*
* isTrue -
*/
bool isTrue(const std::string& s)
{
if (strcasecmp(s.c_str(), "true") == 0)
return true;
if (strcasecmp(s.c_str(), "yes") == 0)
return true;
return false;
}
/* ****************************************************************************
*
* isFalse -
*/
bool isFalse(const std::string& s)
{
if (strcasecmp(s.c_str(), "false") == 0)
return true;
if (strcasecmp(s.c_str(), "no") == 0)
return true;
return false;
}
/*****************************************************************************
*
* getTimer -
*/
Timer* getTimer() {
return timer;
}
/*****************************************************************************
*
* setTimer -
*/
void setTimer(Timer* t) {
timer = t;
}
/* ****************************************************************************
*
* getCurrentTime -
*/
int getCurrentTime(void)
{
if (getTimer() == NULL)
{
LM_E(("getTimer() == NULL - calling exit function for library user"));
orionExitFunction(1, "getTimer() == NULL");
return -1;
}
return getTimer()->getCurrentTime();
}
/* ****************************************************************************
*
* toSeconds -
*/
long long toSeconds(int value, char what, bool dayPart)
{
long long result = -1;
if (dayPart == true)
{
if (what == 'Y')
result = 365L * 24 * 3600 * value;
else if (what == 'M')
result = 30L * 24 * 3600 * value;
else if (what == 'W')
result = 7L * 24 * 3600 * value;
else if (what == 'D')
result = 24L * 3600 * value;
}
else
{
if (what == 'H')
result = 3600L * value;
else if (what == 'M')
result = 60L * value;
else if (what == 'S')
result = value;
}
if (result == -1)
LM_E(("ERROR in duration string!"));
return result;
}
/*****************************************************************************
*
* parse8601 -
*
* This is common code for Duration and Throttling (at least)
*
*/
long long parse8601(std::string s)
{
if (s == "")
return 0;
char* duration = strdup(s.c_str());
char* toFree = duration;
bool dayPart = true;
long long accumulated = 0;
char* start;
if (*duration != 'P')
{
free(toFree);
return -1;
}
++duration;
start = duration;
while (*duration != 0)
{
if (isdigit(*duration))
++duration;
else if ((dayPart == true) && ((*duration == 'Y') || (*duration == 'M') || (*duration == 'D') || (*duration == 'W')))
{
char what = *duration;
*duration = 0;
int value = atoi(start);
accumulated += toSeconds(value, what, dayPart);
++duration;
start = duration;
}
else if ((dayPart == true) && (*duration == 'T'))
{
dayPart = false;
++duration;
start = duration;
}
else if ((dayPart == false) && ((*duration == 'H') || (*duration == 'M') || (*duration == 'S')))
{
char what = *duration;
*duration = 0;
int value = atoi(start);
accumulated += toSeconds(value, what, dayPart);
++duration;
start = duration;
}
else
{
free(toFree);
return -1; // ParseError
}
}
free(toFree);
return accumulated;
}
<|endoftext|> |
<commit_before>//
// Name: LayerPropDlg.cpp
//
// Copyright (c) 2002 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#ifdef __GNUG__
#pragma implementation "LayerPropDlg.cpp"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "LayerPropDlg.h"
// WDR: class implementations
//----------------------------------------------------------------------------
// LayerPropDlg
//----------------------------------------------------------------------------
// WDR: event table for LayerPropDlg
BEGIN_EVENT_TABLE(LayerPropDlg,AutoDialog)
END_EVENT_TABLE()
LayerPropDlg::LayerPropDlg( wxWindow *parent, wxWindowID id, const wxString &title,
const wxPoint &position, const wxSize& size, long style ) :
AutoDialog( parent, id, title, position, size, style )
{
ElevPropDialogFunc( this, TRUE );
}
// WDR: handler implementations for LayerPropDlg
void LayerPropDlg::OnInitDialog(wxInitDialogEvent& event)
{
AddNumValidator(ID_LEFT, &m_fLeft);
AddNumValidator(ID_TOP, &m_fTop);
AddNumValidator(ID_RIGHT, &m_fRight);
AddNumValidator(ID_BOTTOM, &m_fBottom);
AddValidator(ID_PROPS, &m_strText);
wxDialog::OnInitDialog(event); // calls TransferDataToWindow()
}
<commit_msg>chg name of dialog fn to LayerPropDialogFunc<commit_after>//
// Name: LayerPropDlg.cpp
//
// Copyright (c) 2002 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#ifdef __GNUG__
#pragma implementation "LayerPropDlg.cpp"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "LayerPropDlg.h"
// WDR: class implementations
//----------------------------------------------------------------------------
// LayerPropDlg
//----------------------------------------------------------------------------
// WDR: event table for LayerPropDlg
BEGIN_EVENT_TABLE(LayerPropDlg,AutoDialog)
END_EVENT_TABLE()
LayerPropDlg::LayerPropDlg( wxWindow *parent, wxWindowID id, const wxString &title,
const wxPoint &position, const wxSize& size, long style ) :
AutoDialog( parent, id, title, position, size, style )
{
LayerPropDialogFunc( this, TRUE );
}
// WDR: handler implementations for LayerPropDlg
void LayerPropDlg::OnInitDialog(wxInitDialogEvent& event)
{
AddNumValidator(ID_LEFT, &m_fLeft);
AddNumValidator(ID_TOP, &m_fTop);
AddNumValidator(ID_RIGHT, &m_fRight);
AddNumValidator(ID_BOTTOM, &m_fBottom);
AddValidator(ID_PROPS, &m_strText);
wxDialog::OnInitDialog(event); // calls TransferDataToWindow()
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of the Qt Build Suite
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file.
** Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**************************************************************************/
#include "fileinfo.h"
#include <QtCore/QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <cassert>
#ifdef Q_OS_UNIX
#include <sys/stat.h>
#endif
namespace qbs {
QString FileInfo::fileName(const QString &fp)
{
int last = fp.lastIndexOf('/');
if (last < 0)
return fp;
return fp.mid(last + 1);
}
QString FileInfo::baseName(const QString &fp)
{
QString fn = fileName(fp);
int dot = fn.indexOf('.');
if (dot < 0)
return fp;
return fn.mid(0, dot);
}
QString FileInfo::completeBaseName(const QString &fp)
{
QString fn = fileName(fp);
int dot = fn.lastIndexOf('.');
if (dot < 0)
return fp;
return fn.mid(0, dot);
}
QString FileInfo::path(const QString &fp)
{
if (fp.isEmpty())
return QString();
if (fp.at(fp.size() - 1) == '/')
return fp;
int last = fp.lastIndexOf('/');
if (last < 0)
return ".";
return QDir::cleanPath(fp.mid(0, last));
}
bool FileInfo::exists(const QString &fp)
{
return FileInfo(fp).exists();
}
// from creator/src/shared/proparser/ioutils.cpp
bool FileInfo::isAbsolute(const QString &path)
{
if (path.startsWith(QLatin1Char('/')))
return true;
#ifdef Q_OS_WIN
if (path.startsWith(QLatin1Char('\\')))
return true;
// Unlike QFileInfo, this won't accept a relative path with a drive letter.
// Such paths result in a royal mess anyway ...
if (path.length() >= 3 && path.at(1) == QLatin1Char(':') && path.at(0).isLetter()
&& (path.at(2) == QLatin1Char('/') || path.at(2) == QLatin1Char('\\')))
return true;
#endif
return false;
}
QString FileInfo::resolvePath(const QString &base, const QString &rel)
{
if (isAbsolute(rel))
return rel;
if (rel == QLatin1String("."))
return base;
QString r = base;
if (!r.endsWith('/')) {
r.append('/');
}
r.append(rel);
return r;
}
bool FileInfo::globMatches(const QString &pattern, const QString &subject)
{
// ### the QRegExp wildcard matcher is slow!
//QRegExp rex(pattern, Qt::CaseSensitive, QRegExp::Wildcard);
//return rex.exactMatch(subject);
return subject.endsWith(pattern.mid(1), Qt::CaseInsensitive);
}
static QString resolveSymlinks(const QString &fileName)
{
QFileInfo fi(fileName);
while (fi.isSymLink())
fi.setFile(fi.symLinkTarget());
return fi.absoluteFilePath();
}
#if defined(Q_OS_WIN)
#include <qt_windows.h>
#define z(x) reinterpret_cast<WIN32_FILE_ATTRIBUTE_DATA*>(const_cast<FileInfo::InternalStatType*>(&x))
template<bool> struct CompileTimeAssert;
template<> struct CompileTimeAssert<true> {};
FileInfo::FileInfo(const QString &fileName)
{
static CompileTimeAssert<
sizeof(FileInfo::InternalStatType) == sizeof(WIN32_FILE_ATTRIBUTE_DATA)
> internal_type_has_wrong_size;
if (!GetFileAttributesEx(reinterpret_cast<const WCHAR*>(fileName.utf16()),
GetFileExInfoStandard, &m_stat))
{
z(m_stat)->dwFileAttributes = INVALID_FILE_ATTRIBUTES;
}
}
bool FileInfo::exists() const
{
return z(m_stat)->dwFileAttributes != INVALID_FILE_ATTRIBUTES;
}
FileTime FileInfo::lastModified() const
{
return FileTime(*reinterpret_cast<const FileTime::InternalType*>(
&z(m_stat)->ftLastWriteTime));
}
QString applicationDirPath()
{
static const QString appDirPath = FileInfo::path(resolveSymlinks(QCoreApplication::applicationFilePath()));
return appDirPath;
}
#elif defined(Q_OS_UNIX)
FileInfo::FileInfo(const QString &fileName)
{
if (stat(fileName.toLocal8Bit(), &m_stat) == -1)
m_stat.st_mtime = 0;
}
bool FileInfo::exists() const
{
return m_stat.st_mtime != 0;
}
FileTime FileInfo::lastModified() const
{
return m_stat.st_mtime;
}
QString applicationDirPath()
{
return QCoreApplication::applicationDirPath();
}
#endif
// adapted from qtc/plugins/vcsbase/cleandialog.cpp
static bool removeFileRecursion(const QFileInfo &f, QString *errorMessage)
{
if (!f.exists())
return true;
if (f.isDir()) {
const QDir dir(f.absoluteFilePath());
foreach(const QFileInfo &fi, dir.entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden))
removeFileRecursion(fi, errorMessage);
QDir parent = f.absoluteDir();
if (!parent.rmdir(f.fileName())) {
errorMessage->append(FileInfo::tr("The directory %1 could not be deleted.").
arg(QDir::toNativeSeparators(f.absoluteFilePath())));
return false;
}
} else if (!QFile::remove(f.absoluteFilePath())) {
if (!errorMessage->isEmpty())
errorMessage->append(QLatin1Char('\n'));
errorMessage->append(FileInfo::tr("The file %1 could not be deleted.").
arg(QDir::toNativeSeparators(f.absoluteFilePath())));
return false;
}
return true;
}
bool removeDirectoryWithContents(const QString &path, QString *errorMessage)
{
QFileInfo f(path);
if (f.exists() && !f.isDir()) {
*errorMessage = FileInfo::tr("%1 is not a directory.").arg(QDir::toNativeSeparators(path));
return false;
}
return removeFileRecursion(f, errorMessage);
}
QString qbsRootPath()
{
return QDir::cleanPath(applicationDirPath() + QLatin1String("/../"));
}
}
<commit_msg>use QLatin1Char when appropriate<commit_after>/**************************************************************************
**
** This file is part of the Qt Build Suite
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file.
** Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**************************************************************************/
#include "fileinfo.h"
#include <QtCore/QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <cassert>
#ifdef Q_OS_UNIX
#include <sys/stat.h>
#endif
namespace qbs {
QString FileInfo::fileName(const QString &fp)
{
int last = fp.lastIndexOf('/');
if (last < 0)
return fp;
return fp.mid(last + 1);
}
QString FileInfo::baseName(const QString &fp)
{
QString fn = fileName(fp);
int dot = fn.indexOf('.');
if (dot < 0)
return fp;
return fn.mid(0, dot);
}
QString FileInfo::completeBaseName(const QString &fp)
{
QString fn = fileName(fp);
int dot = fn.lastIndexOf('.');
if (dot < 0)
return fp;
return fn.mid(0, dot);
}
QString FileInfo::path(const QString &fp)
{
if (fp.isEmpty())
return QString();
if (fp.at(fp.size() - 1) == '/')
return fp;
int last = fp.lastIndexOf('/');
if (last < 0)
return ".";
return QDir::cleanPath(fp.mid(0, last));
}
bool FileInfo::exists(const QString &fp)
{
return FileInfo(fp).exists();
}
// from creator/src/shared/proparser/ioutils.cpp
bool FileInfo::isAbsolute(const QString &path)
{
if (path.startsWith(QLatin1Char('/')))
return true;
#ifdef Q_OS_WIN
if (path.startsWith(QLatin1Char('\\')))
return true;
// Unlike QFileInfo, this won't accept a relative path with a drive letter.
// Such paths result in a royal mess anyway ...
if (path.length() >= 3 && path.at(1) == QLatin1Char(':') && path.at(0).isLetter()
&& (path.at(2) == QLatin1Char('/') || path.at(2) == QLatin1Char('\\')))
return true;
#endif
return false;
}
QString FileInfo::resolvePath(const QString &base, const QString &rel)
{
if (isAbsolute(rel))
return rel;
if (rel.size() == 1 && rel.at(0) == QLatin1Char('.'))
return base;
QString r = base;
if (!r.endsWith(QLatin1Char('/')))
r.append(QLatin1Char('/'));
r.append(rel);
return r;
}
bool FileInfo::globMatches(const QString &pattern, const QString &subject)
{
// ### the QRegExp wildcard matcher is slow!
//QRegExp rex(pattern, Qt::CaseSensitive, QRegExp::Wildcard);
//return rex.exactMatch(subject);
return subject.endsWith(pattern.mid(1), Qt::CaseInsensitive);
}
static QString resolveSymlinks(const QString &fileName)
{
QFileInfo fi(fileName);
while (fi.isSymLink())
fi.setFile(fi.symLinkTarget());
return fi.absoluteFilePath();
}
#if defined(Q_OS_WIN)
#include <qt_windows.h>
#define z(x) reinterpret_cast<WIN32_FILE_ATTRIBUTE_DATA*>(const_cast<FileInfo::InternalStatType*>(&x))
template<bool> struct CompileTimeAssert;
template<> struct CompileTimeAssert<true> {};
FileInfo::FileInfo(const QString &fileName)
{
static CompileTimeAssert<
sizeof(FileInfo::InternalStatType) == sizeof(WIN32_FILE_ATTRIBUTE_DATA)
> internal_type_has_wrong_size;
if (!GetFileAttributesEx(reinterpret_cast<const WCHAR*>(fileName.utf16()),
GetFileExInfoStandard, &m_stat))
{
z(m_stat)->dwFileAttributes = INVALID_FILE_ATTRIBUTES;
}
}
bool FileInfo::exists() const
{
return z(m_stat)->dwFileAttributes != INVALID_FILE_ATTRIBUTES;
}
FileTime FileInfo::lastModified() const
{
return FileTime(*reinterpret_cast<const FileTime::InternalType*>(
&z(m_stat)->ftLastWriteTime));
}
QString applicationDirPath()
{
static const QString appDirPath = FileInfo::path(resolveSymlinks(QCoreApplication::applicationFilePath()));
return appDirPath;
}
#elif defined(Q_OS_UNIX)
FileInfo::FileInfo(const QString &fileName)
{
if (stat(fileName.toLocal8Bit(), &m_stat) == -1)
m_stat.st_mtime = 0;
}
bool FileInfo::exists() const
{
return m_stat.st_mtime != 0;
}
FileTime FileInfo::lastModified() const
{
return m_stat.st_mtime;
}
QString applicationDirPath()
{
return QCoreApplication::applicationDirPath();
}
#endif
// adapted from qtc/plugins/vcsbase/cleandialog.cpp
static bool removeFileRecursion(const QFileInfo &f, QString *errorMessage)
{
if (!f.exists())
return true;
if (f.isDir()) {
const QDir dir(f.absoluteFilePath());
foreach(const QFileInfo &fi, dir.entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden))
removeFileRecursion(fi, errorMessage);
QDir parent = f.absoluteDir();
if (!parent.rmdir(f.fileName())) {
errorMessage->append(FileInfo::tr("The directory %1 could not be deleted.").
arg(QDir::toNativeSeparators(f.absoluteFilePath())));
return false;
}
} else if (!QFile::remove(f.absoluteFilePath())) {
if (!errorMessage->isEmpty())
errorMessage->append(QLatin1Char('\n'));
errorMessage->append(FileInfo::tr("The file %1 could not be deleted.").
arg(QDir::toNativeSeparators(f.absoluteFilePath())));
return false;
}
return true;
}
bool removeDirectoryWithContents(const QString &path, QString *errorMessage)
{
QFileInfo f(path);
if (f.exists() && !f.isDir()) {
*errorMessage = FileInfo::tr("%1 is not a directory.").arg(QDir::toNativeSeparators(path));
return false;
}
return removeFileRecursion(f, errorMessage);
}
QString qbsRootPath()
{
return QDir::cleanPath(applicationDirPath() + QLatin1String("/../"));
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 Andrew Toulouse.
// Distributed under the MIT License.
#include "Block.h"
#include <fstream>
#include <cassert>
#include <cstring>
namespace libol {
bool get_bit(uint8_t byte, int n) {
return (byte >> (7 - n)) & 1;
}
Block::Stream Block::createStream(size_t offset) {
Stream stream(*this, offset);
return stream;
}
Block Block::decode(std::ifstream& ifs, Block* previous) {
Block block;
uint8_t marker = ifs.get();
// Bit 1: Time format
block.time.isAbsolute = get_bit(marker, 0);
if(block.time.isAbsolute) {
block.time.diff = ifs.get();
} else {
ifs.read(reinterpret_cast<char*>(&block.time.absolute), sizeof(block.time.absolute));
}
// Bit 4: Size size
if(get_bit(marker, 3)) {
block.size = (unsigned) ifs.get();
} else {
ifs.read(reinterpret_cast<char*>(&block.size), sizeof(block.size));
}
// Bit 2: Has type
block.hasExplicitType = !get_bit(marker, 1);
if(block.hasExplicitType) {
block.type = ifs.get();
} else {
if(previous != nullptr) {
block.type = previous->type;
} else {
std::cout << "typeless block as first block" << std::endl;
exit(1);
}
}
// Bit 3: Blockdata size
block.param.is32 = !get_bit(marker, 2);
if(block.param.is32) {
ifs.read(reinterpret_cast<char*>(&block.param.value32), sizeof(block.param.value32));
} else {
block.param.value8 = ifs.get();
}
// Read content
block.content.resize(block.size);
ifs.read(reinterpret_cast<char*>(block.content.data()), block.size);
return block;
}
}
<commit_msg>Fix block time<commit_after>// Copyright (c) 2014 Andrew Toulouse.
// Distributed under the MIT License.
#include "Block.h"
#include <fstream>
#include <cassert>
#include <cstring>
namespace libol {
bool get_bit(uint8_t byte, int n) {
return (byte >> (7 - n)) & 1;
}
Block::Stream Block::createStream(size_t offset) {
Stream stream(*this, offset);
return stream;
}
Block Block::decode(std::ifstream& ifs, Block* previous) {
Block block;
uint8_t marker = ifs.get();
// Bit 1: Time format
block.time.isAbsolute = !get_bit(marker, 0);
if(block.time.isAbsolute) {
ifs.read(reinterpret_cast<char*>(&block.time.absolute), sizeof(block.time.absolute));
} else {
block.time.diff = ifs.get();
}
// Bit 4: Size size
if(get_bit(marker, 3)) {
block.size = (unsigned) ifs.get();
} else {
ifs.read(reinterpret_cast<char*>(&block.size), sizeof(block.size));
}
// Bit 2: Has type
block.hasExplicitType = !get_bit(marker, 1);
if(block.hasExplicitType) {
block.type = ifs.get();
} else {
if(previous != nullptr) {
block.type = previous->type;
} else {
std::cout << "typeless block as first block" << std::endl;
exit(1);
}
}
// Bit 3: Blockdata size
block.param.is32 = !get_bit(marker, 2);
if(block.param.is32) {
ifs.read(reinterpret_cast<char*>(&block.param.value32), sizeof(block.param.value32));
} else {
block.param.value8 = ifs.get();
}
// Read content
block.content.resize(block.size);
ifs.read(reinterpret_cast<char*>(block.content.data()), block.size);
return block;
}
}
<|endoftext|> |
<commit_before>#include "expr-to-xml.hh"
#include "xml-writer.hh"
#include "nixexpr-ast.hh"
#include "aterm.hh"
#include "util.hh"
namespace nix {
static XMLAttrs singletonAttrs(const string & name, const string & value)
{
XMLAttrs attrs;
attrs[name] = value;
return attrs;
}
static void printTermAsXML(Expr e, XMLWriter & doc, PathSet & context)
{
XMLAttrs attrs;
string s;
ATerm s2;
int i;
ATermList as, es, formals;
ATerm body, pos;
checkInterrupt();
if (matchStr(e, s, context)) /* !!! show the context? */
doc.writeEmptyElement("string", singletonAttrs("value", s));
else if (matchPath(e, s2))
doc.writeEmptyElement("path", singletonAttrs("value", aterm2String(s2)));
else if (matchNull(e))
doc.writeEmptyElement("null");
else if (matchInt(e, i))
doc.writeEmptyElement("int", singletonAttrs("value", (format("%1%") % i).str()));
else if (e == eTrue)
doc.writeEmptyElement("bool", singletonAttrs("value", "true"));
else if (e == eFalse)
doc.writeEmptyElement("bool", singletonAttrs("value", "false"));
else if (matchAttrs(e, as)) {
XMLOpenElement _(doc, "attrs");
ATermMap attrs;
queryAllAttrs(e, attrs);
StringSet names;
for (ATermMap::const_iterator i = attrs.begin(); i != attrs.end(); ++i)
names.insert(aterm2String(i->key));
for (StringSet::iterator i = names.begin(); i != names.end(); ++i) {
XMLOpenElement _(doc, "attr", singletonAttrs("name", *i));
printTermAsXML(attrs.get(toATerm(*i)), doc, context);
}
}
else if (matchList(e, es)) {
XMLOpenElement _(doc, "list");
for (ATermIterator i(es); i; ++i)
printTermAsXML(*i, doc, context);
}
else if (matchFunction(e, formals, body, pos)) {
XMLOpenElement _(doc, "function");
for (ATermIterator i(formals); i; ++i) {
Expr name; ValidValues valids; ATerm dummy;
if (!matchFormal(*i, name, valids, dummy)) abort();
XMLOpenElement _(doc, "arg", singletonAttrs("name", aterm2String(name)));
ATermList valids2;
if (matchValidValues(valids, valids2)) {
for (ATermIterator j(valids2); j; ++j) {
XMLOpenElement _(doc, "value");
printTermAsXML(*j, doc, context);
}
}
}
}
else
doc.writeEmptyElement("unevaluated");
}
void printTermAsXML(Expr e, std::ostream & out, PathSet & context)
{
XMLWriter doc(true, out);
XMLOpenElement root(doc, "expr");
printTermAsXML(e, doc, context);
}
}
<commit_msg>* printTermAsXML: treat derivations specially; emit an element <derivation outPath=... drvPath=...> attrs </derivation>. Only emit the attributes of any specific derivation only. This prevents exponententially large XML output due to the absense of sharing.<commit_after>#include "expr-to-xml.hh"
#include "xml-writer.hh"
#include "nixexpr-ast.hh"
#include "aterm.hh"
#include "util.hh"
namespace nix {
static XMLAttrs singletonAttrs(const string & name, const string & value)
{
XMLAttrs attrs;
attrs[name] = value;
return attrs;
}
/* set<Expr> is safe because all the expressions are also reachable
from the stack, therefore can't be garbage-collected. */
typedef set<Expr> ExprSet;
static void printTermAsXML(Expr e, XMLWriter & doc, PathSet & context,
ExprSet & drvsSeen);
static void showAttrs(const ATermMap & attrs, XMLWriter & doc,
PathSet & context, ExprSet & drvsSeen)
{
StringSet names;
for (ATermMap::const_iterator i = attrs.begin(); i != attrs.end(); ++i)
names.insert(aterm2String(i->key));
for (StringSet::iterator i = names.begin(); i != names.end(); ++i) {
XMLOpenElement _(doc, "attr", singletonAttrs("name", *i));
printTermAsXML(attrs.get(toATerm(*i)), doc, context, drvsSeen);
}
}
static void printTermAsXML(Expr e, XMLWriter & doc, PathSet & context,
ExprSet & drvsSeen)
{
XMLAttrs attrs;
string s;
ATerm s2;
int i;
ATermList as, es, formals;
ATerm body, pos;
checkInterrupt();
if (matchStr(e, s, context)) /* !!! show the context? */
doc.writeEmptyElement("string", singletonAttrs("value", s));
else if (matchPath(e, s2))
doc.writeEmptyElement("path", singletonAttrs("value", aterm2String(s2)));
else if (matchNull(e))
doc.writeEmptyElement("null");
else if (matchInt(e, i))
doc.writeEmptyElement("int", singletonAttrs("value", (format("%1%") % i).str()));
else if (e == eTrue)
doc.writeEmptyElement("bool", singletonAttrs("value", "true"));
else if (e == eFalse)
doc.writeEmptyElement("bool", singletonAttrs("value", "false"));
else if (matchAttrs(e, as)) {
ATermMap attrs;
queryAllAttrs(e, attrs);
Expr a = attrs.get(toATerm("type"));
if (a && matchStr(a, s, context) && s == "derivation") {
XMLAttrs xmlAttrs;
Path outPath, drvPath;
a = attrs.get(toATerm("drvPath"));
if (matchStr(a, drvPath, context))
xmlAttrs["drvPath"] = drvPath;
a = attrs.get(toATerm("outPath"));
if (matchStr(a, outPath, context))
xmlAttrs["outPath"] = outPath;
XMLOpenElement _(doc, "derivation", xmlAttrs);
if (drvsSeen.find(e) == drvsSeen.end()) {
drvsSeen.insert(e);
showAttrs(attrs, doc, context, drvsSeen);
} else
doc.writeEmptyElement("repeated");
}
else {
XMLOpenElement _(doc, "attrs");
showAttrs(attrs, doc, context, drvsSeen);
}
}
else if (matchList(e, es)) {
XMLOpenElement _(doc, "list");
for (ATermIterator i(es); i; ++i)
printTermAsXML(*i, doc, context, drvsSeen);
}
else if (matchFunction(e, formals, body, pos)) {
XMLOpenElement _(doc, "function");
for (ATermIterator i(formals); i; ++i) {
Expr name; ValidValues valids; ATerm dummy;
if (!matchFormal(*i, name, valids, dummy)) abort();
XMLOpenElement _(doc, "arg", singletonAttrs("name", aterm2String(name)));
ATermList valids2;
if (matchValidValues(valids, valids2)) {
for (ATermIterator j(valids2); j; ++j) {
XMLOpenElement _(doc, "value");
printTermAsXML(*j, doc, context, drvsSeen);
}
}
}
}
else
doc.writeEmptyElement("unevaluated");
}
void printTermAsXML(Expr e, std::ostream & out, PathSet & context)
{
XMLWriter doc(true, out);
XMLOpenElement root(doc, "expr");
ExprSet drvsSeen;
printTermAsXML(e, doc, context, drvsSeen);
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <vector>
#include <memory>
#include <string>
#include "util/sstream.h"
#include "library/scoped_ext.h"
namespace lean {
typedef std::tuple<push_scope_fn, pop_scope_fn> entry;
typedef std::vector<entry> scoped_exts;
static scoped_exts * g_exts = nullptr;
static scoped_exts & get_exts() { return *g_exts; }
void register_scoped_ext(push_scope_fn push, pop_scope_fn pop) {
get_exts().emplace_back(push, pop);
}
struct scope_mng_ext : public environment_extension {
name_set m_namespace_set; // all namespaces registered in the system
name_set m_opened_namespaces; // set of namespaces marked as "open"
list<name> m_namespaces; // stack of namespaces/sections
list<name> m_headers; // namespace/section header
list<scope_kind> m_scope_kinds;
};
struct scope_mng_ext_reg {
unsigned m_ext_id;
scope_mng_ext_reg() { m_ext_id = environment::register_extension(std::make_shared<scope_mng_ext>()); }
};
static scope_mng_ext_reg * g_ext = nullptr;
static scope_mng_ext const & get_extension(environment const & env) {
return static_cast<scope_mng_ext const &>(env.get_extension(g_ext->m_ext_id));
}
static environment update(environment const & env, scope_mng_ext const & ext) {
return env.update(g_ext->m_ext_id, std::make_shared<scope_mng_ext>(ext));
}
name const & get_namespace(environment const & env) {
scope_mng_ext const & ext = get_extension(env);
return !is_nil(ext.m_namespaces) ? head(ext.m_namespaces) : name::anonymous();
}
list<name> const & get_namespaces(environment const & env) {
return get_extension(env).m_namespaces;
}
bool in_section(environment const & env) {
scope_mng_ext const & ext = get_extension(env);
return !is_nil(ext.m_scope_kinds) && head(ext.m_scope_kinds) == scope_kind::Section;
}
environment mark_namespace_as_open(environment const & env, name const & n) {
scope_mng_ext ext = get_extension(env);
ext.m_opened_namespaces.insert(n);
return update(env, ext);
}
name_set get_opened_namespaces(environment const & env) {
return get_extension(env).m_opened_namespaces;
}
optional<name> to_valid_namespace_name(environment const & env, name const & n) {
scope_mng_ext const & ext = get_extension(env);
if (ext.m_namespace_set.contains(n))
return optional<name>(n);
for (auto const & ns : ext.m_namespaces) {
name r = ns + n;
if (ext.m_namespace_set.contains(r))
return optional<name>(r);
}
return optional<name>();
}
std::vector<name> get_namespace_completion_candidates(environment const & env) {
std::vector<name> ret;
scope_mng_ext const & ext = get_extension(env);
ext.m_namespace_set.for_each([&](name const & ns) {
ret.push_back(ns);
for (auto const & open_ns : ext.m_namespaces)
if (open_ns != ns && is_prefix_of(open_ns, ns))
ret.push_back(ns.replace_prefix(open_ns, {}));
});
return ret;
}
struct new_namespace_modification : public modification {
LEAN_MODIFICATION("nspace")
name m_ns;
new_namespace_modification(name const & ns) : m_ns(ns) {}
new_namespace_modification() {}
void perform(environment & env) const override {
scope_mng_ext ext = get_extension(env);
ext.m_namespace_set.insert(m_ns);
env = update(env, ext);
}
void serialize(serializer & s) const override {
s << m_ns;
}
static std::shared_ptr<modification const> deserialize(deserializer & d) {
name n;
d >> n;
return std::make_shared<new_namespace_modification>(n);
}
};
environment add_namespace(environment const & env, name const & ns) {
scope_mng_ext ext = get_extension(env);
if (!ext.m_namespace_set.contains(ns)) {
ext.m_namespace_set.insert(ns);
environment r = update(env, ext);
r = module::add(r, std::make_shared<new_namespace_modification>(ns));
if (ns.is_atomic())
return r;
else
return add_namespace(r, ns.get_prefix());
} else {
return env;
}
}
environment push_scope(environment const & env, io_state const & ios, scope_kind k, name const & n) {
if (k == scope_kind::Namespace && in_section(env))
throw exception("invalid namespace declaration, a namespace cannot be declared inside a section");
name new_n = get_namespace(env);
if (k == scope_kind::Namespace)
new_n = new_n + n;
scope_mng_ext ext = get_extension(env);
bool save_ns = false;
if (!ext.m_namespace_set.contains(new_n)) {
save_ns = true;
ext.m_namespace_set.insert(new_n);
}
ext.m_namespaces = cons(new_n, ext.m_namespaces);
ext.m_headers = cons(n, ext.m_headers);
ext.m_scope_kinds = cons(k, ext.m_scope_kinds);
environment r = update(env, ext);
for (auto const & t : get_exts()) {
r = std::get<0>(t)(r, ios, k);
}
if (save_ns)
r = module::add(r, std::make_shared<new_namespace_modification>(new_n));
return r;
}
environment pop_scope_core(environment const & env, io_state const & ios) {
scope_mng_ext ext = get_extension(env);
if (is_nil(ext.m_namespaces))
return env;
scope_kind k = head(ext.m_scope_kinds);
ext.m_namespaces = tail(ext.m_namespaces);
ext.m_headers = tail(ext.m_headers);
ext.m_scope_kinds = tail(ext.m_scope_kinds);
environment r = update(env, ext);
for (auto const & t : get_exts()) {
r = std::get<1>(t)(r, ios, k);
}
return r;
}
environment pop_scope(environment const & env, io_state const & ios, name const & n) {
scope_mng_ext ext = get_extension(env);
if (is_nil(ext.m_namespaces))
throw exception("invalid end of scope, there are no open namespaces/sections");
if (n != head(ext.m_headers))
throw exception(sstream() << "invalid end of scope, begin/end mistmatch, scope starts with '"
<< head(ext.m_headers) << "', and ends with '" << n << "'");
return pop_scope_core(env, ios);
}
bool has_open_scopes(environment const & env) {
scope_mng_ext ext = get_extension(env);
return !is_nil(ext.m_namespaces);
}
void initialize_scoped_ext() {
g_exts = new scoped_exts();
g_ext = new scope_mng_ext_reg();
new_namespace_modification::init();
}
void finalize_scoped_ext() {
new_namespace_modification::finalize();
delete g_exts;
delete g_ext;
}
}
<commit_msg>fix(library/scoped_ext): typo in error message<commit_after>/*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <vector>
#include <memory>
#include <string>
#include "util/sstream.h"
#include "library/scoped_ext.h"
namespace lean {
typedef std::tuple<push_scope_fn, pop_scope_fn> entry;
typedef std::vector<entry> scoped_exts;
static scoped_exts * g_exts = nullptr;
static scoped_exts & get_exts() { return *g_exts; }
void register_scoped_ext(push_scope_fn push, pop_scope_fn pop) {
get_exts().emplace_back(push, pop);
}
struct scope_mng_ext : public environment_extension {
name_set m_namespace_set; // all namespaces registered in the system
name_set m_opened_namespaces; // set of namespaces marked as "open"
list<name> m_namespaces; // stack of namespaces/sections
list<name> m_headers; // namespace/section header
list<scope_kind> m_scope_kinds;
};
struct scope_mng_ext_reg {
unsigned m_ext_id;
scope_mng_ext_reg() { m_ext_id = environment::register_extension(std::make_shared<scope_mng_ext>()); }
};
static scope_mng_ext_reg * g_ext = nullptr;
static scope_mng_ext const & get_extension(environment const & env) {
return static_cast<scope_mng_ext const &>(env.get_extension(g_ext->m_ext_id));
}
static environment update(environment const & env, scope_mng_ext const & ext) {
return env.update(g_ext->m_ext_id, std::make_shared<scope_mng_ext>(ext));
}
name const & get_namespace(environment const & env) {
scope_mng_ext const & ext = get_extension(env);
return !is_nil(ext.m_namespaces) ? head(ext.m_namespaces) : name::anonymous();
}
list<name> const & get_namespaces(environment const & env) {
return get_extension(env).m_namespaces;
}
bool in_section(environment const & env) {
scope_mng_ext const & ext = get_extension(env);
return !is_nil(ext.m_scope_kinds) && head(ext.m_scope_kinds) == scope_kind::Section;
}
environment mark_namespace_as_open(environment const & env, name const & n) {
scope_mng_ext ext = get_extension(env);
ext.m_opened_namespaces.insert(n);
return update(env, ext);
}
name_set get_opened_namespaces(environment const & env) {
return get_extension(env).m_opened_namespaces;
}
optional<name> to_valid_namespace_name(environment const & env, name const & n) {
scope_mng_ext const & ext = get_extension(env);
if (ext.m_namespace_set.contains(n))
return optional<name>(n);
for (auto const & ns : ext.m_namespaces) {
name r = ns + n;
if (ext.m_namespace_set.contains(r))
return optional<name>(r);
}
return optional<name>();
}
std::vector<name> get_namespace_completion_candidates(environment const & env) {
std::vector<name> ret;
scope_mng_ext const & ext = get_extension(env);
ext.m_namespace_set.for_each([&](name const & ns) {
ret.push_back(ns);
for (auto const & open_ns : ext.m_namespaces)
if (open_ns != ns && is_prefix_of(open_ns, ns))
ret.push_back(ns.replace_prefix(open_ns, {}));
});
return ret;
}
struct new_namespace_modification : public modification {
LEAN_MODIFICATION("nspace")
name m_ns;
new_namespace_modification(name const & ns) : m_ns(ns) {}
new_namespace_modification() {}
void perform(environment & env) const override {
scope_mng_ext ext = get_extension(env);
ext.m_namespace_set.insert(m_ns);
env = update(env, ext);
}
void serialize(serializer & s) const override {
s << m_ns;
}
static std::shared_ptr<modification const> deserialize(deserializer & d) {
name n;
d >> n;
return std::make_shared<new_namespace_modification>(n);
}
};
environment add_namespace(environment const & env, name const & ns) {
scope_mng_ext ext = get_extension(env);
if (!ext.m_namespace_set.contains(ns)) {
ext.m_namespace_set.insert(ns);
environment r = update(env, ext);
r = module::add(r, std::make_shared<new_namespace_modification>(ns));
if (ns.is_atomic())
return r;
else
return add_namespace(r, ns.get_prefix());
} else {
return env;
}
}
environment push_scope(environment const & env, io_state const & ios, scope_kind k, name const & n) {
if (k == scope_kind::Namespace && in_section(env))
throw exception("invalid namespace declaration, a namespace cannot be declared inside a section");
name new_n = get_namespace(env);
if (k == scope_kind::Namespace)
new_n = new_n + n;
scope_mng_ext ext = get_extension(env);
bool save_ns = false;
if (!ext.m_namespace_set.contains(new_n)) {
save_ns = true;
ext.m_namespace_set.insert(new_n);
}
ext.m_namespaces = cons(new_n, ext.m_namespaces);
ext.m_headers = cons(n, ext.m_headers);
ext.m_scope_kinds = cons(k, ext.m_scope_kinds);
environment r = update(env, ext);
for (auto const & t : get_exts()) {
r = std::get<0>(t)(r, ios, k);
}
if (save_ns)
r = module::add(r, std::make_shared<new_namespace_modification>(new_n));
return r;
}
environment pop_scope_core(environment const & env, io_state const & ios) {
scope_mng_ext ext = get_extension(env);
if (is_nil(ext.m_namespaces))
return env;
scope_kind k = head(ext.m_scope_kinds);
ext.m_namespaces = tail(ext.m_namespaces);
ext.m_headers = tail(ext.m_headers);
ext.m_scope_kinds = tail(ext.m_scope_kinds);
environment r = update(env, ext);
for (auto const & t : get_exts()) {
r = std::get<1>(t)(r, ios, k);
}
return r;
}
environment pop_scope(environment const & env, io_state const & ios, name const & n) {
scope_mng_ext ext = get_extension(env);
if (is_nil(ext.m_namespaces))
throw exception("invalid end of scope, there are no open namespaces/sections");
if (n != head(ext.m_headers))
throw exception(sstream() << "invalid end of scope, begin/end mismatch, scope starts with '"
<< head(ext.m_headers) << "', and ends with '" << n << "'");
return pop_scope_core(env, ios);
}
bool has_open_scopes(environment const & env) {
scope_mng_ext ext = get_extension(env);
return !is_nil(ext.m_namespaces);
}
void initialize_scoped_ext() {
g_exts = new scoped_exts();
g_ext = new scope_mng_ext_reg();
new_namespace_modification::init();
}
void finalize_scoped_ext() {
new_namespace_modification::finalize();
delete g_exts;
delete g_ext;
}
}
<|endoftext|> |
<commit_before>#include "robocup-py.hpp"
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <string>
#include <sstream>
#include <iostream>
using namespace boost::python;
#include <Geometry2d/Point.hpp>
#include <Geometry2d/Rect.hpp>
#include <Geometry2d/CompositeShape.hpp>
#include <Robot.hpp>
#include <SystemState.hpp>
#include <protobuf/LogFrame.pb.h>
// this is here so boost can work with std::shared_ptr
template<class T> T * get_pointer( std::shared_ptr<T> const& p) {
return p.get();
}
std::string Point_repr(Geometry2d::Point *self) {
std::ostringstream ss;
ss << "Point(";
ss << self->x;
ss << ", ";
ss << self->y;
ss << ")";
std::string repr(ss.str());
return repr;
}
std::string Robot_repr(Robot *self) {
std::ostringstream ss;
ss << "<Robot ";
ss << (self->self() ? "us[" : "them[");
ss << self->shell();
ss << "], pos=";
ss << Point_repr(&(self->pos));
ss << ">";
std::string repr(ss.str());
return repr;
}
void OurRobot_move_to(OurRobot *self, Geometry2d::Point *to) {
self->move(*to);
}
void OurRobot_set_avoid_ball_radius(OurRobot *self, float radius) {
self->avoidBallRadius(radius);
}
void OurRobot_approach_opponent(OurRobot *self, unsigned shell_id, bool enable_approach) {
self->approachOpponent(shell_id, enable_approach);
}
void OutRobot_add_text(OurRobot *self, const std::string &text, boost::python::tuple rgb, const std::string &layerPrefix) {
float r = extract<float>(rgb[0]);
float g = extract<float>(rgb[1]);
float b = extract<float>(rgb[2]);
self->addText(QString::fromStdString(text), QColor(r,g,b), QString::fromStdString(layerPrefix));
}
bool Rect_contains_rect(Geometry2d::Rect *self, Geometry2d::Rect *other) {
return self->contains(*other);
}
bool Rect_contains_point(Geometry2d::Rect *self, Geometry2d::Point *pt) {
return self->contains(*pt);
}
void Point_rotate(Geometry2d::Point *self, Geometry2d::Point *origin, float angle) {
self->rotate(*origin, angle);
}
void CompositeShape_add_shape(Geometry2d::CompositeShape *self, Geometry2d::Shape *shape) {
self->add(std::shared_ptr<Geometry2d::Shape>( shape->clone() ));
}
boost::python::tuple Line_wrap_pt(Geometry2d::Line *self) {
boost::python::list a;
for (int i = 0; i < 2; i++) {
a.append(self->pt[i]);
}
return boost::python::tuple(a);
}
void State_draw_circle(SystemState *self, const Geometry2d::Point *center, float radius, boost::python::tuple rgb, const std::string &layer) {
float r = extract<float>(rgb[0]);
float g = extract<float>(rgb[1]);
float b = extract<float>(rgb[2]);
self->drawCircle(*center, radius, QColor(r,g,b), QString::fromStdString(layer));
}
// returns None or a Geometry2d::Point
boost::python::object Line_line_intersection(Geometry2d::Line *self, Geometry2d::Line *other) {
Geometry2d::Point pt;
if (self->intersects(*other, &pt)) {
boost::python::object obj(pt);
return obj;
} else {
// return None
return boost::python::object();
}
};
void State_draw_line(SystemState *self, const Geometry2d::Line *line, boost::python::tuple rgb, const std::string &layer) {
float r = extract<float>(rgb[0]);
float g = extract<float>(rgb[1]);
float b = extract<float>(rgb[2]);
self->drawLine(*line, QColor(r, g, b), QString::fromStdString(layer));
}
/**
* The code in this block wraps up c++ classes and makes them
* accessible to python in the 'robocup' module.
*/
BOOST_PYTHON_MODULE(robocup)
{
class_<Geometry2d::Point>("Point", init<float, float>())
.def(init<const Geometry2d::Point &>())
.def_readwrite("x", &Geometry2d::Point::x)
.def_readwrite("y", &Geometry2d::Point::y)
.def(self - self)
.def(self + self)
.def("mag", &Geometry2d::Point::mag)
.def("magsq", &Geometry2d::Point::magsq)
.def("__repr__", &Point_repr)
.def("normalized", &Geometry2d::Point::normalized)
.def("rotate", &Point_rotate)
.def(self * float())
.def(self / float())
.def("perp_ccw", &Geometry2d::Point::perpCCW)
.def("perp_cw", &Geometry2d::Point::perpCW)
.def("angle", &Geometry2d::Point::angle)
.def("dot", &Geometry2d::Point::dot)
.def("near_point", &Geometry2d::Point::nearPoint)
;
class_<Geometry2d::Line, Geometry2d::Line*>("Line", init<Geometry2d::Point, Geometry2d::Point>())
.add_property("pt", Line_wrap_pt)
.def("delta", &Geometry2d::Line::delta)
.def("line_intersection", &Line_line_intersection)
.def("dist_to", &Geometry2d::Line::distTo)
;
class_<Geometry2d::Segment, Geometry2d::Segment*, bases<Geometry2d::Line> >("Segment", init<Geometry2d::Point, Geometry2d::Point>())
.def("center", &Geometry2d::Segment::center)
.def("length", &Geometry2d::Segment::length)
.def("dist_to", &Geometry2d::Segment::distTo)
.def("nearest_point", &Geometry2d::Segment::nearestPoint)
;
class_<Geometry2d::Shape, boost::noncopyable>("Shape")
;
class_<Geometry2d::Rect, bases<Geometry2d::Shape> >("Rect", init<Geometry2d::Point, Geometry2d::Point>())
.def("contains_rect", &Rect_contains_rect)
.def("min_x", &Geometry2d::Rect::minx)
.def("min_y", &Geometry2d::Rect::miny)
.def("max_x", &Geometry2d::Rect::maxx)
.def("max_y", &Geometry2d::Rect::maxy)
.def("near_point", &Geometry2d::Rect::nearPoint)
.def("intersects_rect", &Geometry2d::Rect::intersects)
.def("contains_point", &Geometry2d::Rect::containsPoint)
;
class_<Geometry2d::Circle, bases<Geometry2d::Shape> >("Circle", init<Geometry2d::Point, float>());
class_<Geometry2d::CompositeShape, bases<Geometry2d::Shape> >("CompositeShape", init<>())
.def("clear", &Geometry2d::CompositeShape::clear)
.def("is_empty", &Geometry2d::CompositeShape::empty)
.def("size", &Geometry2d::CompositeShape::size)
.def("add_shape", &CompositeShape_add_shape)
.def("contains_point", &Geometry2d::CompositeShape::containsPoint)
;
class_<GameState>("GameState")
.def_readonly("our_score", &GameState::ourScore)
.def_readonly("their_score", &GameState::theirScore)
.def("is_halted", &GameState::halt)
.def("is_stopped", &GameState::stopped)
.def("is_playing", &GameState::playing)
.def("is_kickoff", &GameState::kickoff)
.def("is_penalty", &GameState::penalty)
.def("is_direct", &GameState::direct)
.def("is_indirect", &GameState::indirect)
.def("is_our_kickoff", &GameState::ourKickoff)
.def("is_our_penalty", &GameState::ourPenalty)
.def("is_our_direct", &GameState::ourDirect)
.def("is_our_indirect", &GameState::ourIndirect)
.def("is_our_free_kick", &GameState::ourFreeKick)
.def("is_their_kickoff", &GameState::theirKickoff)
.def("is_their_penalty", &GameState::theirPenalty)
.def("is_their_direct", &GameState::theirDirect)
.def("is_their_indirect", &GameState::theirIndirect)
.def("is_their_free_kick", &GameState::theirFreeKick)
.def("is_setup_state", &GameState::inSetupState)
.def("is_ready_state", &GameState::inReadyState)
.def("can_kick", &GameState::canKick)
.def("stay_away_from_ball", &GameState::stayAwayFromBall)
.def("stay_on_side", &GameState::stayOnSide)
.def("stay_behind_penalty_line", &GameState::stayBehindPenaltyLine)
;
class_<Robot>("Robot", init<int, bool>())
.def("shell_id", &Robot::shell)
.def("is_ours", &Robot::self)
.def_readwrite("pos", &Robot::pos)
.def_readwrite("vel", &Robot::vel)
.def_readwrite("angle", &Robot::angle)
.def_readwrite("angle_vel", &Robot::angleVel)
.def_readwrite("visible", &Robot::visible)
.def("__repr__", &Robot_repr)
;
class_<OurRobot, OurRobot *, std::shared_ptr<OurRobot>, bases<Robot> >("OurRobot", init<int, SystemState*>())
.def("move_to", &OurRobot_move_to)
.def("set_world_vel", &OurRobot::worldVelocity)
.def("face", &OurRobot::face)
.def("set_avoid_ball_radius", &OurRobot_set_avoid_ball_radius)
.def("disable_avoid_ball", &OurRobot::disableAvoidBall)
.def("avoid_all_teammates", &OurRobot::avoidAllTeammates)
.def("add_text", &OutRobot_add_text)
.def("approach_opponent", &OurRobot_approach_opponent)
.def("set_dribble_speed", &OurRobot::dribble)
.def("has_ball", &OurRobot::hasBall)
;
class_<OpponentRobot, OpponentRobot *, std::shared_ptr<OpponentRobot>, bases<Robot> >("OpponentRobot", init<int>());
class_<Ball, std::shared_ptr<Ball> >("Ball", init<>())
.def_readonly("pos", &Ball::pos)
.def_readonly("vel", &Ball::vel)
.def_readonly("valid", &Ball::valid)
;
class_<std::vector<OurRobot *> >("vector_OurRobot")
.def(vector_indexing_suite<std::vector<OurRobot *> >())
;
class_<std::vector<OpponentRobot *> >("vector_OpponentRobot")
.def(vector_indexing_suite<std::vector<OpponentRobot *> >())
;
class_<SystemState, SystemState *>("SystemState")
.def_readonly("our_robots", &SystemState::self)
.def_readonly("their_robots", &SystemState::opp)
.def_readonly("ball", &SystemState::ball)
.def_readonly("game_state", &SystemState::gameState)
.def_readonly("timestamp", &SystemState::timestamp)
// debug drawing methods
.def("draw_circle", &State_draw_circle)
.def("draw_path", &SystemState::drawPath)
.def("draw_text", &SystemState::drawText)
.def("draw_shape", &SystemState::drawShape)
.def("draw_line", &State_draw_line)
;
}
<commit_msg>added some wrapper stuff<commit_after>#include "robocup-py.hpp"
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <string>
#include <sstream>
#include <iostream>
using namespace boost::python;
#include <Geometry2d/Point.hpp>
#include <Geometry2d/Rect.hpp>
#include <Geometry2d/CompositeShape.hpp>
#include <Robot.hpp>
#include <SystemState.hpp>
#include <protobuf/LogFrame.pb.h>
/**
* NOTES FOR WRAPPER FUNCTIONS/METHODS
*
* Keep in mind that pointer parameters will be be nullptr/NULL if the value
* from python was None. Check for this case so that we don't segfault.
*/
// this is here so boost can work with std::shared_ptr
template<class T> T * get_pointer( std::shared_ptr<T> const& p) {
return p.get();
}
std::string Point_repr(Geometry2d::Point *self) {
std::ostringstream ss;
ss << "Point(";
ss << self->x;
ss << ", ";
ss << self->y;
ss << ")";
std::string repr(ss.str());
return repr;
}
std::string Robot_repr(Robot *self) {
std::ostringstream ss;
ss << "<Robot ";
ss << (self->self() ? "us[" : "them[");
ss << self->shell();
ss << "], pos=";
ss << Point_repr(&(self->pos));
ss << ">";
std::string repr(ss.str());
return repr;
}
void OurRobot_move_to(OurRobot *self, Geometry2d::Point *to) {
self->move(*to);
}
void OurRobot_set_avoid_ball_radius(OurRobot *self, float radius) {
self->avoidBallRadius(radius);
}
void OurRobot_approach_opponent(OurRobot *self, unsigned shell_id, bool enable_approach) {
self->approachOpponent(shell_id, enable_approach);
}
void OutRobot_add_text(OurRobot *self, const std::string &text, boost::python::tuple rgb, const std::string &layerPrefix) {
float r = extract<float>(rgb[0]);
float g = extract<float>(rgb[1]);
float b = extract<float>(rgb[2]);
self->addText(QString::fromStdString(text), QColor(r,g,b), QString::fromStdString(layerPrefix));
}
bool Rect_contains_rect(Geometry2d::Rect *self, Geometry2d::Rect *other) {
return self->contains(*other);
}
bool Rect_contains_point(Geometry2d::Rect *self, Geometry2d::Point *pt) {
return self->contains(*pt);
}
void Point_rotate(Geometry2d::Point *self, Geometry2d::Point *origin, float angle) {
self->rotate(*origin, angle);
}
void CompositeShape_add_shape(Geometry2d::CompositeShape *self, Geometry2d::Shape *shape) {
self->add(std::shared_ptr<Geometry2d::Shape>( shape->clone() ));
}
boost::python::tuple Line_wrap_pt(Geometry2d::Line *self) {
boost::python::list a;
for (int i = 0; i < 2; i++) {
a.append(self->pt[i]);
}
return boost::python::tuple(a);
}
// returns None or a Geometry2d::Point
boost::python::object Line_line_intersection(Geometry2d::Line *self, Geometry2d::Line *other) {
Geometry2d::Point pt;
if (self->intersects(*other, &pt)) {
boost::python::object obj(pt);
return obj;
} else {
// return None
return boost::python::object();
}
};
QColor Color_from_tuple(const boost::python::tuple &colorTuple) {
float r = extract<float>(rgb[0]);
float g = extract<float>(rgb[1]);
float b = extract<float>(rgb[2]);
return QColor(r, g, b);
}
void State_draw_circle(SystemState *self, const Geometry2d::Point *center, float radius, boost::python::tuple rgb, const std::string &layer) {
self->drawCircle(*center, radius, Color_from_tuple(rgb), QString::fromStdString(layer));
}
void State_draw_line(SystemState *self, const Geometry2d::Line *line, boost::python::tuple rgb, const std::string &layer) {
self->drawLine(*line, Color_from_tuple(rgb), QString::fromStdString(layer));
}
/**
* The code in this block wraps up c++ classes and makes them
* accessible to python in the 'robocup' module.
*/
BOOST_PYTHON_MODULE(robocup)
{
class_<Geometry2d::Point>("Point", init<float, float>())
.def(init<const Geometry2d::Point &>())
.def_readwrite("x", &Geometry2d::Point::x)
.def_readwrite("y", &Geometry2d::Point::y)
.def(self - self)
.def(self + self)
.def("mag", &Geometry2d::Point::mag)
.def("magsq", &Geometry2d::Point::magsq)
.def("__repr__", &Point_repr)
.def("normalized", &Geometry2d::Point::normalized)
.def("rotate", &Point_rotate)
.def(self * float())
.def(self / float())
.def("perp_ccw", &Geometry2d::Point::perpCCW)
.def("perp_cw", &Geometry2d::Point::perpCW)
.def("angle", &Geometry2d::Point::angle)
.def("dot", &Geometry2d::Point::dot)
.def("near_point", &Geometry2d::Point::nearPoint)
;
class_<Geometry2d::Line, Geometry2d::Line*>("Line", init<Geometry2d::Point, Geometry2d::Point>())
.add_property("pt", Line_wrap_pt)
.def("delta", &Geometry2d::Line::delta)
.def("line_intersection", &Line_line_intersection)
.def("dist_to", &Geometry2d::Line::distTo)
;
class_<Geometry2d::Segment, Geometry2d::Segment*, bases<Geometry2d::Line> >("Segment", init<Geometry2d::Point, Geometry2d::Point>())
.def("center", &Geometry2d::Segment::center)
.def("length", &Geometry2d::Segment::length)
.def("dist_to", &Geometry2d::Segment::distTo)
.def("nearest_point", &Geometry2d::Segment::nearestPoint)
;
class_<Geometry2d::Shape, boost::noncopyable>("Shape")
;
class_<Geometry2d::Rect, bases<Geometry2d::Shape> >("Rect", init<Geometry2d::Point, Geometry2d::Point>())
.def("contains_rect", &Rect_contains_rect)
.def("min_x", &Geometry2d::Rect::minx)
.def("min_y", &Geometry2d::Rect::miny)
.def("max_x", &Geometry2d::Rect::maxx)
.def("max_y", &Geometry2d::Rect::maxy)
.def("near_point", &Geometry2d::Rect::nearPoint)
.def("intersects_rect", &Geometry2d::Rect::intersects)
.def("contains_point", &Geometry2d::Rect::containsPoint)
;
class_<Geometry2d::Circle, bases<Geometry2d::Shape> >("Circle", init<Geometry2d::Point, float>());
class_<Geometry2d::CompositeShape, bases<Geometry2d::Shape> >("CompositeShape", init<>())
.def("clear", &Geometry2d::CompositeShape::clear)
.def("is_empty", &Geometry2d::CompositeShape::empty)
.def("size", &Geometry2d::CompositeShape::size)
.def("add_shape", &CompositeShape_add_shape)
.def("contains_point", &Geometry2d::CompositeShape::containsPoint)
;
class_<GameState>("GameState")
.def_readonly("our_score", &GameState::ourScore)
.def_readonly("their_score", &GameState::theirScore)
.def("is_halted", &GameState::halt)
.def("is_stopped", &GameState::stopped)
.def("is_playing", &GameState::playing)
.def("is_kickoff", &GameState::kickoff)
.def("is_penalty", &GameState::penalty)
.def("is_direct", &GameState::direct)
.def("is_indirect", &GameState::indirect)
.def("is_our_kickoff", &GameState::ourKickoff)
.def("is_our_penalty", &GameState::ourPenalty)
.def("is_our_direct", &GameState::ourDirect)
.def("is_our_indirect", &GameState::ourIndirect)
.def("is_our_free_kick", &GameState::ourFreeKick)
.def("is_their_kickoff", &GameState::theirKickoff)
.def("is_their_penalty", &GameState::theirPenalty)
.def("is_their_direct", &GameState::theirDirect)
.def("is_their_indirect", &GameState::theirIndirect)
.def("is_their_free_kick", &GameState::theirFreeKick)
.def("is_setup_state", &GameState::inSetupState)
.def("is_ready_state", &GameState::inReadyState)
.def("can_kick", &GameState::canKick)
.def("stay_away_from_ball", &GameState::stayAwayFromBall)
.def("stay_on_side", &GameState::stayOnSide)
.def("stay_behind_penalty_line", &GameState::stayBehindPenaltyLine)
;
class_<Robot>("Robot", init<int, bool>())
.def("shell_id", &Robot::shell)
.def("is_ours", &Robot::self)
.def_readwrite("pos", &Robot::pos)
.def_readwrite("vel", &Robot::vel)
.def_readwrite("angle", &Robot::angle)
.def_readwrite("angle_vel", &Robot::angleVel)
.def_readwrite("visible", &Robot::visible)
.def("__repr__", &Robot_repr)
;
class_<OurRobot, OurRobot *, std::shared_ptr<OurRobot>, bases<Robot> >("OurRobot", init<int, SystemState*>())
.def("move_to", &OurRobot_move_to)
.def("set_world_vel", &OurRobot::worldVelocity)
.def("face", &OurRobot::face)
.def("set_avoid_ball_radius", &OurRobot_set_avoid_ball_radius)
.def("disable_avoid_ball", &OurRobot::disableAvoidBall)
.def("avoid_all_teammates", &OurRobot::avoidAllTeammates)
.def("add_text", &OutRobot_add_text)
.def("approach_opponent", &OurRobot_approach_opponent)
.def("set_dribble_speed", &OurRobot::dribble)
.def("has_ball", &OurRobot::hasBall)
;
class_<OpponentRobot, OpponentRobot *, std::shared_ptr<OpponentRobot>, bases<Robot> >("OpponentRobot", init<int>());
class_<Ball, std::shared_ptr<Ball> >("Ball", init<>())
.def_readonly("pos", &Ball::pos)
.def_readonly("vel", &Ball::vel)
.def_readonly("valid", &Ball::valid)
;
class_<std::vector<OurRobot *> >("vector_OurRobot")
.def(vector_indexing_suite<std::vector<OurRobot *> >())
;
class_<std::vector<OpponentRobot *> >("vector_OpponentRobot")
.def(vector_indexing_suite<std::vector<OpponentRobot *> >())
;
class_<SystemState, SystemState *>("SystemState")
.def_readonly("our_robots", &SystemState::self)
.def_readonly("their_robots", &SystemState::opp)
.def_readonly("ball", &SystemState::ball)
.def_readonly("game_state", &SystemState::gameState)
.def_readonly("timestamp", &SystemState::timestamp)
// debug drawing methods
.def("draw_circle", &State_draw_circle)
.def("draw_path", &SystemState::drawPath)
.def("draw_text", &SystemState::drawText)
.def("draw_shape", &SystemState::drawShape)
.def("draw_line", &State_draw_line)
;
}
<|endoftext|> |
<commit_before>//
// Copyright 2011-2015 Jeff Bush
//
// 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 "Barrier.h"
#include "Matrix2x2.h"
typedef int veci16 __attribute__((ext_vector_type(16)));
typedef float vecf16 __attribute__((ext_vector_type(16)));
veci16* const kFrameBufferAddress = (veci16*) 0x200000;
const vecf16 kXOffsets = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f,
8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f };
extern unsigned int kImage[];
const int kImageWidth = 16;
const int kImageHeight = 16;
const int kBytesPerPixel = 4;
const int kScreenWidth = 640;
const int kScreenHeight = 480;
void dflush(void *ptr)
{
__asm("dflush %0" : : "r" (ptr));
}
Barrier<4> gFrameBarrier; // We don't execute global ctors yet, but I know this is fine.
Matrix2x2 displayMatrix;
int main()
{
// Start other threads
__builtin_nyuzi_write_control_reg(30, 0xffffffff);
int myStrandId = __builtin_nyuzi_read_control_reg(0);
if (myStrandId == 0)
displayMatrix = Matrix2x2();
// 1/64 step rotation
Matrix2x2 stepMatrix(
0.9987954562, -0.04906767432,
0.04906767432, 0.9987954562);
stepMatrix = stepMatrix * Matrix2x2(0.99, 0.0, 0.0, 0.99); // Scale slightly
// Strands work on interleaved chunks of pixels. The strand ID determines
// the starting point.
while (true)
{
unsigned int imageBase = (unsigned int) kImage;
veci16 *outputPtr = kFrameBufferAddress + myStrandId;
for (int y = 0; y < kScreenHeight; y++)
{
for (int x = myStrandId * 16; x < kScreenWidth; x += 64)
{
vecf16 xv = kXOffsets + __builtin_nyuzi_makevectorf((float) x)
- __builtin_nyuzi_makevectorf(kScreenWidth / 2);
vecf16 yv = __builtin_nyuzi_makevectorf((float) y)
- __builtin_nyuzi_makevectorf(kScreenHeight / 2);;
vecf16 u = xv * __builtin_nyuzi_makevectorf(displayMatrix.a)
+ yv * __builtin_nyuzi_makevectorf(displayMatrix.b);
vecf16 v = xv * __builtin_nyuzi_makevectorf(displayMatrix.c)
+ yv * __builtin_nyuzi_makevectorf(displayMatrix.d);
veci16 tx = (__builtin_convertvector(u, veci16) & __builtin_nyuzi_makevectori(kImageWidth - 1));
veci16 ty = (__builtin_convertvector(v, veci16) & __builtin_nyuzi_makevectori(kImageHeight - 1));
veci16 pixelPtrs = (ty * __builtin_nyuzi_makevectori(kImageWidth * kBytesPerPixel))
+ (tx * __builtin_nyuzi_makevectori(kBytesPerPixel))
+ __builtin_nyuzi_makevectori(imageBase);
*outputPtr = __builtin_nyuzi_gather_loadi(pixelPtrs);
dflush(outputPtr);
outputPtr += 4; // Skip over four chunks because there are four threads.
}
}
if (myStrandId == 0)
displayMatrix = displayMatrix * stepMatrix;
gFrameBarrier.wait();
}
return 0;
}
unsigned int kImage[] = {
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xfffff8,
0xc8ffeb,
0x68ffe3,
0x28ffdf,
0x7ffdf,
0x7ffe3,
0x28ffeb,
0x68fff8,
0xc8ffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffeb,
0x68ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffeb,
0x68ffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffe7,
0x48ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffe7,
0x48ffff,
0xffffff,
0xffffff,
0xffffeb,
0x68ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffeb,
0x68ffff,
0xfffff8,
0xc8ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xfff8,
0xc8ffeb,
0x68ffde,
0xffde,
0xffde,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0xffde,
0xffeb,
0x68ffe3,
0x28ffde,
0xffde,
0xffde,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0xffde,
0xffe3,
0x28ffdf,
0x7ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffdf,
0x7ffdf,
0x7ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffdf,
0x7ffe3,
0x28ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffe3,
0x28ffeb,
0x68ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0x0,
0xffde,
0xffde,
0xffde,
0xffeb,
0x68fff8,
0xc8ffde,
0xffde,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0x0,
0xffde,
0xffde,
0xffde,
0xfff8,
0xc8ffff,
0xffffeb,
0x68ffde,
0xffde,
0x0,
0x0,
0x0,
0xffde,
0xffde,
0x0,
0x0,
0x0,
0xffde,
0xffde,
0xffeb,
0x68ffff,
0xffffff,
0xffffff,
0xffffe7,
0x48ffde,
0xffde,
0xffde,
0x0,
0x0,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0xffe7,
0x48ffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffeb,
0x68ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffeb,
0x68ffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xfffff8,
0xc8ffeb,
0x68ffe3,
0x28ffdf,
0x7ffdf,
0x7ffe3,
0x28ffeb,
0x68fff8,
0xc8ffff,
0xffffff,
0xffffff,
0xffffff
};
<commit_msg>remove obsolete comment<commit_after>//
// Copyright 2011-2015 Jeff Bush
//
// 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 "Barrier.h"
#include "Matrix2x2.h"
typedef int veci16 __attribute__((ext_vector_type(16)));
typedef float vecf16 __attribute__((ext_vector_type(16)));
veci16* const kFrameBufferAddress = (veci16*) 0x200000;
const vecf16 kXOffsets = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f,
8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f };
extern unsigned int kImage[];
const int kImageWidth = 16;
const int kImageHeight = 16;
const int kBytesPerPixel = 4;
const int kScreenWidth = 640;
const int kScreenHeight = 480;
void dflush(void *ptr)
{
__asm("dflush %0" : : "r" (ptr));
}
Barrier<4> gFrameBarrier;
Matrix2x2 displayMatrix;
int main()
{
// Start other threads
__builtin_nyuzi_write_control_reg(30, 0xffffffff);
int myStrandId = __builtin_nyuzi_read_control_reg(0);
if (myStrandId == 0)
displayMatrix = Matrix2x2();
// 1/64 step rotation
Matrix2x2 stepMatrix(
0.9987954562, -0.04906767432,
0.04906767432, 0.9987954562);
stepMatrix = stepMatrix * Matrix2x2(0.99, 0.0, 0.0, 0.99); // Scale slightly
// Strands work on interleaved chunks of pixels. The strand ID determines
// the starting point.
while (true)
{
unsigned int imageBase = (unsigned int) kImage;
veci16 *outputPtr = kFrameBufferAddress + myStrandId;
for (int y = 0; y < kScreenHeight; y++)
{
for (int x = myStrandId * 16; x < kScreenWidth; x += 64)
{
vecf16 xv = kXOffsets + __builtin_nyuzi_makevectorf((float) x)
- __builtin_nyuzi_makevectorf(kScreenWidth / 2);
vecf16 yv = __builtin_nyuzi_makevectorf((float) y)
- __builtin_nyuzi_makevectorf(kScreenHeight / 2);;
vecf16 u = xv * __builtin_nyuzi_makevectorf(displayMatrix.a)
+ yv * __builtin_nyuzi_makevectorf(displayMatrix.b);
vecf16 v = xv * __builtin_nyuzi_makevectorf(displayMatrix.c)
+ yv * __builtin_nyuzi_makevectorf(displayMatrix.d);
veci16 tx = (__builtin_convertvector(u, veci16) & __builtin_nyuzi_makevectori(kImageWidth - 1));
veci16 ty = (__builtin_convertvector(v, veci16) & __builtin_nyuzi_makevectori(kImageHeight - 1));
veci16 pixelPtrs = (ty * __builtin_nyuzi_makevectori(kImageWidth * kBytesPerPixel))
+ (tx * __builtin_nyuzi_makevectori(kBytesPerPixel))
+ __builtin_nyuzi_makevectori(imageBase);
*outputPtr = __builtin_nyuzi_gather_loadi(pixelPtrs);
dflush(outputPtr);
outputPtr += 4; // Skip over four chunks because there are four threads.
}
}
if (myStrandId == 0)
displayMatrix = displayMatrix * stepMatrix;
gFrameBarrier.wait();
}
return 0;
}
unsigned int kImage[] = {
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xfffff8,
0xc8ffeb,
0x68ffe3,
0x28ffdf,
0x7ffdf,
0x7ffe3,
0x28ffeb,
0x68fff8,
0xc8ffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffeb,
0x68ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffeb,
0x68ffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffe7,
0x48ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffe7,
0x48ffff,
0xffffff,
0xffffff,
0xffffeb,
0x68ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffeb,
0x68ffff,
0xfffff8,
0xc8ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xfff8,
0xc8ffeb,
0x68ffde,
0xffde,
0xffde,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0xffde,
0xffeb,
0x68ffe3,
0x28ffde,
0xffde,
0xffde,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0xffde,
0xffe3,
0x28ffdf,
0x7ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffdf,
0x7ffdf,
0x7ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffdf,
0x7ffe3,
0x28ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffe3,
0x28ffeb,
0x68ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0x0,
0xffde,
0xffde,
0xffde,
0xffeb,
0x68fff8,
0xc8ffde,
0xffde,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0x0,
0xffde,
0xffde,
0xffde,
0xfff8,
0xc8ffff,
0xffffeb,
0x68ffde,
0xffde,
0x0,
0x0,
0x0,
0xffde,
0xffde,
0x0,
0x0,
0x0,
0xffde,
0xffde,
0xffeb,
0x68ffff,
0xffffff,
0xffffff,
0xffffe7,
0x48ffde,
0xffde,
0xffde,
0x0,
0x0,
0x0,
0x0,
0xffde,
0xffde,
0xffde,
0xffe7,
0x48ffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffeb,
0x68ffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffde,
0xffeb,
0x68ffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xffffff,
0xfffff8,
0xc8ffeb,
0x68ffe3,
0x28ffdf,
0x7ffdf,
0x7ffe3,
0x28ffeb,
0x68fff8,
0xc8ffff,
0xffffff,
0xffffff,
0xffffff
};
<|endoftext|> |
<commit_before>/* Copyright © 2001-2022, Hove and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Hove (www.hove.com).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "configuration.h"
#include "utils/exception.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/optional.hpp>
#include <fstream>
#include <iostream>
namespace po = boost::program_options;
namespace navitia {
namespace kraken {
po::options_description get_options_description(const boost::optional<std::string>& name,
const boost::optional<std::string>& zmq,
const boost::optional<bool>& display_contributors) {
po::options_description desc("Allowed options");
// clang-format off
desc.add_options()
("GENERAL.database", po::value<std::string>()->default_value("data.nav.lz4"), "path to the data file")
//name and zmq socket can have default values (for tests)
("GENERAL.zmq_socket",
zmq ? po::value<std::string>()->default_value(*zmq) : po::value<std::string>()->required(),
"path to the zmq socket used for receiving resquest")
("GENERAL.instance_name",
name ? po::value<std::string>()->default_value(*name) : po::value<std::string>()->required(),
"name of the instance")
("GENERAL.nb_threads", po::value<int>()->default_value(1), "number of workers threads")
("GENERAL.is_realtime_enabled", po::value<bool>()->default_value(false),
"enable loading of realtime data")
("GENERAL.is_realtime_add_enabled", po::value<bool>()->default_value(false),
"enable loading of realtime data that add stop_times")
("GENERAL.is_realtime_add_trip_enabled", po::value<bool>()->default_value(false),
"enable loading of realtime data that add trips (only if is_realtime_add_enabled is activated)")
("GENERAL.kirin_timeout", po::value<int>()->default_value(60000),
"timeout in ms for loading realtime data from kirin")
("GENERAL.kirin_retry_timeout", po::value<int>()->default_value(5*60*1000),
"timeout in ms before retrying to load realtime data")
("GENERAL.slow_request_duration", po::value<int>()->default_value(1000),
"request running a least this number of milliseconds are logged")
("GENERAL.display_contributors", display_contributors ?
po::value<bool>()->default_value(*display_contributors) : po::value<bool>()->default_value(false),
"display all contributors in feed publishers")
("GENERAL.raptor_cache_size", po::value<int>()->default_value(10), "maximum number of stored raptor caches")
("GENERAL.log_level", po::value<std::string>(), "log level of kraken")
("GENERAL.log_format", po::value<std::string>()->default_value("[%D{%y-%m-%d %H:%M:%S,%q}] [%p] [%x] - %m %b:%L %n"), "log format")
("GENERAL.enable_request_deadline", po::value<bool>()->default_value(true), "enable deadline of request")
("GENERAL.metrics_binding", po::value<std::string>(), "IP:PORT to serving metrics in http")
("GENERAL.core_file_size_limit", po::value<int>()->default_value(0), "ulimit that define the maximum size of a core file")
("BROKER.uri", po::value<std::string>(), "rabbitmq connection uri")
("BROKER.protocol", po::value<std::string>()->default_value("amqp"), "rabbitmq connection protocol")
("BROKER.host", po::value<std::string>()->default_value("localhost"), "host of rabbitmq")
("BROKER.port", po::value<int>()->default_value(5672), "port of rabbitmq")
("BROKER.username", po::value<std::string>()->default_value("guest"), "username for rabbitmq")
("BROKER.password", po::value<std::string>()->default_value("guest"), "password for rabbitmq")
("BROKER.vhost", po::value<std::string>()->default_value("/"), "vhost for rabbitmq")
("BROKER.exchange", po::value<std::string>()->default_value("navitia"), "exchange used in rabbitmq")
("BROKER.rt_topics", po::value<std::vector<std::string>>(), "list of realtime topic for this instance")
("BROKER.timeout", po::value<int>()->default_value(100), "timeout for maintenance worker in millisecond")
("BROKER.sleeptime", po::value<int>()->default_value(1), "sleeptime for maintenance worker in second")
("BROKER.queue", po::value<std::string>(), "rabbitmq's queue name to be bound")
("BROKER.queue_auto_delete", po::value<bool>()->default_value(false), "auto delete rabbitmq's queue when unbind")
("CHAOS.database", po::value<std::string>(), "Chaos database connection string")
("CHAOS.batch_size", po::value<int>()->default_value(1000000), "Chaos database row batch size");
// clang-format on
return desc;
}
static std::string env_parser(std::string env) {
if (!boost::algorithm::starts_with(env, "KRAKEN_")) {
return "";
}
boost::algorithm::replace_first(env, "KRAKEN_", "");
boost::algorithm::replace_first(env, "GENERAL_", "GENERAL.");
boost::algorithm::replace_first(env, "BROKER_", "BROKER.");
boost::algorithm::replace_first(env, "CHAOS_", "CHAOS.");
if (!boost::algorithm::starts_with(env, "GENERAL") && !boost::algorithm::starts_with(env, "BROKER")
&& !boost::algorithm::starts_with(env, "CHAOS")) {
// it doesn't look like one of our var, we ignore it
// docker and kubernetes define a lot of env var starting by kraken when deploying kraken
// and boost po will abort startup if unknown var are present
return "";
}
return env;
}
void Configuration::load(const std::string& filename) {
po::options_description desc = get_options_description();
po::store(po::parse_environment(desc, env_parser), this->vm);
std::ifstream stream(filename);
if (!stream.is_open() || !stream.good()) {
std::cerr << "no configuration file found, using only environment variables" << std::endl;
} else {
// we allow unknown option for log4cplus
po::store(po::parse_config_file(stream, desc, true), this->vm);
}
po::notify(this->vm);
}
std::vector<std::string> Configuration::load_from_command_line(const po::options_description& desc,
int argc,
const char* const argv[]) {
auto tmp = po::basic_command_line_parser<char>(argc, argv).options(desc).allow_unregistered().run();
po::store(tmp, vm);
po::notify(vm);
// return unparsed options
return po::collect_unrecognized(tmp.options, po::include_positional);
}
std::string Configuration::databases_path() const {
return this->vm["GENERAL.database"].as<std::string>();
}
std::string Configuration::zmq_socket_path() const {
return this->vm["GENERAL.zmq_socket"].as<std::string>();
}
std::string Configuration::instance_name() const {
return this->vm["GENERAL.instance_name"].as<std::string>();
}
boost::optional<std::string> Configuration::chaos_database() const {
boost::optional<std::string> result;
if (this->vm.count("CHAOS.database") > 0) {
result = this->vm["CHAOS.database"].as<std::string>();
}
return result;
}
int Configuration::chaos_batch_size() const {
int batch_size = vm["CHAOS.batch_size"].as<int>();
if (batch_size < 0) {
throw std::invalid_argument("chaos.batch_size cannot be negative");
}
return batch_size;
}
int Configuration::nb_threads() const {
int nb_threads = vm["GENERAL.nb_threads"].as<int>();
if (nb_threads < 0) {
throw std::invalid_argument("nb_threads cannot be negative");
}
return size_t(nb_threads);
}
bool Configuration::is_realtime_enabled() const {
return this->vm["GENERAL.is_realtime_enabled"].as<bool>();
}
bool Configuration::is_realtime_add_enabled() const {
return this->vm["GENERAL.is_realtime_add_enabled"].as<bool>();
}
bool Configuration::is_realtime_add_trip_enabled() const {
return this->vm["GENERAL.is_realtime_add_trip_enabled"].as<bool>();
}
int Configuration::kirin_timeout() const {
return this->vm["GENERAL.kirin_timeout"].as<int>();
}
int Configuration::core_file_size_limit() const {
return this->vm["GENERAL.core_file_size_limit"].as<int>();
}
boost::optional<std::string> Configuration::broker_uri() const {
if (this->vm.count("BROKER.uri") > 0) {
return this->vm["BROKER.uri"].as<std::string>();
}
return {};
}
std::string Configuration::broker_protocol() const {
return this->vm["BROKER.protocol"].as<std::string>();
}
std::string Configuration::broker_host() const {
return this->vm["BROKER.host"].as<std::string>();
}
int Configuration::broker_port() const {
return this->vm["BROKER.port"].as<int>();
}
std::string Configuration::broker_username() const {
return this->vm["BROKER.username"].as<std::string>();
}
std::string Configuration::broker_password() const {
return this->vm["BROKER.password"].as<std::string>();
}
std::string Configuration::broker_vhost() const {
return this->vm["BROKER.vhost"].as<std::string>();
}
std::string Configuration::broker_exchange() const {
return this->vm["BROKER.exchange"].as<std::string>();
}
int Configuration::broker_timeout() const {
return vm["BROKER.timeout"].as<int>();
}
int Configuration::broker_sleeptime() const {
return vm["BROKER.sleeptime"].as<int>();
}
std::string Configuration::broker_queue(const std::string& default_queue) const {
if (vm.count("BROKER.queue")) {
return this->vm["BROKER.queue"].as<std::string>();
}
return default_queue;
}
bool Configuration::broker_queue_auto_delete() const {
return vm["BROKER.queue_auto_delete"].as<bool>();
}
std::vector<std::string> Configuration::rt_topics() const {
if (!this->vm.count("BROKER.rt_topics")) {
return std::vector<std::string>();
}
return this->vm["BROKER.rt_topics"].as<std::vector<std::string>>();
}
int Configuration::kirin_retry_timeout() const {
return vm["GENERAL.kirin_retry_timeout"].as<int>();
}
bool Configuration::display_contributors() const {
if (!this->vm.count("GENERAL.display_contributors")) {
return false;
}
return vm["GENERAL.display_contributors"].as<bool>();
}
int Configuration::slow_request_duration() const {
return vm["GENERAL.slow_request_duration"].as<int>();
}
bool Configuration::enable_request_deadline() const {
return vm["GENERAL.enable_request_deadline"].as<bool>();
}
size_t Configuration::raptor_cache_size() const {
if (!vm.count("GENERAL.raptor_cache_size")) {
return 10;
}
int raptor_cache_size = vm["GENERAL.raptor_cache_size"].as<int>();
if (raptor_cache_size < 1) {
throw std::invalid_argument("raptor_cache_size must be strictly positive");
}
return size_t(raptor_cache_size);
}
boost::optional<std::string> Configuration::log_level() const {
boost::optional<std::string> result;
if (this->vm.count("GENERAL.log_level") > 0) {
result = this->vm["GENERAL.log_level"].as<std::string>();
}
return result;
}
boost::optional<std::string> Configuration::log_format() const {
boost::optional<std::string> result;
if (this->vm.count("GENERAL.log_format") > 0) {
result = this->vm["GENERAL.log_format"].as<std::string>();
}
return result;
}
boost::optional<std::string> Configuration::metrics_binding() const {
boost::optional<std::string> result;
if (this->vm.count("GENERAL.metrics_binding") > 0) {
result = this->vm["GENERAL.metrics_binding"].as<std::string>();
}
return result;
}
} // namespace kraken
} // namespace navitia
<commit_msg>Remove unused include<commit_after>/* Copyright © 2001-2022, Hove and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Hove (www.hove.com).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "configuration.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/optional.hpp>
#include <fstream>
#include <iostream>
namespace po = boost::program_options;
namespace navitia {
namespace kraken {
po::options_description get_options_description(const boost::optional<std::string>& name,
const boost::optional<std::string>& zmq,
const boost::optional<bool>& display_contributors) {
po::options_description desc("Allowed options");
// clang-format off
desc.add_options()
("GENERAL.database", po::value<std::string>()->default_value("data.nav.lz4"), "path to the data file")
//name and zmq socket can have default values (for tests)
("GENERAL.zmq_socket",
zmq ? po::value<std::string>()->default_value(*zmq) : po::value<std::string>()->required(),
"path to the zmq socket used for receiving resquest")
("GENERAL.instance_name",
name ? po::value<std::string>()->default_value(*name) : po::value<std::string>()->required(),
"name of the instance")
("GENERAL.nb_threads", po::value<int>()->default_value(1), "number of workers threads")
("GENERAL.is_realtime_enabled", po::value<bool>()->default_value(false),
"enable loading of realtime data")
("GENERAL.is_realtime_add_enabled", po::value<bool>()->default_value(false),
"enable loading of realtime data that add stop_times")
("GENERAL.is_realtime_add_trip_enabled", po::value<bool>()->default_value(false),
"enable loading of realtime data that add trips (only if is_realtime_add_enabled is activated)")
("GENERAL.kirin_timeout", po::value<int>()->default_value(60000),
"timeout in ms for loading realtime data from kirin")
("GENERAL.kirin_retry_timeout", po::value<int>()->default_value(5*60*1000),
"timeout in ms before retrying to load realtime data")
("GENERAL.slow_request_duration", po::value<int>()->default_value(1000),
"request running a least this number of milliseconds are logged")
("GENERAL.display_contributors", display_contributors ?
po::value<bool>()->default_value(*display_contributors) : po::value<bool>()->default_value(false),
"display all contributors in feed publishers")
("GENERAL.raptor_cache_size", po::value<int>()->default_value(10), "maximum number of stored raptor caches")
("GENERAL.log_level", po::value<std::string>(), "log level of kraken")
("GENERAL.log_format", po::value<std::string>()->default_value("[%D{%y-%m-%d %H:%M:%S,%q}] [%p] [%x] - %m %b:%L %n"), "log format")
("GENERAL.enable_request_deadline", po::value<bool>()->default_value(true), "enable deadline of request")
("GENERAL.metrics_binding", po::value<std::string>(), "IP:PORT to serving metrics in http")
("GENERAL.core_file_size_limit", po::value<int>()->default_value(0), "ulimit that define the maximum size of a core file")
("BROKER.uri", po::value<std::string>(), "rabbitmq connection uri")
("BROKER.protocol", po::value<std::string>()->default_value("amqp"), "rabbitmq connection protocol")
("BROKER.host", po::value<std::string>()->default_value("localhost"), "host of rabbitmq")
("BROKER.port", po::value<int>()->default_value(5672), "port of rabbitmq")
("BROKER.username", po::value<std::string>()->default_value("guest"), "username for rabbitmq")
("BROKER.password", po::value<std::string>()->default_value("guest"), "password for rabbitmq")
("BROKER.vhost", po::value<std::string>()->default_value("/"), "vhost for rabbitmq")
("BROKER.exchange", po::value<std::string>()->default_value("navitia"), "exchange used in rabbitmq")
("BROKER.rt_topics", po::value<std::vector<std::string>>(), "list of realtime topic for this instance")
("BROKER.timeout", po::value<int>()->default_value(100), "timeout for maintenance worker in millisecond")
("BROKER.sleeptime", po::value<int>()->default_value(1), "sleeptime for maintenance worker in second")
("BROKER.queue", po::value<std::string>(), "rabbitmq's queue name to be bound")
("BROKER.queue_auto_delete", po::value<bool>()->default_value(false), "auto delete rabbitmq's queue when unbind")
("CHAOS.database", po::value<std::string>(), "Chaos database connection string")
("CHAOS.batch_size", po::value<int>()->default_value(1000000), "Chaos database row batch size");
// clang-format on
return desc;
}
static std::string env_parser(std::string env) {
if (!boost::algorithm::starts_with(env, "KRAKEN_")) {
return "";
}
boost::algorithm::replace_first(env, "KRAKEN_", "");
boost::algorithm::replace_first(env, "GENERAL_", "GENERAL.");
boost::algorithm::replace_first(env, "BROKER_", "BROKER.");
boost::algorithm::replace_first(env, "CHAOS_", "CHAOS.");
if (!boost::algorithm::starts_with(env, "GENERAL") && !boost::algorithm::starts_with(env, "BROKER")
&& !boost::algorithm::starts_with(env, "CHAOS")) {
// it doesn't look like one of our var, we ignore it
// docker and kubernetes define a lot of env var starting by kraken when deploying kraken
// and boost po will abort startup if unknown var are present
return "";
}
return env;
}
void Configuration::load(const std::string& filename) {
po::options_description desc = get_options_description();
po::store(po::parse_environment(desc, env_parser), this->vm);
std::ifstream stream(filename);
if (!stream.is_open() || !stream.good()) {
std::cerr << "no configuration file found, using only environment variables" << std::endl;
} else {
// we allow unknown option for log4cplus
po::store(po::parse_config_file(stream, desc, true), this->vm);
}
po::notify(this->vm);
}
std::vector<std::string> Configuration::load_from_command_line(const po::options_description& desc,
int argc,
const char* const argv[]) {
auto tmp = po::basic_command_line_parser<char>(argc, argv).options(desc).allow_unregistered().run();
po::store(tmp, vm);
po::notify(vm);
// return unparsed options
return po::collect_unrecognized(tmp.options, po::include_positional);
}
std::string Configuration::databases_path() const {
return this->vm["GENERAL.database"].as<std::string>();
}
std::string Configuration::zmq_socket_path() const {
return this->vm["GENERAL.zmq_socket"].as<std::string>();
}
std::string Configuration::instance_name() const {
return this->vm["GENERAL.instance_name"].as<std::string>();
}
boost::optional<std::string> Configuration::chaos_database() const {
boost::optional<std::string> result;
if (this->vm.count("CHAOS.database") > 0) {
result = this->vm["CHAOS.database"].as<std::string>();
}
return result;
}
int Configuration::chaos_batch_size() const {
int batch_size = vm["CHAOS.batch_size"].as<int>();
if (batch_size < 0) {
throw std::invalid_argument("chaos.batch_size cannot be negative");
}
return batch_size;
}
int Configuration::nb_threads() const {
int nb_threads = vm["GENERAL.nb_threads"].as<int>();
if (nb_threads < 0) {
throw std::invalid_argument("nb_threads cannot be negative");
}
return size_t(nb_threads);
}
bool Configuration::is_realtime_enabled() const {
return this->vm["GENERAL.is_realtime_enabled"].as<bool>();
}
bool Configuration::is_realtime_add_enabled() const {
return this->vm["GENERAL.is_realtime_add_enabled"].as<bool>();
}
bool Configuration::is_realtime_add_trip_enabled() const {
return this->vm["GENERAL.is_realtime_add_trip_enabled"].as<bool>();
}
int Configuration::kirin_timeout() const {
return this->vm["GENERAL.kirin_timeout"].as<int>();
}
int Configuration::core_file_size_limit() const {
return this->vm["GENERAL.core_file_size_limit"].as<int>();
}
boost::optional<std::string> Configuration::broker_uri() const {
if (this->vm.count("BROKER.uri") > 0) {
return this->vm["BROKER.uri"].as<std::string>();
}
return {};
}
std::string Configuration::broker_protocol() const {
return this->vm["BROKER.protocol"].as<std::string>();
}
std::string Configuration::broker_host() const {
return this->vm["BROKER.host"].as<std::string>();
}
int Configuration::broker_port() const {
return this->vm["BROKER.port"].as<int>();
}
std::string Configuration::broker_username() const {
return this->vm["BROKER.username"].as<std::string>();
}
std::string Configuration::broker_password() const {
return this->vm["BROKER.password"].as<std::string>();
}
std::string Configuration::broker_vhost() const {
return this->vm["BROKER.vhost"].as<std::string>();
}
std::string Configuration::broker_exchange() const {
return this->vm["BROKER.exchange"].as<std::string>();
}
int Configuration::broker_timeout() const {
return vm["BROKER.timeout"].as<int>();
}
int Configuration::broker_sleeptime() const {
return vm["BROKER.sleeptime"].as<int>();
}
std::string Configuration::broker_queue(const std::string& default_queue) const {
if (vm.count("BROKER.queue")) {
return this->vm["BROKER.queue"].as<std::string>();
}
return default_queue;
}
bool Configuration::broker_queue_auto_delete() const {
return vm["BROKER.queue_auto_delete"].as<bool>();
}
std::vector<std::string> Configuration::rt_topics() const {
if (!this->vm.count("BROKER.rt_topics")) {
return std::vector<std::string>();
}
return this->vm["BROKER.rt_topics"].as<std::vector<std::string>>();
}
int Configuration::kirin_retry_timeout() const {
return vm["GENERAL.kirin_retry_timeout"].as<int>();
}
bool Configuration::display_contributors() const {
if (!this->vm.count("GENERAL.display_contributors")) {
return false;
}
return vm["GENERAL.display_contributors"].as<bool>();
}
int Configuration::slow_request_duration() const {
return vm["GENERAL.slow_request_duration"].as<int>();
}
bool Configuration::enable_request_deadline() const {
return vm["GENERAL.enable_request_deadline"].as<bool>();
}
size_t Configuration::raptor_cache_size() const {
if (!vm.count("GENERAL.raptor_cache_size")) {
return 10;
}
int raptor_cache_size = vm["GENERAL.raptor_cache_size"].as<int>();
if (raptor_cache_size < 1) {
throw std::invalid_argument("raptor_cache_size must be strictly positive");
}
return size_t(raptor_cache_size);
}
boost::optional<std::string> Configuration::log_level() const {
boost::optional<std::string> result;
if (this->vm.count("GENERAL.log_level") > 0) {
result = this->vm["GENERAL.log_level"].as<std::string>();
}
return result;
}
boost::optional<std::string> Configuration::log_format() const {
boost::optional<std::string> result;
if (this->vm.count("GENERAL.log_format") > 0) {
result = this->vm["GENERAL.log_format"].as<std::string>();
}
return result;
}
boost::optional<std::string> Configuration::metrics_binding() const {
boost::optional<std::string> result;
if (this->vm.count("GENERAL.metrics_binding") > 0) {
result = this->vm["GENERAL.metrics_binding"].as<std::string>();
}
return result;
}
} // namespace kraken
} // namespace navitia
<|endoftext|> |
<commit_before>#include <fstream>
#include "data/EventsHeader.h"
#include "data/Event.h"
#include "exception/Base.h"
namespace blitzortung {
namespace data {
const char* EventsHeader::ID = "BOSF";
const gr::date EventsHeader::STARTOFEPOCH = gr::date(1970, 1, 1);
bool file_exists(std::string filename) {
std::ifstream file;
file.open(filename.c_str(), std::ios::in);
file.close();
return ! file.fail();
}
EventsHeader::EventsHeader(const gr::date& date) :
date_(date),
logger_("data.EventsHeader")
{
if (logger_.isDebugEnabled())
logger_.debugStream() << "construct() date " << date;
}
EventsHeader::~EventsHeader() {
}
const gr::date& EventsHeader::getDate() const {
return date_;
}
void EventsHeader::setDate(const gr::date& date) {
date_ = date;
}
unsigned int EventsHeader::getNumberOfEvents() const {
return numberOfEvents_;
}
unsigned int EventsHeader::getEventSize() const {
return dataFormat_.getDataSize();
}
void EventsHeader::read(const std::string& filename) {
if (! file_exists(filename)) {
std::ostringstream oss;
oss << "data::EventHeader::read() file '" << filename << "' does not exist";
throw exception::Base(oss.str());
}
std::fstream fstream;
fstream.open(formatFilename(filename).c_str(), std::ios::in | std::ios::binary);
fstream.seekg(0, std::ios::beg);
{
char tempId[5];
// check for correct file ID
fstream.read(tempId, 4);
std::string fileId(tempId);
tempId[sizeof(tempId)-1] = 0;
if (std::string(tempId) != ID) {
std::ostringstream oss;
oss << "data::EventsHeader bad file header '" << tempId << "' vs '" << ID << "'";
throw exception::Base(oss.str());
}
}
{
unsigned int fileEpochDays;
// read file version from file
fstream.read((char*)&fileEpochDays, sizeof(unsigned int));
date_ = STARTOFEPOCH + gr::days(fileEpochDays);
}
dataFormat_.fromStream(fstream);
// check if read position corresponds to header size
assert(fstream.tellg() == getSize());
fstream.seekg(0, std::ios::end);
unsigned int filesize = fstream.tellg();
fstream.close();
filesize -= getSize();
numberOfEvents_ = filesize / getEventSize();
if (logger_.isDebugEnabled())
logger_.debugStream() << "read() date " << date_ << " #events " << numberOfEvents_ << " eventsize " << getEventSize() << " filesize " << filesize;
if (numberOfEvents_ * getEventSize() != filesize)
throw exception::Base("data::EventsHeader file size mismatch");
}
Event::AP EventsHeader::createEvent(std::iostream& stream) const {
return Event::AP(new Event(dataFormat_, date_, stream));
}
std::string EventsHeader::formatFilename(const std::string& fileformat) const {
if (! date_.is_not_a_date()) {
gr::date_facet *datefacet = new gr::date_facet();
datefacet->format(fileformat.c_str());
std::ostringstream filenamestream;
filenamestream.imbue(std::locale(std::locale::classic(), datefacet));
filenamestream << date_;
return filenamestream.str();
} else {
return fileformat;
throw exception::Base("data::EventsHeader formatFilename() ERROR: no file date");
}
}
void EventsHeader::write(const std::string& filename) const {
if (date_ == gr::date(pt::not_a_date_time))
throw exception::Base("data::EventsHeader writeHeader() invalid file date");
std::fstream fstream;
fstream.open(formatFilename(filename).c_str(), std::ios::out | std::ios::trunc | std::ios::binary);
fstream.seekg(0, std::ios::beg);
fstream.write(ID, 4);
{
unsigned int fileEpochDays = (date_ - STARTOFEPOCH).days();
fstream.write((char*) &fileEpochDays, sizeof(unsigned int));
}
dataFormat_.toStream(fstream);
assert(fstream.tellg() == getSize());
fstream.close();
}
bool EventsHeader::fileExists(const std::string& filename) const {
return file_exists(formatFilename(filename));
}
bool EventsHeader::operator==(const EventsHeader& other) {
return date_ == other.date_ && dataFormat_ == other.dataFormat_;
}
bool EventsHeader::operator!=(const EventsHeader& other) {
return !(*this == other);
}
unsigned int EventsHeader::getSize() const {
return 10;
}
}
}
<commit_msg>adapt header size<commit_after>#include <fstream>
#include "data/EventsHeader.h"
#include "data/Event.h"
#include "exception/Base.h"
namespace blitzortung {
namespace data {
const char* EventsHeader::ID = "BOSF";
const gr::date EventsHeader::STARTOFEPOCH = gr::date(1970, 1, 1);
bool file_exists(std::string filename) {
std::ifstream file;
file.open(filename.c_str(), std::ios::in);
file.close();
return ! file.fail();
}
EventsHeader::EventsHeader(const gr::date& date) :
date_(date),
logger_("data.EventsHeader")
{
if (logger_.isDebugEnabled())
logger_.debugStream() << "construct() date " << date;
}
EventsHeader::~EventsHeader() {
}
const gr::date& EventsHeader::getDate() const {
return date_;
}
void EventsHeader::setDate(const gr::date& date) {
date_ = date;
}
unsigned int EventsHeader::getNumberOfEvents() const {
return numberOfEvents_;
}
unsigned int EventsHeader::getEventSize() const {
return dataFormat_.getDataSize();
}
void EventsHeader::read(const std::string& filename) {
if (! file_exists(filename)) {
std::ostringstream oss;
oss << "data::EventHeader::read() file '" << filename << "' does not exist";
throw exception::Base(oss.str());
}
std::fstream fstream;
fstream.open(formatFilename(filename).c_str(), std::ios::in | std::ios::binary);
fstream.seekg(0, std::ios::beg);
{
char tempId[5];
// check for correct file ID
fstream.read(tempId, 4);
std::string fileId(tempId);
tempId[sizeof(tempId)-1] = 0;
if (std::string(tempId) != ID) {
std::ostringstream oss;
oss << "data::EventsHeader bad file header '" << tempId << "' vs '" << ID << "'";
throw exception::Base(oss.str());
}
}
{
unsigned int fileEpochDays;
// read file version from file
fstream.read((char*)&fileEpochDays, sizeof(unsigned int));
date_ = STARTOFEPOCH + gr::days(fileEpochDays);
}
dataFormat_.fromStream(fstream);
// check if read position corresponds to header size
assert(fstream.tellg() == getSize());
fstream.seekg(0, std::ios::end);
unsigned int filesize = fstream.tellg();
fstream.close();
filesize -= getSize();
numberOfEvents_ = filesize / getEventSize();
if (logger_.isDebugEnabled())
logger_.debugStream() << "read() date " << date_ << " #events " << numberOfEvents_ << " eventsize " << getEventSize() << " filesize " << filesize;
if (numberOfEvents_ * getEventSize() != filesize)
throw exception::Base("data::EventsHeader file size mismatch");
}
Event::AP EventsHeader::createEvent(std::iostream& stream) const {
return Event::AP(new Event(dataFormat_, date_, stream));
}
std::string EventsHeader::formatFilename(const std::string& fileformat) const {
if (! date_.is_not_a_date()) {
gr::date_facet *datefacet = new gr::date_facet();
datefacet->format(fileformat.c_str());
std::ostringstream filenamestream;
filenamestream.imbue(std::locale(std::locale::classic(), datefacet));
filenamestream << date_;
return filenamestream.str();
} else {
return fileformat;
throw exception::Base("data::EventsHeader formatFilename() ERROR: no file date");
}
}
void EventsHeader::write(const std::string& filename) const {
if (date_ == gr::date(pt::not_a_date_time))
throw exception::Base("data::EventsHeader writeHeader() invalid file date");
std::fstream fstream;
fstream.open(formatFilename(filename).c_str(), std::ios::out | std::ios::trunc | std::ios::binary);
fstream.seekg(0, std::ios::beg);
fstream.write(ID, 4);
{
unsigned int fileEpochDays = (date_ - STARTOFEPOCH).days();
fstream.write((char*) &fileEpochDays, sizeof(unsigned int));
}
dataFormat_.toStream(fstream);
//std::cout << " header size: " << fstream.tellg() << " should be " << getSize();
assert(fstream.tellg() == getSize());
fstream.close();
}
bool EventsHeader::fileExists(const std::string& filename) const {
return file_exists(formatFilename(filename));
}
bool EventsHeader::operator==(const EventsHeader& other) {
return date_ == other.date_ && dataFormat_ == other.dataFormat_;
}
bool EventsHeader::operator!=(const EventsHeader& other) {
return !(*this == other);
}
unsigned int EventsHeader::getSize() const {
return 12;
}
}
}
<|endoftext|> |
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2009 Sandro Santilli <strk@keybit.net>
* Copyright (C) 2001-2002 Vivid Solutions Inc.
* Copyright (C) 2005 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: operation/IsSimpleOp.java rev. 1.22 (JTS-1.10)
*
**********************************************************************/
#include <geos/operation/IsSimpleOp.h>
//#include <geos/operation/EndpointInfo.h>
#include <geos/algorithm/BoundaryNodeRule.h>
#include <geos/algorithm/LineIntersector.h>
#include <geos/geomgraph/GeometryGraph.h>
#include <geos/geomgraph/Edge.h>
#include <geos/geomgraph/EdgeIntersection.h>
#include <geos/geomgraph/index/SegmentIntersector.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/MultiPoint.h>
#include <geos/geom/MultiLineString.h>
#include <geos/geom/Point.h>
#include <geos/geom/Coordinate.h>
#include <set>
#include <cassert>
using namespace std;
using namespace geos::algorithm;
using namespace geos::geomgraph;
using namespace geos::geomgraph::index;
using namespace geos::geom;
namespace geos {
namespace operation { // geos.operation
// This is supposedly a private of IsSimpleOp...
class EndpointInfo
{
public:
Coordinate pt;
bool isClosed;
int degree;
EndpointInfo(const geom::Coordinate& newPt);
const Coordinate& getCoordinate() const { return pt; }
void addEndpoint(bool newIsClosed)
{
degree++;
isClosed |= newIsClosed;
}
};
EndpointInfo::EndpointInfo(const Coordinate& newPt)
{
pt=newPt;
isClosed=false;
degree=0;
}
// -----------------------------------------------------
/*public*/
IsSimpleOp::IsSimpleOp()
:
isClosedEndpointsInInterior(true),
geom(0),
nonSimpleLocation()
{}
/*public*/
IsSimpleOp::IsSimpleOp(const Geometry& g)
:
isClosedEndpointsInInterior(true),
geom(&g),
nonSimpleLocation()
{}
/*public*/
IsSimpleOp::IsSimpleOp(const Geometry& g,
const BoundaryNodeRule& boundaryNodeRule)
:
isClosedEndpointsInInterior( ! boundaryNodeRule.isInBoundary(2) ),
geom(&g),
nonSimpleLocation()
{}
/*public*/
bool
IsSimpleOp::isSimple()
{
nonSimpleLocation.reset();
if ( dynamic_cast<const LineString*>(geom) )
return isSimpleLinearGeometry(geom);
if ( dynamic_cast<const MultiLineString*>(geom) )
return isSimpleLinearGeometry(geom);
const MultiPoint* mp = dynamic_cast<const MultiPoint*>(geom);
if ( mp ) return isSimpleMultiPoint(*mp);
// all other geometry types are simple by definition
return true;
}
/*public*/
bool
IsSimpleOp::isSimple(const LineString *geom)
{
return isSimpleLinearGeometry(geom);
}
/*public*/
bool
IsSimpleOp::isSimple(const MultiLineString *geom)
{
return isSimpleLinearGeometry(geom);
}
/*public*/
bool
IsSimpleOp::isSimple(const MultiPoint *mp)
{
return isSimpleMultiPoint(*mp);
}
/*private*/
bool
IsSimpleOp::isSimpleMultiPoint(const MultiPoint& mp)
{
if (mp.isEmpty()) return true;
set<const Coordinate*, CoordinateLessThen> points;
for (std::size_t i=0, n=mp.getNumGeometries(); i<n; ++i)
{
assert(dynamic_cast<const Point*>(mp.getGeometryN(i)));
const Point *pt=static_cast<const Point*>(mp.getGeometryN(i));
const Coordinate *p=pt->getCoordinate();
if (points.find(p) != points.end())
{
nonSimpleLocation.reset(new Coordinate(*p));
return false;
}
points.insert(p);
}
return true;
}
bool
IsSimpleOp::isSimpleLinearGeometry(const Geometry *geom)
{
if (geom->isEmpty()) return true;
GeometryGraph graph(0,geom);
LineIntersector li;
std::auto_ptr<SegmentIntersector> si (graph.computeSelfNodes(&li,true));
// if no self-intersection, must be simple
if (!si->hasIntersection()) return true;
if (si->hasProperIntersection())
{
nonSimpleLocation.reset(
new Coordinate(si->getProperIntersectionPoint())
);
return false;
}
if (hasNonEndpointIntersection(graph)) return false;
if ( isClosedEndpointsInInterior ) {
if (hasClosedEndpointIntersection(graph)) return false;
}
return true;
}
/*private*/
bool
IsSimpleOp::hasNonEndpointIntersection(GeometryGraph &graph)
{
vector<Edge*> *edges=graph.getEdges();
for (vector<Edge*>::iterator i=edges->begin();i<edges->end();i++) {
Edge *e=*i;
int maxSegmentIndex=e->getMaximumSegmentIndex();
EdgeIntersectionList &eiL=e->getEdgeIntersectionList();
for ( EdgeIntersectionList::iterator eiIt=eiL.begin(),
eiEnd=eiL.end(); eiIt!=eiEnd; ++eiIt )
{
EdgeIntersection *ei=*eiIt;
if (!ei->isEndPoint(maxSegmentIndex))
{
nonSimpleLocation.reset(
new Coordinate(ei->getCoordinate())
);
return true;
}
}
}
return false;
}
/*private*/
bool
IsSimpleOp::hasClosedEndpointIntersection(GeometryGraph &graph)
{
map<const Coordinate*,EndpointInfo*,CoordinateLessThen> endPoints;
vector<Edge*> *edges=graph.getEdges();
for (vector<Edge*>::iterator i=edges->begin();i<edges->end();i++) {
Edge *e=*i;
//int maxSegmentIndex=e->getMaximumSegmentIndex();
bool isClosed=e->isClosed();
const Coordinate *p0=&e->getCoordinate(0);
addEndpoint(endPoints,p0,isClosed);
const Coordinate *p1=&e->getCoordinate(e->getNumPoints()-1);
addEndpoint(endPoints,p1,isClosed);
}
map<const Coordinate*,EndpointInfo*,CoordinateLessThen>::iterator it=endPoints.begin();
for (; it!=endPoints.end(); ++it) {
EndpointInfo *eiInfo=it->second;
if (eiInfo->isClosed && eiInfo->degree!=2) {
it=endPoints.begin();
for (; it!=endPoints.end(); ++it) {
EndpointInfo *ep=it->second;
delete ep;
}
nonSimpleLocation.reset(
new Coordinate( eiInfo->getCoordinate() )
);
return true;
}
}
it=endPoints.begin();
for (; it!=endPoints.end(); ++it) {
EndpointInfo *ep=it->second;
delete ep;
}
return false;
}
/*private*/
void
IsSimpleOp::addEndpoint(
map<const Coordinate*,EndpointInfo*,CoordinateLessThen>&endPoints,
const Coordinate *p,bool isClosed)
{
map<const Coordinate*,EndpointInfo*,CoordinateLessThen>::iterator it=endPoints.find(p);
EndpointInfo *eiInfo;
if (it==endPoints.end()) {
eiInfo=NULL;
} else {
eiInfo=it->second;
}
if (eiInfo==NULL) {
eiInfo=new EndpointInfo(*p);
endPoints[p]=eiInfo;
}
eiInfo->addEndpoint(isClosed);
}
} // namespace geos::operation
} // namespace geos
<commit_msg>Fix memory bug <commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2009 Sandro Santilli <strk@keybit.net>
* Copyright (C) 2001-2002 Vivid Solutions Inc.
* Copyright (C) 2005 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: operation/IsSimpleOp.java rev. 1.22 (JTS-1.10)
*
**********************************************************************/
#include <geos/operation/IsSimpleOp.h>
//#include <geos/operation/EndpointInfo.h>
#include <geos/algorithm/BoundaryNodeRule.h>
#include <geos/algorithm/LineIntersector.h>
#include <geos/geomgraph/GeometryGraph.h>
#include <geos/geomgraph/Edge.h>
#include <geos/geomgraph/EdgeIntersection.h>
#include <geos/geomgraph/index/SegmentIntersector.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/MultiPoint.h>
#include <geos/geom/MultiLineString.h>
#include <geos/geom/Point.h>
#include <geos/geom/Coordinate.h>
#include <set>
#include <cassert>
using namespace std;
using namespace geos::algorithm;
using namespace geos::geomgraph;
using namespace geos::geomgraph::index;
using namespace geos::geom;
namespace geos {
namespace operation { // geos.operation
// This is supposedly a private of IsSimpleOp...
class EndpointInfo
{
public:
Coordinate pt;
bool isClosed;
int degree;
EndpointInfo(const geom::Coordinate& newPt);
const Coordinate& getCoordinate() const { return pt; }
void addEndpoint(bool newIsClosed)
{
degree++;
isClosed |= newIsClosed;
}
};
EndpointInfo::EndpointInfo(const Coordinate& newPt)
{
pt=newPt;
isClosed=false;
degree=0;
}
// -----------------------------------------------------
/*public*/
IsSimpleOp::IsSimpleOp()
:
isClosedEndpointsInInterior(true),
geom(0),
nonSimpleLocation()
{}
/*public*/
IsSimpleOp::IsSimpleOp(const Geometry& g)
:
isClosedEndpointsInInterior(true),
geom(&g),
nonSimpleLocation()
{}
/*public*/
IsSimpleOp::IsSimpleOp(const Geometry& g,
const BoundaryNodeRule& boundaryNodeRule)
:
isClosedEndpointsInInterior( ! boundaryNodeRule.isInBoundary(2) ),
geom(&g),
nonSimpleLocation()
{}
/*public*/
bool
IsSimpleOp::isSimple()
{
nonSimpleLocation.reset();
if ( dynamic_cast<const LineString*>(geom) )
return isSimpleLinearGeometry(geom);
if ( dynamic_cast<const MultiLineString*>(geom) )
return isSimpleLinearGeometry(geom);
const MultiPoint* mp = dynamic_cast<const MultiPoint*>(geom);
if ( mp ) return isSimpleMultiPoint(*mp);
// all other geometry types are simple by definition
return true;
}
/*public*/
bool
IsSimpleOp::isSimple(const LineString *geom)
{
return isSimpleLinearGeometry(geom);
}
/*public*/
bool
IsSimpleOp::isSimple(const MultiLineString *geom)
{
return isSimpleLinearGeometry(geom);
}
/*public*/
bool
IsSimpleOp::isSimple(const MultiPoint *mp)
{
return isSimpleMultiPoint(*mp);
}
/*private*/
bool
IsSimpleOp::isSimpleMultiPoint(const MultiPoint& mp)
{
if (mp.isEmpty()) return true;
set<const Coordinate*, CoordinateLessThen> points;
for (std::size_t i=0, n=mp.getNumGeometries(); i<n; ++i)
{
assert(dynamic_cast<const Point*>(mp.getGeometryN(i)));
const Point *pt=static_cast<const Point*>(mp.getGeometryN(i));
const Coordinate *p=pt->getCoordinate();
if (points.find(p) != points.end())
{
nonSimpleLocation.reset(new Coordinate(*p));
return false;
}
points.insert(p);
}
return true;
}
bool
IsSimpleOp::isSimpleLinearGeometry(const Geometry *geom)
{
if (geom->isEmpty()) return true;
GeometryGraph graph(0,geom);
LineIntersector li;
std::auto_ptr<SegmentIntersector> si (graph.computeSelfNodes(&li,true));
// if no self-intersection, must be simple
if (!si->hasIntersection()) return true;
if (si->hasProperIntersection())
{
nonSimpleLocation.reset(
new Coordinate(si->getProperIntersectionPoint())
);
return false;
}
if (hasNonEndpointIntersection(graph)) return false;
if ( isClosedEndpointsInInterior ) {
if (hasClosedEndpointIntersection(graph)) return false;
}
return true;
}
/*private*/
bool
IsSimpleOp::hasNonEndpointIntersection(GeometryGraph &graph)
{
vector<Edge*> *edges=graph.getEdges();
for (vector<Edge*>::iterator i=edges->begin();i<edges->end();i++) {
Edge *e=*i;
int maxSegmentIndex=e->getMaximumSegmentIndex();
EdgeIntersectionList &eiL=e->getEdgeIntersectionList();
for ( EdgeIntersectionList::iterator eiIt=eiL.begin(),
eiEnd=eiL.end(); eiIt!=eiEnd; ++eiIt )
{
EdgeIntersection *ei=*eiIt;
if (!ei->isEndPoint(maxSegmentIndex))
{
nonSimpleLocation.reset(
new Coordinate(ei->getCoordinate())
);
return true;
}
}
}
return false;
}
/*private*/
bool
IsSimpleOp::hasClosedEndpointIntersection(GeometryGraph &graph)
{
map<const Coordinate*,EndpointInfo*,CoordinateLessThen> endPoints;
vector<Edge*> *edges=graph.getEdges();
for (vector<Edge*>::iterator i=edges->begin();i<edges->end();i++) {
Edge *e=*i;
//int maxSegmentIndex=e->getMaximumSegmentIndex();
bool isClosed=e->isClosed();
const Coordinate *p0=&e->getCoordinate(0);
addEndpoint(endPoints,p0,isClosed);
const Coordinate *p1=&e->getCoordinate(e->getNumPoints()-1);
addEndpoint(endPoints,p1,isClosed);
}
map<const Coordinate*,EndpointInfo*,CoordinateLessThen>::iterator it=endPoints.begin();
for (; it!=endPoints.end(); ++it) {
EndpointInfo *eiInfo=it->second;
if (eiInfo->isClosed && eiInfo->degree!=2) {
nonSimpleLocation.reset(
new Coordinate( eiInfo->getCoordinate() )
);
it=endPoints.begin();
for (; it!=endPoints.end(); ++it) {
EndpointInfo *ep=it->second;
delete ep;
}
return true;
}
}
it=endPoints.begin();
for (; it!=endPoints.end(); ++it) {
EndpointInfo *ep=it->second;
delete ep;
}
return false;
}
/*private*/
void
IsSimpleOp::addEndpoint(
map<const Coordinate*,EndpointInfo*,CoordinateLessThen>&endPoints,
const Coordinate *p,bool isClosed)
{
map<const Coordinate*,EndpointInfo*,CoordinateLessThen>::iterator it=endPoints.find(p);
EndpointInfo *eiInfo;
if (it==endPoints.end()) {
eiInfo=NULL;
} else {
eiInfo=it->second;
}
if (eiInfo==NULL) {
eiInfo=new EndpointInfo(*p);
endPoints[p]=eiInfo;
}
eiInfo->addEndpoint(isClosed);
}
} // namespace geos::operation
} // namespace geos
<|endoftext|> |
<commit_before>//===- Disassembler.cpp - Disassembler for hex strings --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements the disassembler of strings of bytes written in
// hexadecimal, from standard input or from a file.
//
//===----------------------------------------------------------------------===//
#include "Disassembler.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
using namespace llvm;
typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;
namespace {
class VectorMemoryObject : public MemoryObject {
private:
const ByteArrayTy &Bytes;
public:
VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}
uint64_t getBase() const { return 0; }
uint64_t getExtent() const { return Bytes.size(); }
int readByte(uint64_t Addr, uint8_t *Byte) const {
if (Addr > getExtent())
return -1;
*Byte = Bytes[Addr].first;
return 0;
}
};
}
static bool PrintInsts(const llvm::MCDisassembler &DisAsm,
llvm::MCInstPrinter &Printer, const ByteArrayTy &Bytes,
SourceMgr &SM) {
// Wrap the vector in a MemoryObject.
VectorMemoryObject memoryObject(Bytes);
// Disassemble it to strings.
uint64_t Size;
uint64_t Index;
for (Index = 0; Index < Bytes.size(); Index += Size) {
MCInst Inst;
if (DisAsm.getInstruction(Inst, Size, memoryObject, Index,
/*REMOVE*/ nulls())) {
Printer.printInst(&Inst);
outs() << "\n";
}
else {
SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
"invalid instruction encoding", "warning");
if (Size == 0)
Size = 1; // skip illegible bytes
}
}
return false;
}
int Disassembler::disassemble(const Target &T, const std::string &Triple,
MemoryBuffer &Buffer) {
// Set up disassembler.
llvm::OwningPtr<const llvm::MCAsmInfo> AsmInfo(T.createAsmInfo(Triple));
if (!AsmInfo) {
errs() << "error: no assembly info for target " << Triple << "\n";
return -1;
}
llvm::OwningPtr<const llvm::MCDisassembler> DisAsm(T.createMCDisassembler());
if (!DisAsm) {
errs() << "error: no disassembler for target " << Triple << "\n";
return -1;
}
llvm::MCInstPrinter *InstPrinter = T.createMCInstPrinter(0, *AsmInfo, outs());
if (!InstPrinter) {
errs() << "error: no instruction printer for target " << Triple << '\n';
return -1;
}
bool ErrorOccurred = false;
SourceMgr SM;
SM.AddNewSourceBuffer(&Buffer, SMLoc());
// Convert the input to a vector for disassembly.
ByteArrayTy ByteArray;
StringRef Str = Buffer.getBuffer();
while (!Str.empty()) {
// Strip horizontal whitespace.
if (size_t Pos = Str.find_first_not_of(" \t\r")) {
Str = Str.substr(Pos);
continue;
}
// If this is the end of a line or start of a comment, remove the rest of
// the line.
if (Str[0] == '\n' || Str[0] == '#') {
// Strip to the end of line if we already processed any bytes on this
// line. This strips the comment and/or the \n.
if (Str[0] == '\n')
Str = Str.substr(1);
else {
Str = Str.substr(Str.find_first_of('\n'));
if (!Str.empty())
Str = Str.substr(1);
}
continue;
}
// Get the current token.
size_t Next = Str.find_first_of(" \t\n\r#");
StringRef Value = Str.substr(0, Next);
// Convert to a byte and add to the byte vector.
unsigned ByteVal;
if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
// If we have an error, print it and skip to the end of line.
SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
"invalid input token", "error");
ErrorOccurred = true;
Str = Str.substr(Str.find('\n'));
ByteArray.clear();
continue;
}
ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
Str = Str.substr(Next);
}
if (!ByteArray.empty())
ErrorOccurred |= PrintInsts(*DisAsm, *InstPrinter, ByteArray, SM);
return ErrorOccurred;
}
<commit_msg>llvm-mc: Fix MCInstPrinter memory leaks.<commit_after>//===- Disassembler.cpp - Disassembler for hex strings --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements the disassembler of strings of bytes written in
// hexadecimal, from standard input or from a file.
//
//===----------------------------------------------------------------------===//
#include "Disassembler.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
using namespace llvm;
typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;
namespace {
class VectorMemoryObject : public MemoryObject {
private:
const ByteArrayTy &Bytes;
public:
VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}
uint64_t getBase() const { return 0; }
uint64_t getExtent() const { return Bytes.size(); }
int readByte(uint64_t Addr, uint8_t *Byte) const {
if (Addr > getExtent())
return -1;
*Byte = Bytes[Addr].first;
return 0;
}
};
}
static bool PrintInsts(const MCDisassembler &DisAsm,
MCInstPrinter &Printer, const ByteArrayTy &Bytes,
SourceMgr &SM) {
// Wrap the vector in a MemoryObject.
VectorMemoryObject memoryObject(Bytes);
// Disassemble it to strings.
uint64_t Size;
uint64_t Index;
for (Index = 0; Index < Bytes.size(); Index += Size) {
MCInst Inst;
if (DisAsm.getInstruction(Inst, Size, memoryObject, Index,
/*REMOVE*/ nulls())) {
Printer.printInst(&Inst);
outs() << "\n";
}
else {
SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
"invalid instruction encoding", "warning");
if (Size == 0)
Size = 1; // skip illegible bytes
}
}
return false;
}
int Disassembler::disassemble(const Target &T, const std::string &Triple,
MemoryBuffer &Buffer) {
// Set up disassembler.
OwningPtr<const MCAsmInfo> AsmInfo(T.createAsmInfo(Triple));
if (!AsmInfo) {
errs() << "error: no assembly info for target " << Triple << "\n";
return -1;
}
OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler());
if (!DisAsm) {
errs() << "error: no disassembler for target " << Triple << "\n";
return -1;
}
OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(0, *AsmInfo, outs()));
if (!IP) {
errs() << "error: no instruction printer for target " << Triple << '\n';
return -1;
}
bool ErrorOccurred = false;
SourceMgr SM;
SM.AddNewSourceBuffer(&Buffer, SMLoc());
// Convert the input to a vector for disassembly.
ByteArrayTy ByteArray;
StringRef Str = Buffer.getBuffer();
while (!Str.empty()) {
// Strip horizontal whitespace.
if (size_t Pos = Str.find_first_not_of(" \t\r")) {
Str = Str.substr(Pos);
continue;
}
// If this is the end of a line or start of a comment, remove the rest of
// the line.
if (Str[0] == '\n' || Str[0] == '#') {
// Strip to the end of line if we already processed any bytes on this
// line. This strips the comment and/or the \n.
if (Str[0] == '\n')
Str = Str.substr(1);
else {
Str = Str.substr(Str.find_first_of('\n'));
if (!Str.empty())
Str = Str.substr(1);
}
continue;
}
// Get the current token.
size_t Next = Str.find_first_of(" \t\n\r#");
StringRef Value = Str.substr(0, Next);
// Convert to a byte and add to the byte vector.
unsigned ByteVal;
if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
// If we have an error, print it and skip to the end of line.
SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
"invalid input token", "error");
ErrorOccurred = true;
Str = Str.substr(Str.find('\n'));
ByteArray.clear();
continue;
}
ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
Str = Str.substr(Next);
}
if (!ByteArray.empty())
ErrorOccurred |= PrintInsts(*DisAsm, *IP, ByteArray, SM);
return ErrorOccurred;
}
<|endoftext|> |
<commit_before>/* nuklear - v1.09 - public domain */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <math.h>
#include <limits.h>
#include <time.h>
#include "no_rt_util.h"
#include <GL/glew.h>
#include "glfw3.h"
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_IMPLEMENTATION
#define NK_GLFW_GL3_IMPLEMENTATION
#include "nuklear.h"
#include "nuklear_glfw_gl3.h"
#define WINDOW_WIDTH 1200
#define WINDOW_HEIGHT 800
#define MAX_VERTEX_BUFFER 512 * 1024
#define MAX_ELEMENT_BUFFER 128 * 1024
#define UNUSED(a) (void)a
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) < (b) ? (b) : (a))
#define LEN(a) (sizeof(a)/sizeof(a)[0])
/* ===============================================================
*
* EXAMPLE
*
* ===============================================================*/
/* This are some code examples to provide a small overview of what can be
* done with this library. To try out an example uncomment the include
* and the corresponding function. */
#include "style.c"
#include "calculator.c"
#include "overview.c"
#include "node_editor.c"
/* ===============================================================
*
* DEMO
*
* ===============================================================*/
static void error_callback(int e, const char *d)
{printf("Error %d: %s\n", e, d);}
//int CALLBACK WinMain(
// _In_ HINSTANCE hInstance,
// _In_ HINSTANCE hPrevInstance,
// _In_ LPSTR lpCmdLine,
// _In_ int nCmdShow
//)
int main(void)
{
/* Platform */
static GLFWwindow *win;
int width = 0, height = 0;
struct nk_context *ctx;
struct nk_color background;
/* GLFW */
glfwSetErrorCallback(error_callback);
if (!glfwInit()) {
fprintf(stdout, "[GFLW] failed to init!\n");
exit(1);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
win = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo", NULL, NULL);
glfwMakeContextCurrent(win);
glfwGetWindowSize(win, &width, &height);
/* OpenGL */
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
glewExperimental = 1;
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to setup GLEW\n");
exit(1);
}
/* Vertex Array Object */
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
// An array of 3 vectors which represents 3 vertices
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
// This will identify our vertex buffer
GLuint vertexbuffer;
// Generate 1 buffer, put the resulting identifier in vertexbuffer
glGenBuffers(1, &vertexbuffer);
// The following commands will talk about our 'vertexbuffer' buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// Give our vertices to OpenGL.
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
/* nuklear */
ctx = nk_glfw3_init(win, NK_GLFW3_INSTALL_CALLBACKS);
/* Load Fonts: if none of these are loaded a default font will be used */
/* Load Cursor: if you uncomment cursor loading please hide the cursor */
{struct nk_font_atlas *atlas;
nk_glfw3_font_stash_begin(&atlas);
/*struct nk_font *droid = nk_font_atlas_add_from_file(atlas, "../../../extra_font/DroidSans.ttf", 14, 0);*/
/*struct nk_font *roboto = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Roboto-Regular.ttf", 14, 0);*/
/*struct nk_font *future = nk_font_atlas_add_from_file(atlas, "../../../extra_font/kenvector_future_thin.ttf", 13, 0);*/
/*struct nk_font *clean = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyClean.ttf", 12, 0);*/
/*struct nk_font *tiny = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyTiny.ttf", 10, 0);*/
/*struct nk_font *cousine = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Cousine-Regular.ttf", 13, 0);*/
nk_glfw3_font_stash_end();
/*nk_style_load_all_cursors(ctx, atlas->cursors);*/
/*nk_style_set_font(ctx, &droid->handle);*/}
/* style.c */
/*set_style(ctx, THEME_WHITE);*/
/*set_style(ctx, THEME_RED);*/
/*set_style(ctx, THEME_BLUE);*/
/*set_style(ctx, THEME_DARK);*/
background = nk_rgb(28,48,62);
while (!glfwWindowShouldClose(win))
{
/* Input */
glfwPollEvents();
nk_glfw3_new_frame();
/* GUI */
{struct nk_panel layout;
if (nk_begin(ctx, &layout, "Demo", nk_rect(50, 50, 230, 250),
NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE|
NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE))
{
enum {EASY, HARD};
static int op = EASY;
static int property = 20;
nk_layout_row_static(ctx, 30, 80, 1);
if(nk_button_label(ctx, "button"))
fprintf(stdout, "button pressed\n");
nk_layout_row_dynamic(ctx, 30, 2);
if (nk_option_label(ctx, "easy", op == EASY)) op = EASY;
if (nk_option_label(ctx, "hard", op == HARD)) op = HARD;
nk_layout_row_dynamic(ctx, 25, 1);
nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1);
{struct nk_panel combo;
nk_layout_row_dynamic(ctx, 20, 1);
nk_label(ctx, "background:", NK_TEXT_LEFT);
nk_layout_row_dynamic(ctx, 25, 1);
if (nk_combo_begin_color(ctx, &combo, background, nk_vec2(nk_widget_width(ctx), 400))) {
nk_layout_row_dynamic(ctx, 120, 1);
background = nk_color_picker(ctx, background, NK_RGBA);
nk_layout_row_dynamic(ctx, 25, 1);
background.r = (nk_byte)nk_propertyi(ctx, "#R:", 0, background.r, 255, 1,1);
background.g = (nk_byte)nk_propertyi(ctx, "#G:", 0, background.g, 255, 1,1);
background.b = (nk_byte)nk_propertyi(ctx, "#B:", 0, background.b, 255, 1,1);
background.a = (nk_byte)nk_propertyi(ctx, "#A:", 0, background.a, 255, 1,1);
nk_combo_end(ctx);
}}
}
nk_end(ctx);}
/* -------------- EXAMPLES ---------------- */
/*calculator(ctx);*/
/*overview(ctx);*/
node_editor(ctx);
/* ----------------------------------------- */
/* Draw */
{float bg[4];
nk_color_fv(bg, background);
glfwGetWindowSize(win, &width, &height);
glViewport(0, 0, width, height);
/* Draw opneGL triangle */
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0; 3 vertices total -> 1 triangle
glDisableVertexAttribArray(0);
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(bg[0], bg[1], bg[2], bg[3]);
/* IMPORTANT: `nk_glfw_render` modifies some global OpenGL state
* with blending, scissor, face culling, depth test and viewport and
* defaults everything back into a default state.
* Make sure to either a.) save and restore or b.) reset your own state after
* rendering the UI. */
nk_glfw3_render(NK_ANTI_ALIASING_ON, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER);
glfwSwapBuffers(win);}
}
nk_glfw3_shutdown();
glfwTerminate();
return 0;
}
<commit_msg>Can use modern OpenGL with nuklear<commit_after>/* nuklear - v1.09 - public domain */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <math.h>
#include <limits.h>
#include <time.h>
#include "no_rt_util.h"
#include <GL/glew.h>
#include "glfw3.h"
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_IMPLEMENTATION
#define NK_GLFW_GL3_IMPLEMENTATION
#include "nuklear.h"
#include "nuklear_glfw_gl3.h"
#define WINDOW_WIDTH 1200
#define WINDOW_HEIGHT 800
#define MAX_VERTEX_BUFFER 512 * 1024
#define MAX_ELEMENT_BUFFER 128 * 1024
#define UNUSED(a) (void)a
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) < (b) ? (b) : (a))
#define LEN(a) (sizeof(a)/sizeof(a)[0])
/* ===============================================================
*
* EXAMPLE
*
* ===============================================================*/
/* This are some code examples to provide a small overview of what can be
* done with this library. To try out an example uncomment the include
* and the corresponding function. */
// #include "style.c"
// #include "calculator.c"
// #include "overview.c"
#include "node_editor.c"
/* ===============================================================
*
* DEMO
*
* ===============================================================*/
static void error_callback(int e, const char *d)
{printf("Error %d: %s\n", e, d);}
//int CALLBACK WinMain(
// _In_ HINSTANCE hInstance,
// _In_ HINSTANCE hPrevInstance,
// _In_ LPSTR lpCmdLine,
// _In_ int nCmdShow
//)
int main(void)
{
/* Platform */
static GLFWwindow *win;
int width = 0, height = 0;
struct nk_context *ctx;
struct nk_color background;
/* GLFW */
glfwSetErrorCallback(error_callback);
if (!glfwInit()) {
fprintf(stdout, "[GFLW] failed to init!\n");
exit(1);
}
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
win = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo", NULL, NULL);
glfwMakeContextCurrent(win);
glfwGetWindowSize(win, &width, &height);
/* OpenGL */
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
glewExperimental = 1;
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to setup GLEW\n");
exit(1);
}
/* Vertex Array Object */
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
// An array of 3 vectors which represents 3 vertices
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
// This will identify our vertex buffer
GLuint vertexbuffer;
// Generate 1 buffer, put the resulting identifier in vertexbuffer
glGenBuffers(1, &vertexbuffer);
// The following commands will talk about our 'vertexbuffer' buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// Give our vertices to OpenGL.
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
/* nuklear */
ctx = nk_glfw3_init(win, NK_GLFW3_INSTALL_CALLBACKS);
/* Load Fonts: if none of these are loaded a default font will be used */
/* Load Cursor: if you uncomment cursor loading please hide the cursor */
{struct nk_font_atlas *atlas;
nk_glfw3_font_stash_begin(&atlas);
/*struct nk_font *droid = nk_font_atlas_add_from_file(atlas, "../../../extra_font/DroidSans.ttf", 14, 0);*/
/*struct nk_font *roboto = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Roboto-Regular.ttf", 14, 0);*/
/*struct nk_font *future = nk_font_atlas_add_from_file(atlas, "../../../extra_font/kenvector_future_thin.ttf", 13, 0);*/
/*struct nk_font *clean = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyClean.ttf", 12, 0);*/
/*struct nk_font *tiny = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyTiny.ttf", 10, 0);*/
/*struct nk_font *cousine = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Cousine-Regular.ttf", 13, 0);*/
nk_glfw3_font_stash_end();
/*nk_style_load_all_cursors(ctx, atlas->cursors);*/
/*nk_style_set_font(ctx, &droid->handle);*/}
/* style.c */
/*set_style(ctx, THEME_WHITE);*/
/*set_style(ctx, THEME_RED);*/
/*set_style(ctx, THEME_BLUE);*/
/*set_style(ctx, THEME_DARK);*/
background = nk_rgb(28,48,62);
while (!glfwWindowShouldClose(win))
{
/* Input */
glfwPollEvents();
nk_glfw3_new_frame();
/* GUI */
{struct nk_panel layout;
if (nk_begin(ctx, &layout, "Demo", nk_rect(50, 50, 230, 250),
NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE|
NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE))
{
enum {EASY, HARD};
static int op = EASY;
static int property = 20;
nk_layout_row_static(ctx, 30, 80, 1);
if(nk_button_label(ctx, "button"))
fprintf(stdout, "button pressed\n");
nk_layout_row_dynamic(ctx, 30, 2);
if (nk_option_label(ctx, "easy", op == EASY)) op = EASY;
if (nk_option_label(ctx, "hard", op == HARD)) op = HARD;
nk_layout_row_dynamic(ctx, 25, 1);
nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1);
{struct nk_panel combo;
nk_layout_row_dynamic(ctx, 20, 1);
nk_label(ctx, "background:", NK_TEXT_LEFT);
nk_layout_row_dynamic(ctx, 25, 1);
if (nk_combo_begin_color(ctx, &combo, background, nk_vec2(nk_widget_width(ctx), 400))) {
nk_layout_row_dynamic(ctx, 120, 1);
background = nk_color_picker(ctx, background, NK_RGBA);
nk_layout_row_dynamic(ctx, 25, 1);
background.r = (nk_byte)nk_propertyi(ctx, "#R:", 0, background.r, 255, 1,1);
background.g = (nk_byte)nk_propertyi(ctx, "#G:", 0, background.g, 255, 1,1);
background.b = (nk_byte)nk_propertyi(ctx, "#B:", 0, background.b, 255, 1,1);
background.a = (nk_byte)nk_propertyi(ctx, "#A:", 0, background.a, 255, 1,1);
nk_combo_end(ctx);
}}
}
nk_end(ctx);}
/* -------------- EXAMPLES ---------------- */
/*calculator(ctx);*/
/*overview(ctx);*/
node_editor(ctx);
/* ----------------------------------------- */
/* Draw */
{float bg[4];
nk_color_fv(bg, background);
glfwGetWindowSize(win, &width, &height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(bg[0], bg[1], bg[2], bg[3]);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
/* IMPORTANT: `nk_glfw_render` modifies some global OpenGL state
* with blending, scissor, face culling, depth test and viewport and
* defaults everything back into a default state.
* Make sure to either a.) save and restore or b.) reset your own state after
* rendering the UI. */
nk_glfw3_render(NK_ANTI_ALIASING_ON, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER);
glfwSwapBuffers(win);}
}
nk_glfw3_shutdown();
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before>#include <vector>
#include "../lib/hayai/hayai.hpp"
#include "../lib/hayai/hayai_posix_main.cpp"
#include "../src/vector.hpp"
using namespace lsh;
std::vector<bool> c(128);
BENCHMARK(vector, vector, 10000, 1000) {
lsh::vector v(c);
}
<commit_msg>Add all vector benchmarks<commit_after>#include <vector>
#include "../lib/hayai/hayai.hpp"
#include "../lib/hayai/hayai_posix_main.cpp"
#include "../src/vector.hpp"
using namespace lsh;
std::vector<bool> c(128);
vector u = vector::random(128);
vector v = vector::random(128);
BENCHMARK(vector, vector, 10000, 200) {
lsh::vector v(c);
}
BENCHMARK(vector, size, 10000, 75000) {
v.size();
}
BENCHMARK(vector, get, 10000, 18000) {
v.get(64);
}
BENCHMARK(vector, equals, 10000, 10000) {
bool f = v == u;
}
BENCHMARK(vector, dot_product, 10000, 10000) {
v * u;
}
BENCHMARK(vector, and, 10000, 500) {
v & u;
}
BENCHMARK(vector, hash, 10000, 28000) {
v.hash();
}
BENCHMARK(vector, distance, 10000, 9000) {
vector::distance(u, v);
}
BENCHMARK(vector, random, 10000, 10) {
vector::random(128);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <gtest/gtest.h>
#include <QtCore>
#include <QApplication>
#include <QtQuick>
#include "../src/cplugin.h"
#include "../src/cordova_config.hpp"
TEST(CordovaInternal, format_double_int_int) {
auto t = std::make_tuple(1.1, 2, 3);
auto doc = QJsonDocument().fromJson(QString("[ %1 ]").arg(CordovaInternal::tuple2str(t)).toUtf8());
EXPECT_EQ(doc.isArray(), true);
EXPECT_EQ(doc.array().size(), 3);
EXPECT_EQ(doc.array().at(1).toInt(), 2);
EXPECT_EQ(doc.array().at(2).toInt(), 3);
EXPECT_EQ(doc.array().at(0).toDouble(), 1.1);
}
TEST(CordovaInternal, format_obj_bool) {
QVariantMap obj;
obj.insert("a", 1);
obj.insert("b", 2);
obj.insert("c", "string");
auto t = std::make_tuple(obj, true);
auto doc = QJsonDocument().fromJson(QString("[ %1 ]").arg(CordovaInternal::tuple2str(t)).toUtf8());
EXPECT_EQ(doc.isArray(), true);
EXPECT_EQ(doc.array().size(), 2);
EXPECT_EQ(doc.array().at(1).toBool(), true);
auto o = doc.array().at(0).toObject();
EXPECT_EQ(o.size(), 3);
EXPECT_EQ(o.value("a").toInt(), 1);
EXPECT_EQ(o.value("b").toInt(), 2);
EXPECT_EQ(o.value("c").toString(), "string");
}
TEST(CordovaInternal, config) {
CordovaInternal::Config config("../xml/config.xml");
EXPECT_EQ(config.content(), "index.html");
EXPECT_EQ(config.appId(), "io.cordova.helloCordova");
EXPECT_EQ(config.appVersion(), "2.0.0");
EXPECT_EQ(config.fullscreen(), false);
}
TEST(Cordova, WhiteList) {
int argc = 0;
QApplication app(argc, NULL);
QQmlApplicationEngine view;
view.addImportPath(QDir("./cordova_ubuntu/").absolutePath());
QDir wwwDir("../tests/data/www");
QDir workingDir = QApplication::applicationDirPath();
view.rootContext()->setContextProperty("www", wwwDir.absolutePath());
view.load(QUrl(QString("%1/cordova_ubuntu/qml/main.qml").arg(workingDir.absolutePath())));
QTimer timer;
timer.connect(&timer, &QTimer::timeout, [&]() {
QApplication::quit();
});
timer.start(1000);
EXPECT_EQ(app.exec(), 0);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>add missing license header<commit_after>/*
* Copyright 2014 Canonical Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <gtest/gtest.h>
#include <QtCore>
#include <QApplication>
#include <QtQuick>
#include "../src/cplugin.h"
#include "../src/cordova_config.hpp"
TEST(CordovaInternal, format_double_int_int) {
auto t = std::make_tuple(1.1, 2, 3);
auto doc = QJsonDocument().fromJson(QString("[ %1 ]").arg(CordovaInternal::tuple2str(t)).toUtf8());
EXPECT_EQ(doc.isArray(), true);
EXPECT_EQ(doc.array().size(), 3);
EXPECT_EQ(doc.array().at(1).toInt(), 2);
EXPECT_EQ(doc.array().at(2).toInt(), 3);
EXPECT_EQ(doc.array().at(0).toDouble(), 1.1);
}
TEST(CordovaInternal, format_obj_bool) {
QVariantMap obj;
obj.insert("a", 1);
obj.insert("b", 2);
obj.insert("c", "string");
auto t = std::make_tuple(obj, true);
auto doc = QJsonDocument().fromJson(QString("[ %1 ]").arg(CordovaInternal::tuple2str(t)).toUtf8());
EXPECT_EQ(doc.isArray(), true);
EXPECT_EQ(doc.array().size(), 2);
EXPECT_EQ(doc.array().at(1).toBool(), true);
auto o = doc.array().at(0).toObject();
EXPECT_EQ(o.size(), 3);
EXPECT_EQ(o.value("a").toInt(), 1);
EXPECT_EQ(o.value("b").toInt(), 2);
EXPECT_EQ(o.value("c").toString(), "string");
}
TEST(CordovaInternal, config) {
CordovaInternal::Config config("../xml/config.xml");
EXPECT_EQ(config.content(), "index.html");
EXPECT_EQ(config.appId(), "io.cordova.helloCordova");
EXPECT_EQ(config.appVersion(), "2.0.0");
EXPECT_EQ(config.fullscreen(), false);
}
TEST(Cordova, WhiteList) {
int argc = 0;
QApplication app(argc, NULL);
QQmlApplicationEngine view;
view.addImportPath(QDir("./cordova_ubuntu/").absolutePath());
QDir wwwDir("../tests/data/www");
QDir workingDir = QApplication::applicationDirPath();
view.rootContext()->setContextProperty("www", wwwDir.absolutePath());
view.load(QUrl(QString("%1/cordova_ubuntu/qml/main.qml").arg(workingDir.absolutePath())));
QTimer timer;
timer.connect(&timer, &QTimer::timeout, [&]() {
QApplication::quit();
});
timer.start(1000);
EXPECT_EQ(app.exec(), 0);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>#include "MeshSprLoader.h"
#include "MeshSymLoader.h"
#include "FilepathHelper.h"
#include "SymbolPool.h"
#include "MeshIO.h"
#include <sprite2/Mesh.h>
#include <sprite2/MeshSprite.h>
#include <sprite2/MeshSymbol.h>
#include <sprite2/MeshTriangle.h>
#include <simp/NodeMeshSpr.h>
#include <simp/from_int.h>
#include <assert.h>
namespace gum
{
MeshSprLoader::MeshSprLoader(s2::MeshSprite* spr)
: m_spr(spr)
{
if (m_spr) {
m_spr->AddReference();
}
}
MeshSprLoader::~MeshSprLoader()
{
if (m_spr) {
m_spr->RemoveReference();
}
}
void MeshSprLoader::LoadJson(const Json::Value& val, const std::string& dir)
{
if (!m_spr || !val.isMember("mesh")) {
return;
}
const Json::Value& mesh_val = val["mesh"];
s2::MeshTransform2& trans = m_spr->GetMeshTrans();
const s2::Mesh* mesh = VI_DOWNCASTING<s2::MeshSymbol*>(m_spr->GetSymbol())->GetMesh();
MeshIO::Load(mesh_val, trans, *mesh);
trans.StoreToMesh(mesh);
if (mesh_val.isMember("base_symbol")) {
std::string base_path = FilepathHelper::Absolute(dir, mesh_val["base_symbol"].asString());
s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(base_path);
m_spr->SetBaseSym(base_sym);
base_sym->RemoveReference();
}
}
void MeshSprLoader::LoadBin(const simp::NodeMeshSpr* node)
{
if (!m_spr) {
return;
}
s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(node->base_id);
m_spr->SetBaseSym(base_sym);
base_sym->RemoveReference();
assert(m_spr->GetSymbol()->Type() == s2::SYM_MESH);
s2::MeshSymbol* mesh_sym = VI_DOWNCASTING<s2::MeshSymbol*>(m_spr->GetSymbol());
s2::Mesh* mesh = mesh_sym->GetMesh();
if (!mesh) {
return;
}
s2::MeshTransform2& trans = m_spr->GetMeshTrans();
trans.Clear();
const std::vector<s2::MeshTriangle*>& tris = mesh->GetTriangles();
int idx =0;
for (int i = 0; i < node->n; ++i)
{
sm::vec2 f, t;
f.x = simp::int2float(int16_t(node->vertices[idx++]), 16);
f.y = simp::int2float(int16_t(node->vertices[idx++]), 16);
t.x = simp::int2float(int16_t(node->vertices[idx++]), 16);
t.y = simp::int2float(int16_t(node->vertices[idx++]), 16);
int idx = 0;
sm::vec2 pos = t - f;
for (int j = 0, m = tris.size(); j < m; ++j) {
for (int k = 0; k < 3; ++k) {
if (f == tris[j]->nodes[k]->ori_xy) {
trans.Add(idx, pos);
}
++idx;
}
}
}
trans.StoreToMesh(mesh);
}
}<commit_msg>[FIXED] mesh spr trans loader<commit_after>#include "MeshSprLoader.h"
#include "MeshSymLoader.h"
#include "FilepathHelper.h"
#include "SymbolPool.h"
#include "MeshIO.h"
#include <sprite2/Mesh.h>
#include <sprite2/MeshSprite.h>
#include <sprite2/MeshSymbol.h>
#include <sprite2/MeshTriangle.h>
#include <simp/NodeMeshSpr.h>
#include <simp/from_int.h>
#include <assert.h>
namespace gum
{
MeshSprLoader::MeshSprLoader(s2::MeshSprite* spr)
: m_spr(spr)
{
if (m_spr) {
m_spr->AddReference();
}
}
MeshSprLoader::~MeshSprLoader()
{
if (m_spr) {
m_spr->RemoveReference();
}
}
void MeshSprLoader::LoadJson(const Json::Value& val, const std::string& dir)
{
if (!m_spr || !val.isMember("mesh")) {
return;
}
const Json::Value& mesh_val = val["mesh"];
s2::MeshTransform2& trans = m_spr->GetMeshTrans();
const s2::Mesh* mesh = VI_DOWNCASTING<s2::MeshSymbol*>(m_spr->GetSymbol())->GetMesh();
MeshIO::Load(mesh_val, trans, *mesh);
trans.StoreToMesh(mesh);
if (mesh_val.isMember("base_symbol")) {
std::string base_path = FilepathHelper::Absolute(dir, mesh_val["base_symbol"].asString());
s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(base_path);
m_spr->SetBaseSym(base_sym);
base_sym->RemoveReference();
}
}
void MeshSprLoader::LoadBin(const simp::NodeMeshSpr* node)
{
if (!m_spr) {
return;
}
s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(node->base_id);
m_spr->SetBaseSym(base_sym);
base_sym->RemoveReference();
assert(m_spr->GetSymbol()->Type() == s2::SYM_MESH);
s2::MeshSymbol* mesh_sym = VI_DOWNCASTING<s2::MeshSymbol*>(m_spr->GetSymbol());
s2::Mesh* mesh = mesh_sym->GetMesh();
if (!mesh) {
return;
}
s2::MeshTransform2& trans = m_spr->GetMeshTrans();
trans.Clear();
const std::vector<s2::MeshTriangle*>& tris = mesh->GetTriangles();
std::multimap<sm::vec2, int, sm::Vector2Cmp> map2idx;
int idx = 0;
for (int i = 0, n = tris.size(); i < n; ++i) {
s2::MeshTriangle* tri = tris[i];
for (int j = 0; j < 3; ++j) {
map2idx.insert(std::make_pair(tri->nodes[j]->ori_xy, idx++));
}
}
idx = 0;
for (int i = 0, n = node->n / 2; i < n; ++i)
{
sm::vec2 f, t;
f.x = simp::int2float(int16_t(node->vertices[idx++]), 16);
f.y = simp::int2float(int16_t(node->vertices[idx++]), 16);
t.x = simp::int2float(int16_t(node->vertices[idx++]), 16);
t.y = simp::int2float(int16_t(node->vertices[idx++]), 16);
sm::vec2 pos = f - t;
std::multimap<sm::vec2, int, sm::Vector2Cmp>::const_iterator
itr_begin = map2idx.lower_bound(f),
itr_end = map2idx.upper_bound(f);
assert(itr_begin != map2idx.end());
std::multimap<sm::vec2, int, sm::Vector2Cmp>::const_iterator itr = itr_begin;
for ( ; itr != itr_end; ++itr) {
trans.Add(itr->second, pos);
break; // todo
}
}
trans.StoreToMesh(mesh);
}
}<|endoftext|> |
<commit_before>#include <iostream>
#ifndef ELEMENTS_HYDROGEN_TO_OXYGEN_H
#define ELEMENTS_TO_HYDROHEN_TO_OXYGEN_H
/**denotes elements hrgrogen to argon starting with hydrogen=1
/*takes enum and string file to do if and else work about number of bonds*/
enum elements_hydrogen_to_argon t //element assignments std=c++11
{
HYDROGEN = 1,
HELIUM,
LITHIUM,
BERRLYIUM,
BORON,
CARBON,
NITROGEN,
OXYGEN,
FLUORINE,
NEON,
SODIUM,
MAGNESIUM,
ALUMINUM,
SILICON,
PHOSPHOROUS,
SULFUR,
CHLORINE,
ARGON
};
string elements_to_string (elements_hydrogen_to_argon d) //numbers to element assignments
{
if (element == Hydrogen ) return "Hydrogen";
if (element == Helium ) return "Helium";
if (element == Lithium ) return "Lithium";
if (element == Berrylium ) return "Berrylium";
if (element == Boron ) return "Boron";
if (element == Carbon ) return "Carbon";
if (element == Nitrogen ) return "Nitrogen";
if (element == Oxygen ) return "Oxygen";
if (element == Fluorine ) return "Fluorine";
if (element == Neon ) return "Neon";
if (element == Sodium ) return "Sodium";
if (element == Magenesium ) return "Magnesium";
if (element == Aluminum ) return "Aluminum";
if (element == Silicon ) return "Silicon";
if (element == Phosphourous) return "Phosphorous";
if (element == Sulfur ) return "Sulfur";
if (element == Chlorine ) return "Chlorine";
if (element == Argon ) return "Argon"
}
<commit_msg>Delete number_bonds.cpp<commit_after><|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief application simple user and session management feature
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "ApplicationAdminServer.h"
#include "build.h"
#include "Admin/RestAdminFeConfigurationHandler.h"
#include "Admin/RestAdminLogHandler.h"
#include "Admin/RestHandlerCreator.h"
#include "Basics/ProgramOptionsDescription.h"
#include "HttpServer/HttpHandlerFactory.h"
#include "HttpServer/PathHandler.h"
#include "Logger/Logger.h"
#include "Rest/HttpResponse.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::rest;
using namespace triagens::admin;
// -----------------------------------------------------------------------------
// --SECTION-- static public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief creates a new feature
////////////////////////////////////////////////////////////////////////////////
ApplicationAdminServer* ApplicationAdminServer::create (ApplicationServer*) {
return new ApplicationAdminServer();
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////
ApplicationAdminServer::ApplicationAdminServer ()
: _allowLogViewer(false),
_allowAdminDirectory(false),
_allowFeConfiguration(false),
_allowVersion(false),
_adminDirectory(),
_pathOptions(0),
_feConfiguration(),
_name(),
_version(),
_versionDataDirect(0),
_versionDataQueued(0) {
_pathOptions = new PathHandler::Options();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////
ApplicationAdminServer::~ApplicationAdminServer () {
delete reinterpret_cast<PathHandler::Options*>(_pathOptions);
if (_versionDataDirect != 0) {
delete _versionDataDirect;
}
if (_versionDataQueued != 0) {
delete _versionDataQueued;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief add a log viewer
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowLogViewer () {
_allowLogViewer = true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a webadmin directory
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowAdminDirectory () {
_allowAdminDirectory = true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a webadmin directory
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowAdminDirectory (string const& adminDirectory) {
_allowAdminDirectory = true;
_adminDirectory = adminDirectory;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a front-end configuration
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowFeConfiguration () {
_allowFeConfiguration = true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a version handler using the default version
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowVersion () {
_allowVersion = true;
_version = TRIAGENS_VERSION;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a version handler
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowVersion (string name, string version) {
_allowVersion = true;
_name = name;
_version = version;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief adds the http handlers
///
/// Note that the server does not claim ownership of the factory.
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::addBasicHandlers (HttpHandlerFactory* factory, string const& prefix) {
if (_allowVersion) {
if (!_versionDataDirect) {
_versionDataDirect = new RestVersionHandler::version_options_t;
_versionDataDirect->_name = _name;
_versionDataDirect->_version = _version;
_versionDataDirect->_isDirect = true;
}
factory->addHandler(prefix + "/version",
RestHandlerCreator<RestVersionHandler>::createData<RestVersionHandler::version_options_t const*>,
(void*) _versionDataDirect);
if (!_versionDataQueued) {
_versionDataQueued = new RestVersionHandler::version_options_t;
_versionDataQueued->_name = _name;
_versionDataQueued->_version = _version;
_versionDataQueued->_isDirect = false;
_versionDataQueued->_queue = "STANDARD";
}
factory->addHandler(prefix + "/queued/version",
RestHandlerCreator<RestVersionHandler>::createData<RestVersionHandler::version_options_t const*>,
(void*) _versionDataQueued);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief adds the http handlers for administration
///
/// Note that the server does not claim ownership of the factory.
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::addHandlers (HttpHandlerFactory* factory, string const& prefix) {
// .............................................................................
// add log viewer
// .............................................................................
if (_allowLogViewer) {
factory->addHandler(prefix + "/log", RestHandlerCreator<RestAdminLogHandler>::createNoData, 0);
}
// .............................................................................
// add a web-admin directory
// .............................................................................
if (_allowAdminDirectory) {
if (! _adminDirectory.empty()) {
LOGGER_INFO << "using JavaScript front-end files stored at '" << _adminDirectory << "'";
reinterpret_cast<PathHandler::Options*>(_pathOptions)->path = _adminDirectory;
reinterpret_cast<PathHandler::Options*>(_pathOptions)->contentType = "text/plain";
reinterpret_cast<PathHandler::Options*>(_pathOptions)->allowSymbolicLink = false;
reinterpret_cast<PathHandler::Options*>(_pathOptions)->defaultFile = "index.html";
factory->addPrefixHandler(prefix + "/html", RestHandlerCreator<PathHandler>::createData<PathHandler::Options*>, _pathOptions);
}
}
// .............................................................................
// add a front-end configuration
// .............................................................................
if (_allowFeConfiguration) {
factory->addHandler(prefix + "/fe-configuration",
RestHandlerCreator<RestAdminFeConfigurationHandler>::createData<char const*>,
(void*) _feConfiguration.c_str());
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- ApplicationFeature methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::setupOptions (map<string, basics::ProgramOptionsDescription>& options) {
if (_allowAdminDirectory) {
options[ApplicationServer::OPTIONS_SERVER + ":help-admin"]
("server.admin-directory", &_adminDirectory, "directory containing the ADMIN front-end")
;
}
if (_allowFeConfiguration) {
options[ApplicationServer::OPTIONS_SERVER + ":help-admin"]
("server.fe-configuration", &_feConfiguration, "file to store the front-end preferences")
;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<commit_msg>added /queued-version<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief application simple user and session management feature
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "ApplicationAdminServer.h"
#include "build.h"
#include "Admin/RestAdminFeConfigurationHandler.h"
#include "Admin/RestAdminLogHandler.h"
#include "Admin/RestHandlerCreator.h"
#include "Basics/ProgramOptionsDescription.h"
#include "HttpServer/HttpHandlerFactory.h"
#include "HttpServer/PathHandler.h"
#include "Logger/Logger.h"
#include "Rest/HttpResponse.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::rest;
using namespace triagens::admin;
// -----------------------------------------------------------------------------
// --SECTION-- static public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief creates a new feature
////////////////////////////////////////////////////////////////////////////////
ApplicationAdminServer* ApplicationAdminServer::create (ApplicationServer*) {
return new ApplicationAdminServer();
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////
ApplicationAdminServer::ApplicationAdminServer ()
: _allowLogViewer(false),
_allowAdminDirectory(false),
_allowFeConfiguration(false),
_allowVersion(false),
_adminDirectory(),
_pathOptions(0),
_feConfiguration(),
_name(),
_version(),
_versionDataDirect(0),
_versionDataQueued(0) {
_pathOptions = new PathHandler::Options();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////
ApplicationAdminServer::~ApplicationAdminServer () {
delete reinterpret_cast<PathHandler::Options*>(_pathOptions);
if (_versionDataDirect != 0) {
delete _versionDataDirect;
}
if (_versionDataQueued != 0) {
delete _versionDataQueued;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief add a log viewer
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowLogViewer () {
_allowLogViewer = true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a webadmin directory
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowAdminDirectory () {
_allowAdminDirectory = true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a webadmin directory
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowAdminDirectory (string const& adminDirectory) {
_allowAdminDirectory = true;
_adminDirectory = adminDirectory;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a front-end configuration
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowFeConfiguration () {
_allowFeConfiguration = true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a version handler using the default version
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowVersion () {
_allowVersion = true;
_version = TRIAGENS_VERSION;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a version handler
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::allowVersion (string name, string version) {
_allowVersion = true;
_name = name;
_version = version;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief adds the http handlers
///
/// Note that the server does not claim ownership of the factory.
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::addBasicHandlers (HttpHandlerFactory* factory, string const& prefix) {
if (_allowVersion) {
if (!_versionDataDirect) {
_versionDataDirect = new RestVersionHandler::version_options_t;
_versionDataDirect->_name = _name;
_versionDataDirect->_version = _version;
_versionDataDirect->_isDirect = true;
}
factory->addHandler(prefix + "/version",
RestHandlerCreator<RestVersionHandler>::createData<RestVersionHandler::version_options_t const*>,
(void*) _versionDataDirect);
if (!_versionDataQueued) {
_versionDataQueued = new RestVersionHandler::version_options_t;
_versionDataQueued->_name = _name;
_versionDataQueued->_version = _version;
_versionDataQueued->_isDirect = false;
_versionDataQueued->_queue = "STANDARD";
}
factory->addHandler(prefix + "/queued-version",
RestHandlerCreator<RestVersionHandler>::createData<RestVersionHandler::version_options_t const*>,
(void*) _versionDataQueued);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief adds the http handlers for administration
///
/// Note that the server does not claim ownership of the factory.
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::addHandlers (HttpHandlerFactory* factory, string const& prefix) {
// .............................................................................
// add log viewer
// .............................................................................
if (_allowLogViewer) {
factory->addHandler(prefix + "/log", RestHandlerCreator<RestAdminLogHandler>::createNoData, 0);
}
// .............................................................................
// add a web-admin directory
// .............................................................................
if (_allowAdminDirectory) {
if (! _adminDirectory.empty()) {
LOGGER_INFO << "using JavaScript front-end files stored at '" << _adminDirectory << "'";
reinterpret_cast<PathHandler::Options*>(_pathOptions)->path = _adminDirectory;
reinterpret_cast<PathHandler::Options*>(_pathOptions)->contentType = "text/plain";
reinterpret_cast<PathHandler::Options*>(_pathOptions)->allowSymbolicLink = false;
reinterpret_cast<PathHandler::Options*>(_pathOptions)->defaultFile = "index.html";
factory->addPrefixHandler(prefix + "/html", RestHandlerCreator<PathHandler>::createData<PathHandler::Options*>, _pathOptions);
}
}
// .............................................................................
// add a front-end configuration
// .............................................................................
if (_allowFeConfiguration) {
factory->addHandler(prefix + "/fe-configuration",
RestHandlerCreator<RestAdminFeConfigurationHandler>::createData<char const*>,
(void*) _feConfiguration.c_str());
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- ApplicationFeature methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////
void ApplicationAdminServer::setupOptions (map<string, basics::ProgramOptionsDescription>& options) {
if (_allowAdminDirectory) {
options[ApplicationServer::OPTIONS_SERVER + ":help-admin"]
("server.admin-directory", &_adminDirectory, "directory containing the ADMIN front-end")
;
}
if (_allowFeConfiguration) {
options[ApplicationServer::OPTIONS_SERVER + ":help-admin"]
("server.fe-configuration", &_feConfiguration, "file to store the front-end preferences")
;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<|endoftext|> |
<commit_before>//===-- AlphaAsmPrinter.cpp - Alpha LLVM assembly writer ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to GAS-format Alpha assembly language.
//
//===----------------------------------------------------------------------===//
#include "Alpha.h"
#include "AlphaInstrInfo.h"
#include "AlphaTargetMachine.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Mangler.h"
#include "llvm/ADT/Statistic.h"
#include <iostream>
using namespace llvm;
namespace {
Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
struct VISIBILITY_HIDDEN AlphaAsmPrinter : public AsmPrinter {
/// Unique incrementer for label values for referencing Global values.
///
unsigned LabelNumber;
AlphaAsmPrinter(std::ostream &o, TargetMachine &tm, const TargetAsmInfo *T)
: AsmPrinter(o, tm, T), LabelNumber(0) {
}
/// We name each basic block in a Function with a unique number, so
/// that we can consistently refer to them later. This is cleared
/// at the beginning of each call to runOnMachineFunction().
///
typedef std::map<const Value *, unsigned> ValueMapTy;
ValueMapTy NumberForBB;
std::string CurSection;
virtual const char *getPassName() const {
return "Alpha Assembly Printer";
}
bool printInstruction(const MachineInstr *MI);
void printOp(const MachineOperand &MO, bool IsCallOp = false);
void printOperand(const MachineInstr *MI, int opNum);
void printBaseOffsetPair (const MachineInstr *MI, int i, bool brackets=true);
void printMachineInstruction(const MachineInstr *MI);
bool runOnMachineFunction(MachineFunction &F);
bool doInitialization(Module &M);
bool doFinalization(Module &M);
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
unsigned AsmVariant, const char *ExtraCode);
bool PrintAsmMemoryOperand(const MachineInstr *MI,
unsigned OpNo,
unsigned AsmVariant,
const char *ExtraCode);
};
} // end of anonymous namespace
/// createAlphaCodePrinterPass - Returns a pass that prints the Alpha
/// assembly code for a MachineFunction to the given output stream,
/// using the given target machine description. This should work
/// regardless of whether the function is in SSA form.
///
FunctionPass *llvm::createAlphaCodePrinterPass (std::ostream &o,
TargetMachine &tm) {
return new AlphaAsmPrinter(o, tm, tm.getTargetAsmInfo());
}
#include "AlphaGenAsmWriter.inc"
void AlphaAsmPrinter::printOperand(const MachineInstr *MI, int opNum)
{
const MachineOperand &MO = MI->getOperand(opNum);
if (MO.getType() == MachineOperand::MO_Register) {
assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
O << TM.getRegisterInfo()->get(MO.getReg()).Name;
} else if (MO.isImmediate()) {
O << MO.getImmedValue();
assert(MO.getImmedValue() < (1 << 30));
} else {
printOp(MO);
}
}
void AlphaAsmPrinter::printOp(const MachineOperand &MO, bool IsCallOp) {
const MRegisterInfo &RI = *TM.getRegisterInfo();
int new_symbol;
switch (MO.getType()) {
case MachineOperand::MO_Register:
O << RI.get(MO.getReg()).Name;
return;
case MachineOperand::MO_Immediate:
std::cerr << "printOp() does not handle immediate values\n";
abort();
return;
case MachineOperand::MO_MachineBasicBlock:
printBasicBlockLabel(MO.getMachineBasicBlock());
return;
case MachineOperand::MO_ConstantPoolIndex:
O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
<< MO.getConstantPoolIndex();
return;
case MachineOperand::MO_ExternalSymbol:
O << MO.getSymbolName();
return;
case MachineOperand::MO_GlobalAddress:
O << Mang->getValueName(MO.getGlobal());
return;
case MachineOperand::MO_JumpTableIndex:
O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
<< '_' << MO.getJumpTableIndex();
return;
default:
O << "<unknown operand type: " << MO.getType() << ">";
return;
}
}
/// printMachineInstruction -- Print out a single Alpha MI to
/// the current output stream.
///
void AlphaAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
++EmittedInsts;
if (printInstruction(MI))
return; // Printer was automatically generated
assert(0 && "Unhandled instruction in asm writer!");
abort();
return;
}
/// runOnMachineFunction - This uses the printMachineInstruction()
/// method to print assembly for each instruction.
///
bool AlphaAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
SetupMachineFunction(MF);
O << "\n\n";
// Print out constants referenced by the function
EmitConstantPool(MF.getConstantPool());
// Print out jump tables referenced by the function
EmitJumpTableInfo(MF.getJumpTableInfo());
// Print out labels for the function.
const Function *F = MF.getFunction();
SwitchToTextSection(".text", F);
EmitAlignment(4, F);
switch (F->getLinkage()) {
default: assert(0 && "Unknown linkage type!");
case Function::InternalLinkage: // Symbols default to internal.
break;
case Function::ExternalLinkage:
O << "\t.globl " << CurrentFnName << "\n";
break;
case Function::WeakLinkage:
case Function::LinkOnceLinkage:
O << "\t.weak " << CurrentFnName << "\n";
break;
}
O << "\t.ent " << CurrentFnName << "\n";
O << CurrentFnName << ":\n";
// Print out code for the function.
for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
I != E; ++I) {
printBasicBlockLabel(I, true);
O << '\n';
for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
II != E; ++II) {
// Print the assembly for the instruction.
O << "\t";
printMachineInstruction(II);
}
}
++LabelNumber;
O << "\t.end " << CurrentFnName << "\n";
// We didn't modify anything.
return false;
}
bool AlphaAsmPrinter::doInitialization(Module &M)
{
AsmPrinter::doInitialization(M);
if(TM.getSubtarget<AlphaSubtarget>().hasF2I()
|| TM.getSubtarget<AlphaSubtarget>().hasCT())
O << "\t.arch ev6\n";
else
O << "\t.arch ev56\n";
O << "\t.set noat\n";
return false;
}
bool AlphaAsmPrinter::doFinalization(Module &M) {
const TargetData *TD = TM.getTargetData();
for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
if (I->hasInitializer()) { // External global require no code
// Check to see if this is a special global used by LLVM, if so, emit it.
if (EmitSpecialLLVMGlobal(I))
continue;
O << "\n\n";
std::string name = Mang->getValueName(I);
Constant *C = I->getInitializer();
unsigned Size = TD->getTypeSize(C->getType());
// unsigned Align = TD->getTypeAlignmentShift(C->getType());
unsigned Align = getPreferredAlignmentLog(I);
if (C->isNullValue() &&
(I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
I->hasWeakLinkage() /* FIXME: Verify correct */)) {
SwitchToDataSection("\t.section .data", I);
if (I->hasInternalLinkage())
O << "\t.local " << name << "\n";
O << "\t.comm " << name << "," << TD->getTypeSize(C->getType())
<< "," << (1 << Align)
<< "\n";
} else {
switch (I->getLinkage()) {
case GlobalValue::LinkOnceLinkage:
case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
// Nonnull linkonce -> weak
O << "\t.weak " << name << "\n";
O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
SwitchToDataSection("", I);
break;
case GlobalValue::AppendingLinkage:
// FIXME: appending linkage variables should go into a section of
// their name or something. For now, just emit them as external.
case GlobalValue::ExternalLinkage:
// If external or appending, declare as a global symbol
O << "\t.globl " << name << "\n";
// FALL THROUGH
case GlobalValue::InternalLinkage:
SwitchToDataSection(C->isNullValue() ? "\t.section .bss" :
"\t.section .data", I);
break;
case GlobalValue::GhostLinkage:
std::cerr << "GhostLinkage cannot appear in AlphaAsmPrinter!\n";
abort();
case GlobalValue::DLLImportLinkage:
std::cerr << "DLLImport linkage is not supported by this target!\n";
abort();
case GlobalValue::DLLExportLinkage:
std::cerr << "DLLExport linkage is not supported by this target!\n";
abort();
default:
assert(0 && "Unknown linkage type!");
}
EmitAlignment(Align);
O << "\t.type " << name << ",@object\n";
O << "\t.size " << name << "," << Size << "\n";
O << name << ":\n";
EmitGlobalConstant(C);
}
}
AsmPrinter::doFinalization(M);
return false;
}
/// PrintAsmOperand - Print out an operand for an inline asm expression.
///
bool AlphaAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
unsigned AsmVariant,
const char *ExtraCode) {
printOperand(MI, OpNo);
return false;
}
bool AlphaAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
unsigned OpNo,
unsigned AsmVariant,
const char *ExtraCode) {
if (ExtraCode && ExtraCode[0])
return true; // Unknown modifier.
O << "0(";
printOperand(MI, OpNo);
O << ")";
return false;
}
<commit_msg>use getSectionForFunction to decide which section to emit code into<commit_after>//===-- AlphaAsmPrinter.cpp - Alpha LLVM assembly writer ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to GAS-format Alpha assembly language.
//
//===----------------------------------------------------------------------===//
#include "Alpha.h"
#include "AlphaInstrInfo.h"
#include "AlphaTargetMachine.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Mangler.h"
#include "llvm/ADT/Statistic.h"
#include <iostream>
using namespace llvm;
namespace {
Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
struct VISIBILITY_HIDDEN AlphaAsmPrinter : public AsmPrinter {
/// Unique incrementer for label values for referencing Global values.
///
unsigned LabelNumber;
AlphaAsmPrinter(std::ostream &o, TargetMachine &tm, const TargetAsmInfo *T)
: AsmPrinter(o, tm, T), LabelNumber(0) {
}
/// We name each basic block in a Function with a unique number, so
/// that we can consistently refer to them later. This is cleared
/// at the beginning of each call to runOnMachineFunction().
///
typedef std::map<const Value *, unsigned> ValueMapTy;
ValueMapTy NumberForBB;
std::string CurSection;
virtual const char *getPassName() const {
return "Alpha Assembly Printer";
}
bool printInstruction(const MachineInstr *MI);
void printOp(const MachineOperand &MO, bool IsCallOp = false);
void printOperand(const MachineInstr *MI, int opNum);
void printBaseOffsetPair (const MachineInstr *MI, int i, bool brackets=true);
void printMachineInstruction(const MachineInstr *MI);
bool runOnMachineFunction(MachineFunction &F);
bool doInitialization(Module &M);
bool doFinalization(Module &M);
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
unsigned AsmVariant, const char *ExtraCode);
bool PrintAsmMemoryOperand(const MachineInstr *MI,
unsigned OpNo,
unsigned AsmVariant,
const char *ExtraCode);
};
} // end of anonymous namespace
/// createAlphaCodePrinterPass - Returns a pass that prints the Alpha
/// assembly code for a MachineFunction to the given output stream,
/// using the given target machine description. This should work
/// regardless of whether the function is in SSA form.
///
FunctionPass *llvm::createAlphaCodePrinterPass(std::ostream &o,
TargetMachine &tm) {
return new AlphaAsmPrinter(o, tm, tm.getTargetAsmInfo());
}
#include "AlphaGenAsmWriter.inc"
void AlphaAsmPrinter::printOperand(const MachineInstr *MI, int opNum)
{
const MachineOperand &MO = MI->getOperand(opNum);
if (MO.getType() == MachineOperand::MO_Register) {
assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
O << TM.getRegisterInfo()->get(MO.getReg()).Name;
} else if (MO.isImmediate()) {
O << MO.getImmedValue();
assert(MO.getImmedValue() < (1 << 30));
} else {
printOp(MO);
}
}
void AlphaAsmPrinter::printOp(const MachineOperand &MO, bool IsCallOp) {
const MRegisterInfo &RI = *TM.getRegisterInfo();
int new_symbol;
switch (MO.getType()) {
case MachineOperand::MO_Register:
O << RI.get(MO.getReg()).Name;
return;
case MachineOperand::MO_Immediate:
std::cerr << "printOp() does not handle immediate values\n";
abort();
return;
case MachineOperand::MO_MachineBasicBlock:
printBasicBlockLabel(MO.getMachineBasicBlock());
return;
case MachineOperand::MO_ConstantPoolIndex:
O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
<< MO.getConstantPoolIndex();
return;
case MachineOperand::MO_ExternalSymbol:
O << MO.getSymbolName();
return;
case MachineOperand::MO_GlobalAddress:
O << Mang->getValueName(MO.getGlobal());
return;
case MachineOperand::MO_JumpTableIndex:
O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
<< '_' << MO.getJumpTableIndex();
return;
default:
O << "<unknown operand type: " << MO.getType() << ">";
return;
}
}
/// printMachineInstruction -- Print out a single Alpha MI to
/// the current output stream.
///
void AlphaAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
++EmittedInsts;
if (printInstruction(MI))
return; // Printer was automatically generated
assert(0 && "Unhandled instruction in asm writer!");
abort();
return;
}
/// runOnMachineFunction - This uses the printMachineInstruction()
/// method to print assembly for each instruction.
///
bool AlphaAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
SetupMachineFunction(MF);
O << "\n\n";
// Print out constants referenced by the function
EmitConstantPool(MF.getConstantPool());
// Print out jump tables referenced by the function
EmitJumpTableInfo(MF.getJumpTableInfo());
// Print out labels for the function.
const Function *F = MF.getFunction();
SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
EmitAlignment(4, F);
switch (F->getLinkage()) {
default: assert(0 && "Unknown linkage type!");
case Function::InternalLinkage: // Symbols default to internal.
break;
case Function::ExternalLinkage:
O << "\t.globl " << CurrentFnName << "\n";
break;
case Function::WeakLinkage:
case Function::LinkOnceLinkage:
O << "\t.weak " << CurrentFnName << "\n";
break;
}
O << "\t.ent " << CurrentFnName << "\n";
O << CurrentFnName << ":\n";
// Print out code for the function.
for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
I != E; ++I) {
printBasicBlockLabel(I, true);
O << '\n';
for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
II != E; ++II) {
// Print the assembly for the instruction.
O << "\t";
printMachineInstruction(II);
}
}
++LabelNumber;
O << "\t.end " << CurrentFnName << "\n";
// We didn't modify anything.
return false;
}
bool AlphaAsmPrinter::doInitialization(Module &M)
{
AsmPrinter::doInitialization(M);
if(TM.getSubtarget<AlphaSubtarget>().hasF2I()
|| TM.getSubtarget<AlphaSubtarget>().hasCT())
O << "\t.arch ev6\n";
else
O << "\t.arch ev56\n";
O << "\t.set noat\n";
return false;
}
bool AlphaAsmPrinter::doFinalization(Module &M) {
const TargetData *TD = TM.getTargetData();
for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
if (I->hasInitializer()) { // External global require no code
// Check to see if this is a special global used by LLVM, if so, emit it.
if (EmitSpecialLLVMGlobal(I))
continue;
O << "\n\n";
std::string name = Mang->getValueName(I);
Constant *C = I->getInitializer();
unsigned Size = TD->getTypeSize(C->getType());
// unsigned Align = TD->getTypeAlignmentShift(C->getType());
unsigned Align = getPreferredAlignmentLog(I);
if (C->isNullValue() &&
(I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
I->hasWeakLinkage() /* FIXME: Verify correct */)) {
SwitchToDataSection("\t.section .data", I);
if (I->hasInternalLinkage())
O << "\t.local " << name << "\n";
O << "\t.comm " << name << "," << TD->getTypeSize(C->getType())
<< "," << (1 << Align)
<< "\n";
} else {
switch (I->getLinkage()) {
case GlobalValue::LinkOnceLinkage:
case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
// Nonnull linkonce -> weak
O << "\t.weak " << name << "\n";
O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
SwitchToDataSection("", I);
break;
case GlobalValue::AppendingLinkage:
// FIXME: appending linkage variables should go into a section of
// their name or something. For now, just emit them as external.
case GlobalValue::ExternalLinkage:
// If external or appending, declare as a global symbol
O << "\t.globl " << name << "\n";
// FALL THROUGH
case GlobalValue::InternalLinkage:
SwitchToDataSection(C->isNullValue() ? "\t.section .bss" :
"\t.section .data", I);
break;
case GlobalValue::GhostLinkage:
std::cerr << "GhostLinkage cannot appear in AlphaAsmPrinter!\n";
abort();
case GlobalValue::DLLImportLinkage:
std::cerr << "DLLImport linkage is not supported by this target!\n";
abort();
case GlobalValue::DLLExportLinkage:
std::cerr << "DLLExport linkage is not supported by this target!\n";
abort();
default:
assert(0 && "Unknown linkage type!");
}
EmitAlignment(Align);
O << "\t.type " << name << ",@object\n";
O << "\t.size " << name << "," << Size << "\n";
O << name << ":\n";
EmitGlobalConstant(C);
}
}
AsmPrinter::doFinalization(M);
return false;
}
/// PrintAsmOperand - Print out an operand for an inline asm expression.
///
bool AlphaAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
unsigned AsmVariant,
const char *ExtraCode) {
printOperand(MI, OpNo);
return false;
}
bool AlphaAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
unsigned OpNo,
unsigned AsmVariant,
const char *ExtraCode) {
if (ExtraCode && ExtraCode[0])
return true; // Unknown modifier.
O << "0(";
printOperand(MI, OpNo);
O << ")";
return false;
}
<|endoftext|> |
<commit_before>//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass implements a simple loop unroller. It works best when loops have
// been canonicalized by the -indvars pass, allowing it to determine the trip
// counts of loops easily.
//
// This pass is currently extremely limited. It only currently only unrolls
// single basic block loops that execute a constant number of times.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "loop-unroll"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Local.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/Statistic.h"
#include "Support/STLExtras.h"
#include <cstdio>
#include <set>
using namespace llvm;
namespace {
Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
cl::opt<unsigned>
UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
cl::desc("The cut-off point for loop unrolling"));
class LoopUnroll : public FunctionPass {
LoopInfo *LI; // The current loop information
public:
virtual bool runOnFunction(Function &F);
bool visitLoop(Loop *L);
/// This transformation requires natural loop information & requires that
/// loop preheaders be inserted into the CFG...
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredID(LoopSimplifyID);
AU.addRequired<LoopInfo>();
AU.addPreserved<LoopInfo>();
}
};
RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
}
FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
bool LoopUnroll::runOnFunction(Function &F) {
bool Changed = false;
LI = &getAnalysis<LoopInfo>();
// Transform all the top-level loops. Copy the loop list so that the child
// can update the loop tree if it needs to delete the loop.
std::vector<Loop*> SubLoops(LI->begin(), LI->end());
for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
Changed |= visitLoop(SubLoops[i]);
return Changed;
}
/// ApproximateLoopSize - Approximate the size of the loop after it has been
/// unrolled.
static unsigned ApproximateLoopSize(const Loop *L) {
unsigned Size = 0;
for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
BasicBlock *BB = L->getBlocks()[i];
Instruction *Term = BB->getTerminator();
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
if (isa<PHINode>(I) && BB == L->getHeader()) {
// Ignore PHI nodes in the header.
} else if (I->hasOneUse() && I->use_back() == Term) {
// Ignore instructions only used by the loop terminator.
} else {
++Size;
}
// TODO: Ignore expressions derived from PHI and constants if inval of phi
// is a constant, or if operation is associative. This will get induction
// variables.
}
}
return Size;
}
// RemapInstruction - Convert the instruction operands from referencing the
// current values into those specified by ValueMap.
//
static inline void RemapInstruction(Instruction *I,
std::map<const Value *, Value*> &ValueMap) {
for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
Value *Op = I->getOperand(op);
std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
if (It != ValueMap.end()) Op = It->second;
I->setOperand(op, Op);
}
}
bool LoopUnroll::visitLoop(Loop *L) {
bool Changed = false;
// Recurse through all subloops before we process this loop. Copy the loop
// list so that the child can update the loop tree if it needs to delete the
// loop.
std::vector<Loop*> SubLoops(L->begin(), L->end());
for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
Changed |= visitLoop(SubLoops[i]);
// We only handle single basic block loops right now.
if (L->getBlocks().size() != 1)
return Changed;
BasicBlock *BB = L->getHeader();
BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
if (BI == 0) return Changed; // Must end in a conditional branch
ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
if (!TripCountC) return Changed; // Must have constant trip count!
unsigned TripCount = TripCountC->getRawValue();
if (TripCount != TripCountC->getRawValue())
return Changed; // More than 2^32 iterations???
unsigned LoopSize = ApproximateLoopSize(L);
DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
<< "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
<< " Trip Count = " << TripCount << " - ");
if (LoopSize*TripCount > UnrollThreshold) {
DEBUG(std::cerr << "TOO LARGE: " << LoopSize*TripCount << ">"
<< UnrollThreshold << "\n");
return Changed;
}
DEBUG(std::cerr << "UNROLLING!\n");
BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
// Create a new basic block to temporarily hold all of the cloned code.
BasicBlock *NewBlock = new BasicBlock();
// For the first iteration of the loop, we should use the precloned values for
// PHI nodes. Insert associations now.
std::map<const Value*, Value*> LastValueMap;
std::vector<PHINode*> OrigPHINode;
for (BasicBlock::iterator I = BB->begin();
PHINode *PN = dyn_cast<PHINode>(I); ++I) {
OrigPHINode.push_back(PN);
if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
if (I->getParent() == BB)
LastValueMap[I] = I;
}
// Remove the exit branch from the loop
BB->getInstList().erase(BI);
assert(TripCount != 0 && "Trip count of 0 is impossible!");
for (unsigned It = 1; It != TripCount; ++It) {
char SuffixBuffer[100];
sprintf(SuffixBuffer, ".%d", It);
std::map<const Value*, Value*> ValueMap;
BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);
// Loop over all of the PHI nodes in the block, changing them to use the
// incoming values from the previous block.
for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
Value *InVal = NewPHI->getIncomingValueForBlock(BB);
if (Instruction *InValI = dyn_cast<Instruction>(InVal))
if (InValI->getParent() == BB)
InVal = LastValueMap[InValI];
ValueMap[OrigPHINode[i]] = InVal;
New->getInstList().erase(NewPHI);
}
for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
RemapInstruction(I, ValueMap);
// Now that all of the instructions are remapped, splice them into the end
// of the NewBlock.
NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
delete New;
// LastValue map now contains values from this iteration.
std::swap(LastValueMap, ValueMap);
}
// If there was more than one iteration, replace any uses of values computed
// in the loop with values computed during the last iteration of the loop.
if (TripCount != 1) {
std::set<User*> Users;
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Users.insert(I->use_begin(), I->use_end());
// We don't want to reprocess entries with PHI nodes in them. For this
// reason, we look at each operand of each user exactly once, performing the
// stubstitution exactly once.
for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E;
++UI) {
Instruction *I = cast<Instruction>(*UI);
if (I->getParent() != BB && I->getParent() != NewBlock)
RemapInstruction(I, LastValueMap);
}
}
// Now that we cloned the block as many times as we needed, stitch the new
// code into the original block and delete the temporary block.
BB->getInstList().splice(BB->end(), NewBlock->getInstList());
delete NewBlock;
// Now loop over the PHI nodes in the original block, setting them to their
// incoming values.
BasicBlock *Preheader = L->getLoopPreheader();
for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
PHINode *PN = OrigPHINode[i];
PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
BB->getInstList().erase(PN);
}
// Finally, add an unconditional branch to the block to continue into the exit
// block.
new BranchInst(LoopExit, BB);
// At this point, the code is well formed. We now do a quick sweep over the
// inserted code, doing constant propagation and dead code elimination as we
// go.
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Instruction *Inst = I++;
if (isInstructionTriviallyDead(Inst))
BB->getInstList().erase(Inst);
else if (Constant *C = ConstantFoldInstruction(Inst)) {
Inst->replaceAllUsesWith(C);
BB->getInstList().erase(Inst);
}
}
// Update the loop information for this loop.
Loop *Parent = L->getParentLoop();
// Move all of the basic blocks in the loop into the parent loop.
LI->changeLoopFor(BB, Parent);
// Remove the loop from the parent.
if (Parent)
delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
else
delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
// FIXME: Should update dominator analyses
// Now that everything is up-to-date that will be, we fold the loop block into
// the preheader and exit block, updating our analyses as we go.
LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(),
BB->getInstList().begin(),
prior(BB->getInstList().end()));
LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(),
Preheader->getInstList().begin(),
prior(Preheader->getInstList().end()));
// Make all other blocks in the program branch to LoopExit now instead of
// Preheader.
Preheader->replaceAllUsesWith(LoopExit);
// Remove BB and LoopExit from our analyses.
LI->removeBlock(Preheader);
LI->removeBlock(BB);
// If the preheader was the entry block of this function, move the exit block
// to be the new entry of the loop.
Function *F = LoopExit->getParent();
if (Preheader == &F->front())
F->getBasicBlockList().splice(F->begin(), F->getBasicBlockList(), LoopExit);
// Actually delete the blocks now.
F->getBasicBlockList().erase(Preheader);
F->getBasicBlockList().erase(BB);
++NumUnrolled;
return true;
}
<commit_msg>Fix PR325<commit_after>//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass implements a simple loop unroller. It works best when loops have
// been canonicalized by the -indvars pass, allowing it to determine the trip
// counts of loops easily.
//
// This pass is currently extremely limited. It only currently only unrolls
// single basic block loops that execute a constant number of times.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "loop-unroll"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Local.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/Statistic.h"
#include "Support/STLExtras.h"
#include <cstdio>
#include <set>
using namespace llvm;
namespace {
Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
cl::opt<unsigned>
UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
cl::desc("The cut-off point for loop unrolling"));
class LoopUnroll : public FunctionPass {
LoopInfo *LI; // The current loop information
public:
virtual bool runOnFunction(Function &F);
bool visitLoop(Loop *L);
/// This transformation requires natural loop information & requires that
/// loop preheaders be inserted into the CFG...
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredID(LoopSimplifyID);
AU.addRequired<LoopInfo>();
AU.addPreserved<LoopInfo>();
}
};
RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
}
FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
bool LoopUnroll::runOnFunction(Function &F) {
bool Changed = false;
LI = &getAnalysis<LoopInfo>();
// Transform all the top-level loops. Copy the loop list so that the child
// can update the loop tree if it needs to delete the loop.
std::vector<Loop*> SubLoops(LI->begin(), LI->end());
for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
Changed |= visitLoop(SubLoops[i]);
return Changed;
}
/// ApproximateLoopSize - Approximate the size of the loop after it has been
/// unrolled.
static unsigned ApproximateLoopSize(const Loop *L) {
unsigned Size = 0;
for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
BasicBlock *BB = L->getBlocks()[i];
Instruction *Term = BB->getTerminator();
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
if (isa<PHINode>(I) && BB == L->getHeader()) {
// Ignore PHI nodes in the header.
} else if (I->hasOneUse() && I->use_back() == Term) {
// Ignore instructions only used by the loop terminator.
} else {
++Size;
}
// TODO: Ignore expressions derived from PHI and constants if inval of phi
// is a constant, or if operation is associative. This will get induction
// variables.
}
}
return Size;
}
// RemapInstruction - Convert the instruction operands from referencing the
// current values into those specified by ValueMap.
//
static inline void RemapInstruction(Instruction *I,
std::map<const Value *, Value*> &ValueMap) {
for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
Value *Op = I->getOperand(op);
std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
if (It != ValueMap.end()) Op = It->second;
I->setOperand(op, Op);
}
}
bool LoopUnroll::visitLoop(Loop *L) {
bool Changed = false;
// Recurse through all subloops before we process this loop. Copy the loop
// list so that the child can update the loop tree if it needs to delete the
// loop.
std::vector<Loop*> SubLoops(L->begin(), L->end());
for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
Changed |= visitLoop(SubLoops[i]);
// We only handle single basic block loops right now.
if (L->getBlocks().size() != 1)
return Changed;
BasicBlock *BB = L->getHeader();
BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
if (BI == 0) return Changed; // Must end in a conditional branch
ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
if (!TripCountC) return Changed; // Must have constant trip count!
unsigned TripCount = TripCountC->getRawValue();
if (TripCount != TripCountC->getRawValue() || TripCount == 0)
return Changed; // More than 2^32 iterations???
unsigned LoopSize = ApproximateLoopSize(L);
DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
<< "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
<< " Trip Count = " << TripCount << " - ");
if (LoopSize*TripCount > UnrollThreshold) {
DEBUG(std::cerr << "TOO LARGE: " << LoopSize*TripCount << ">"
<< UnrollThreshold << "\n");
return Changed;
}
DEBUG(std::cerr << "UNROLLING!\n");
BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
// Create a new basic block to temporarily hold all of the cloned code.
BasicBlock *NewBlock = new BasicBlock();
// For the first iteration of the loop, we should use the precloned values for
// PHI nodes. Insert associations now.
std::map<const Value*, Value*> LastValueMap;
std::vector<PHINode*> OrigPHINode;
for (BasicBlock::iterator I = BB->begin();
PHINode *PN = dyn_cast<PHINode>(I); ++I) {
OrigPHINode.push_back(PN);
if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
if (I->getParent() == BB)
LastValueMap[I] = I;
}
// Remove the exit branch from the loop
BB->getInstList().erase(BI);
assert(TripCount != 0 && "Trip count of 0 is impossible!");
for (unsigned It = 1; It != TripCount; ++It) {
char SuffixBuffer[100];
sprintf(SuffixBuffer, ".%d", It);
std::map<const Value*, Value*> ValueMap;
BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);
// Loop over all of the PHI nodes in the block, changing them to use the
// incoming values from the previous block.
for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
Value *InVal = NewPHI->getIncomingValueForBlock(BB);
if (Instruction *InValI = dyn_cast<Instruction>(InVal))
if (InValI->getParent() == BB)
InVal = LastValueMap[InValI];
ValueMap[OrigPHINode[i]] = InVal;
New->getInstList().erase(NewPHI);
}
for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
RemapInstruction(I, ValueMap);
// Now that all of the instructions are remapped, splice them into the end
// of the NewBlock.
NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
delete New;
// LastValue map now contains values from this iteration.
std::swap(LastValueMap, ValueMap);
}
// If there was more than one iteration, replace any uses of values computed
// in the loop with values computed during the last iteration of the loop.
if (TripCount != 1) {
std::set<User*> Users;
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Users.insert(I->use_begin(), I->use_end());
// We don't want to reprocess entries with PHI nodes in them. For this
// reason, we look at each operand of each user exactly once, performing the
// stubstitution exactly once.
for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E;
++UI) {
Instruction *I = cast<Instruction>(*UI);
if (I->getParent() != BB && I->getParent() != NewBlock)
RemapInstruction(I, LastValueMap);
}
}
// Now that we cloned the block as many times as we needed, stitch the new
// code into the original block and delete the temporary block.
BB->getInstList().splice(BB->end(), NewBlock->getInstList());
delete NewBlock;
// Now loop over the PHI nodes in the original block, setting them to their
// incoming values.
BasicBlock *Preheader = L->getLoopPreheader();
for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
PHINode *PN = OrigPHINode[i];
PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
BB->getInstList().erase(PN);
}
// Finally, add an unconditional branch to the block to continue into the exit
// block.
new BranchInst(LoopExit, BB);
// At this point, the code is well formed. We now do a quick sweep over the
// inserted code, doing constant propagation and dead code elimination as we
// go.
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Instruction *Inst = I++;
if (isInstructionTriviallyDead(Inst))
BB->getInstList().erase(Inst);
else if (Constant *C = ConstantFoldInstruction(Inst)) {
Inst->replaceAllUsesWith(C);
BB->getInstList().erase(Inst);
}
}
// Update the loop information for this loop.
Loop *Parent = L->getParentLoop();
// Move all of the basic blocks in the loop into the parent loop.
LI->changeLoopFor(BB, Parent);
// Remove the loop from the parent.
if (Parent)
delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
else
delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
// FIXME: Should update dominator analyses
// Now that everything is up-to-date that will be, we fold the loop block into
// the preheader and exit block, updating our analyses as we go.
LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(),
BB->getInstList().begin(),
prior(BB->getInstList().end()));
LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(),
Preheader->getInstList().begin(),
prior(Preheader->getInstList().end()));
// Make all other blocks in the program branch to LoopExit now instead of
// Preheader.
Preheader->replaceAllUsesWith(LoopExit);
// Remove BB and LoopExit from our analyses.
LI->removeBlock(Preheader);
LI->removeBlock(BB);
// If the preheader was the entry block of this function, move the exit block
// to be the new entry of the loop.
Function *F = LoopExit->getParent();
if (Preheader == &F->front())
F->getBasicBlockList().splice(F->begin(), F->getBasicBlockList(), LoopExit);
// Actually delete the blocks now.
F->getBasicBlockList().erase(Preheader);
F->getBasicBlockList().erase(BB);
++NumUnrolled;
return true;
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2002 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <iostream>
#include <fstream>
#include "OggAudioFile.h"
OggAudioFile::OggAudioFile(std::istream* in) : AudioFile(in)
{
stream = -1;
ov_callbacks cb;
cb.read_func = OAFRead;
cb.seek_func = OAFSeek;
cb.close_func = OAFClose;
cb.tell_func = OAFTell;
OAFInputBundle* bundle = new OAFInputBundle;
in->seekg(0, ios::end);
bundle->input = in; bundle->length = std::streamoff(in->tellg());
in->seekg(0, ios::beg);
if(ov_open_callbacks(bundle, &file, NULL, 0, cb) < 0) {
std::cout << "OggAudioFile() failed: call to ov_open_callbacks failed\n";
}
else {
info = ov_info(&file, -1);
int samples = ov_pcm_total(&file, -1);
std::cout << ov_streams(&file) << " logical bitstreams\n";
init(info->rate, info->channels, samples, 2);
}
}
OggAudioFile::~OggAudioFile()
{
ov_clear(&file);
}
std::string OggAudioFile::getExtension()
{
return ".ogg";
}
bool OggAudioFile::read(void* buffer, int numFrames)
{
int frames;
int bytes = numFrames * info->channels * 2;
ogg_int64_t oldoff = ov_pcm_tell(&file);
#if BYTE_ORDER == BIG_ENDIAN
frames = ov_read(&file, (char *) buffer, bytes, 1, 2, 1, &stream);
#else
frames = ov_read(&file, (char *) buffer, bytes, 0, 2, 1, &stream);
#endif
ogg_int64_t pcmoff = ov_pcm_tell(&file);
std::cout << "requested: " << numFrames << endl;
std::cout << "actual: " << pcmoff - oldoff << endl << endl;
if (frames < 0) {
if (frames == OV_HOLE)
// OV_HOLE is non-fatal
return true;
else
return false;
}
return true;
}
size_t OAFRead(void* ptr, size_t size, size_t nmemb, void* datasource)
{
OAFInputBundle* bundle = (OAFInputBundle*) datasource;
std::streamoff pos1 = std::streamoff(bundle->input->tellg());
std::streamsize read = size * nmemb;
if (pos1 + read > bundle->length) {
read = bundle->length - pos1;
}
if (pos1 == bundle->length)
// EOF
return 0;
bundle->input->read((char*) ptr, read);
return read;
}
int OAFSeek(void* datasource, ogg_int64_t offset, int whence)
{
OAFInputBundle* bundle = (OAFInputBundle*) datasource;
switch (whence) {
case SEEK_SET:
bundle->input->seekg(offset, std::ios::beg);
break;
case SEEK_CUR:
bundle->input->seekg(offset, std::ios::cur);
break;
case SEEK_END:
bundle->input->seekg(offset, std::ios::end);
break;
}
return 0;
}
int OAFClose(void* datasource)
{
// technically we should close here, but this is handled outside
OAFInputBundle* bundle = (OAFInputBundle*) datasource;
delete bundle;
return 0;
}
long OAFTell(void* datasource)
{
OAFInputBundle* bundle = (OAFInputBundle*) datasource;
return bundle->input->tellg();
}
// ex: shiftwidth=4 tabstop=4
<commit_msg>fix for vc++<commit_after>/* bzflag
* Copyright (c) 1993 - 2002 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <iostream>
#include <fstream>
#include "OggAudioFile.h"
OggAudioFile::OggAudioFile(std::istream* in) : AudioFile(in)
{
stream = -1;
ov_callbacks cb;
cb.read_func = OAFRead;
cb.seek_func = OAFSeek;
cb.close_func = OAFClose;
cb.tell_func = OAFTell;
OAFInputBundle* bundle = new OAFInputBundle;
in->seekg(0, std::ios::end);
bundle->input = in; bundle->length = std::streamoff(in->tellg());
in->seekg(0, std::ios::beg);
if(ov_open_callbacks(bundle, &file, NULL, 0, cb) < 0) {
std::cout << "OggAudioFile() failed: call to ov_open_callbacks failed\n";
}
else {
info = ov_info(&file, -1);
int samples = ov_pcm_total(&file, -1);
std::cout << ov_streams(&file) << " logical bitstreams\n";
init(info->rate, info->channels, samples, 2);
}
}
OggAudioFile::~OggAudioFile()
{
ov_clear(&file);
}
std::string OggAudioFile::getExtension()
{
return ".ogg";
}
bool OggAudioFile::read(void* buffer, int numFrames)
{
int frames;
int bytes = numFrames * info->channels * 2;
ogg_int64_t oldoff = ov_pcm_tell(&file);
#if BYTE_ORDER == BIG_ENDIAN
frames = ov_read(&file, (char *) buffer, bytes, 1, 2, 1, &stream);
#else
frames = ov_read(&file, (char *) buffer, bytes, 0, 2, 1, &stream);
#endif
ogg_int64_t pcmoff = ov_pcm_tell(&file);
std::cout << "requested: " << numFrames << "\n";
std::cout << "actual: " << pcmoff - oldoff << "\n\n";
if (frames < 0) {
if (frames == OV_HOLE)
// OV_HOLE is non-fatal
return true;
else
return false;
}
return true;
}
size_t OAFRead(void* ptr, size_t size, size_t nmemb, void* datasource)
{
OAFInputBundle* bundle = (OAFInputBundle*) datasource;
std::streamoff pos1 = std::streamoff(bundle->input->tellg());
std::streamsize read = size * nmemb;
if (pos1 + read > bundle->length) {
read = bundle->length - pos1;
}
if (pos1 == bundle->length)
// EOF
return 0;
bundle->input->read((char*) ptr, read);
return read;
}
int OAFSeek(void* datasource, ogg_int64_t offset, int whence)
{
OAFInputBundle* bundle = (OAFInputBundle*) datasource;
switch (whence) {
case SEEK_SET:
bundle->input->seekg(offset, std::ios::beg);
break;
case SEEK_CUR:
bundle->input->seekg(offset, std::ios::cur);
break;
case SEEK_END:
bundle->input->seekg(offset, std::ios::end);
break;
}
return 0;
}
int OAFClose(void* datasource)
{
// technically we should close here, but this is handled outside
OAFInputBundle* bundle = (OAFInputBundle*) datasource;
delete bundle;
return 0;
}
long OAFTell(void* datasource)
{
OAFInputBundle* bundle = (OAFInputBundle*) datasource;
return bundle->input->tellg();
}
// ex: shiftwidth=4 tabstop=4
<|endoftext|> |
<commit_before>//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MapValue function, which is shared by various parts of
// the lib/Transforms/Utils library.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/ValueMapper.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Metadata.h"
using namespace llvm;
// Out of line method to get vtable etc for class.
void ValueMapTypeRemapper::anchor() {}
void ValueMaterializer::anchor() {}
Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
ValueToValueMapTy::iterator I = VM.find(V);
// If the value already exists in the map, use it.
if (I != VM.end() && I->second) return I->second;
// If we have a materializer and it can materialize a value, use that.
if (Materializer) {
if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
return VM[V] = NewV;
}
// Global values do not need to be seeded into the VM if they
// are using the identity mapping.
if (isa<GlobalValue>(V))
return VM[V] = const_cast<Value*>(V);
if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
// Inline asm may need *type* remapping.
FunctionType *NewTy = IA->getFunctionType();
if (TypeMapper) {
NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
if (NewTy != IA->getFunctionType())
V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
IA->hasSideEffects(), IA->isAlignStack());
}
return VM[V] = const_cast<Value*>(V);
}
if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
const Metadata *MD = MDV->getMetadata();
// If this is a module-level metadata and we know that nothing at the module
// level is changing, then use an identity mapping.
if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
return VM[V] = const_cast<Value *>(V);
auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
return VM[V] = const_cast<Value *>(V);
// FIXME: This assert crashes during bootstrap, but I think it should be
// correct. For now, just match behaviour from before the metadata/value
// split.
//
// assert(MappedMD && "Referenced metadata value not in value map");
return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
}
// Okay, this either must be a constant (which may or may not be mappable) or
// is something that is not in the mapping table.
Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
if (!C)
return nullptr;
if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Function *F =
cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
Flags, TypeMapper, Materializer));
return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
}
// Otherwise, we have some other constant to remap. Start by checking to see
// if all operands have an identity remapping.
unsigned OpNo = 0, NumOperands = C->getNumOperands();
Value *Mapped = nullptr;
for (; OpNo != NumOperands; ++OpNo) {
Value *Op = C->getOperand(OpNo);
Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
if (Mapped != C) break;
}
// See if the type mapper wants to remap the type as well.
Type *NewTy = C->getType();
if (TypeMapper)
NewTy = TypeMapper->remapType(NewTy);
// If the result type and all operands match up, then just insert an identity
// mapping.
if (OpNo == NumOperands && NewTy == C->getType())
return VM[V] = C;
// Okay, we need to create a new constant. We've already processed some or
// all of the operands, set them all up now.
SmallVector<Constant*, 8> Ops;
Ops.reserve(NumOperands);
for (unsigned j = 0; j != OpNo; ++j)
Ops.push_back(cast<Constant>(C->getOperand(j)));
// If one of the operands mismatch, push it and the other mapped operands.
if (OpNo != NumOperands) {
Ops.push_back(cast<Constant>(Mapped));
// Map the rest of the operands that aren't processed yet.
for (++OpNo; OpNo != NumOperands; ++OpNo)
Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
Flags, TypeMapper, Materializer));
}
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
return VM[V] = CE->getWithOperands(Ops, NewTy);
if (isa<ConstantArray>(C))
return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
if (isa<ConstantStruct>(C))
return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
if (isa<ConstantVector>(C))
return VM[V] = ConstantVector::get(Ops);
// If this is a no-operand constant, it must be because the type was remapped.
if (isa<UndefValue>(C))
return VM[V] = UndefValue::get(NewTy);
if (isa<ConstantAggregateZero>(C))
return VM[V] = ConstantAggregateZero::get(NewTy);
assert(isa<ConstantPointerNull>(C));
return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
}
static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
Metadata *Val) {
VM.MD()[Key].reset(Val);
return Val;
}
static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
}
static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer);
static Metadata *mapMetadataOp(Metadata *Op, ValueToValueMapTy &VM,
RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
if (!Op)
return nullptr;
if (Metadata *MappedOp =
MapMetadataImpl(Op, VM, Flags, TypeMapper, Materializer))
return MappedOp;
// Use identity map if MappedOp is null and we can ignore missing entries.
if (Flags & RF_IgnoreMissingEntries)
return Op;
// FIXME: This assert crashes during bootstrap, but I think it should be
// correct. For now, just match behaviour from before the metadata/value
// split.
//
// llvm_unreachable("Referenced metadata not in value map!");
return nullptr;
}
/// \brief Map a distinct MDNode.
///
/// Distinct nodes are not uniqued, so they must always recreated.
static Metadata *mapDistinctNode(const UniquableMDNode *Node,
ValueToValueMapTy &VM, RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
assert(Node->isDistinct() && "Expected distinct node");
// Create the node first so it's available for cyclical references.
SmallVector<Metadata *, 4> EmptyOps(Node->getNumOperands());
MDTuple *NewMD = MDTuple::getDistinct(Node->getContext(), EmptyOps);
mapToMetadata(VM, Node, NewMD);
// Fix the operands.
for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
NewMD->replaceOperandWith(I, mapMetadataOp(Node->getOperand(I), VM, Flags,
TypeMapper, Materializer));
return NewMD;
}
/// \brief Map a uniqued MDNode.
///
/// Uniqued nodes may not need to be recreated (they may map to themselves).
static Metadata *mapUniquedNode(const UniquableMDNode *Node,
ValueToValueMapTy &VM, RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
assert(!Node->isDistinct() && "Expected uniqued node");
// Create a dummy node in case we have a metadata cycle.
MDNodeFwdDecl *Dummy = MDNode::getTemporary(Node->getContext(), None);
mapToMetadata(VM, Node, Dummy);
// Check all operands to see if any need to be remapped.
for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
Metadata *Op = Node->getOperand(I);
Metadata *MappedOp = mapMetadataOp(Op, VM, Flags, TypeMapper, Materializer);
if (Op == MappedOp)
continue;
// Ok, at least one operand needs remapping.
SmallVector<Metadata *, 4> Elts;
Elts.reserve(Node->getNumOperands());
for (I = 0; I != E; ++I)
Elts.push_back(mapMetadataOp(Node->getOperand(I), VM, Flags, TypeMapper,
Materializer));
MDNode *NewMD = MDTuple::get(Node->getContext(), Elts);
Dummy->replaceAllUsesWith(NewMD);
MDNode::deleteTemporary(Dummy);
return mapToMetadata(VM, Node, NewMD);
}
// No operands needed remapping. Use an identity mapping.
mapToSelf(VM, Node);
MDNode::deleteTemporary(Dummy);
return const_cast<Metadata *>(static_cast<const Metadata *>(Node));
}
static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
// If the value already exists in the map, use it.
if (Metadata *NewMD = VM.MD().lookup(MD).get())
return NewMD;
if (isa<MDString>(MD))
return mapToSelf(VM, MD);
if (isa<ConstantAsMetadata>(MD))
if ((Flags & RF_NoModuleLevelChanges))
return mapToSelf(VM, MD);
if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
Value *MappedV =
MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
if (VMD->getValue() == MappedV ||
(!MappedV && (Flags & RF_IgnoreMissingEntries)))
return mapToSelf(VM, MD);
// FIXME: This assert crashes during bootstrap, but I think it should be
// correct. For now, just match behaviour from before the metadata/value
// split.
//
// assert(MappedV && "Referenced metadata not in value map!");
if (MappedV)
return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
return nullptr;
}
const UniquableMDNode *Node = cast<UniquableMDNode>(MD);
assert(Node->isResolved() && "Unexpected unresolved node");
// If this is a module-level metadata and we know that nothing at the
// module level is changing, then use an identity mapping.
if (Flags & RF_NoModuleLevelChanges)
return mapToSelf(VM, MD);
if (Node->isDistinct())
return mapDistinctNode(Node, VM, Flags, TypeMapper, Materializer);
return mapUniquedNode(Node, VM, Flags, TypeMapper, Materializer);
}
Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
Metadata *NewMD = MapMetadataImpl(MD, VM, Flags, TypeMapper, Materializer);
if (NewMD && NewMD != MD)
if (auto *N = dyn_cast<UniquableMDNode>(NewMD))
N->resolveCycles();
return NewMD;
}
MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
TypeMapper, Materializer));
}
/// RemapInstruction - Convert the instruction operands from referencing the
/// current values into those specified by VMap.
///
void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer){
// Remap operands.
for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
// If we aren't ignoring missing entries, assert that something happened.
if (V)
*op = V;
else
assert((Flags & RF_IgnoreMissingEntries) &&
"Referenced value not in value map!");
}
// Remap phi nodes' incoming blocks.
if (PHINode *PN = dyn_cast<PHINode>(I)) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
// If we aren't ignoring missing entries, assert that something happened.
if (V)
PN->setIncomingBlock(i, cast<BasicBlock>(V));
else
assert((Flags & RF_IgnoreMissingEntries) &&
"Referenced block not in value map!");
}
}
// Remap attached metadata.
SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
I->getAllMetadata(MDs);
for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
MI = MDs.begin(),
ME = MDs.end();
MI != ME; ++MI) {
MDNode *Old = MI->second;
MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
if (New != Old)
I->setMetadata(MI->first, New);
}
// If the instruction's type is being remapped, do so now.
if (TypeMapper)
I->mutateType(TypeMapper->remapType(I->getType()));
}
<commit_msg>Utils: Simplify code, NFC<commit_after>//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MapValue function, which is shared by various parts of
// the lib/Transforms/Utils library.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/ValueMapper.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Metadata.h"
using namespace llvm;
// Out of line method to get vtable etc for class.
void ValueMapTypeRemapper::anchor() {}
void ValueMaterializer::anchor() {}
Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
ValueToValueMapTy::iterator I = VM.find(V);
// If the value already exists in the map, use it.
if (I != VM.end() && I->second) return I->second;
// If we have a materializer and it can materialize a value, use that.
if (Materializer) {
if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
return VM[V] = NewV;
}
// Global values do not need to be seeded into the VM if they
// are using the identity mapping.
if (isa<GlobalValue>(V))
return VM[V] = const_cast<Value*>(V);
if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
// Inline asm may need *type* remapping.
FunctionType *NewTy = IA->getFunctionType();
if (TypeMapper) {
NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
if (NewTy != IA->getFunctionType())
V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
IA->hasSideEffects(), IA->isAlignStack());
}
return VM[V] = const_cast<Value*>(V);
}
if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
const Metadata *MD = MDV->getMetadata();
// If this is a module-level metadata and we know that nothing at the module
// level is changing, then use an identity mapping.
if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
return VM[V] = const_cast<Value *>(V);
auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
return VM[V] = const_cast<Value *>(V);
// FIXME: This assert crashes during bootstrap, but I think it should be
// correct. For now, just match behaviour from before the metadata/value
// split.
//
// assert(MappedMD && "Referenced metadata value not in value map");
return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
}
// Okay, this either must be a constant (which may or may not be mappable) or
// is something that is not in the mapping table.
Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
if (!C)
return nullptr;
if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Function *F =
cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
Flags, TypeMapper, Materializer));
return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
}
// Otherwise, we have some other constant to remap. Start by checking to see
// if all operands have an identity remapping.
unsigned OpNo = 0, NumOperands = C->getNumOperands();
Value *Mapped = nullptr;
for (; OpNo != NumOperands; ++OpNo) {
Value *Op = C->getOperand(OpNo);
Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
if (Mapped != C) break;
}
// See if the type mapper wants to remap the type as well.
Type *NewTy = C->getType();
if (TypeMapper)
NewTy = TypeMapper->remapType(NewTy);
// If the result type and all operands match up, then just insert an identity
// mapping.
if (OpNo == NumOperands && NewTy == C->getType())
return VM[V] = C;
// Okay, we need to create a new constant. We've already processed some or
// all of the operands, set them all up now.
SmallVector<Constant*, 8> Ops;
Ops.reserve(NumOperands);
for (unsigned j = 0; j != OpNo; ++j)
Ops.push_back(cast<Constant>(C->getOperand(j)));
// If one of the operands mismatch, push it and the other mapped operands.
if (OpNo != NumOperands) {
Ops.push_back(cast<Constant>(Mapped));
// Map the rest of the operands that aren't processed yet.
for (++OpNo; OpNo != NumOperands; ++OpNo)
Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
Flags, TypeMapper, Materializer));
}
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
return VM[V] = CE->getWithOperands(Ops, NewTy);
if (isa<ConstantArray>(C))
return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
if (isa<ConstantStruct>(C))
return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
if (isa<ConstantVector>(C))
return VM[V] = ConstantVector::get(Ops);
// If this is a no-operand constant, it must be because the type was remapped.
if (isa<UndefValue>(C))
return VM[V] = UndefValue::get(NewTy);
if (isa<ConstantAggregateZero>(C))
return VM[V] = ConstantAggregateZero::get(NewTy);
assert(isa<ConstantPointerNull>(C));
return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
}
static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
Metadata *Val) {
VM.MD()[Key].reset(Val);
return Val;
}
static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
}
static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer);
static Metadata *mapMetadataOp(Metadata *Op, ValueToValueMapTy &VM,
RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
if (!Op)
return nullptr;
if (Metadata *MappedOp =
MapMetadataImpl(Op, VM, Flags, TypeMapper, Materializer))
return MappedOp;
// Use identity map if MappedOp is null and we can ignore missing entries.
if (Flags & RF_IgnoreMissingEntries)
return Op;
// FIXME: This assert crashes during bootstrap, but I think it should be
// correct. For now, just match behaviour from before the metadata/value
// split.
//
// llvm_unreachable("Referenced metadata not in value map!");
return nullptr;
}
/// \brief Map a distinct MDNode.
///
/// Distinct nodes are not uniqued, so they must always recreated.
static Metadata *mapDistinctNode(const UniquableMDNode *Node,
ValueToValueMapTy &VM, RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
assert(Node->isDistinct() && "Expected distinct node");
// Create the node first so it's available for cyclical references.
SmallVector<Metadata *, 4> EmptyOps(Node->getNumOperands());
MDTuple *NewMD = MDTuple::getDistinct(Node->getContext(), EmptyOps);
mapToMetadata(VM, Node, NewMD);
// Fix the operands.
for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
NewMD->replaceOperandWith(I, mapMetadataOp(Node->getOperand(I), VM, Flags,
TypeMapper, Materializer));
return NewMD;
}
/// \brief Map a uniqued MDNode.
///
/// Uniqued nodes may not need to be recreated (they may map to themselves).
static Metadata *mapUniquedNode(const UniquableMDNode *Node,
ValueToValueMapTy &VM, RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
assert(!Node->isDistinct() && "Expected uniqued node");
// Create a dummy node in case we have a metadata cycle.
MDNodeFwdDecl *Dummy = MDNode::getTemporary(Node->getContext(), None);
mapToMetadata(VM, Node, Dummy);
// Check all operands to see if any need to be remapped.
for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
Metadata *Op = Node->getOperand(I);
if (Op == mapMetadataOp(Op, VM, Flags, TypeMapper, Materializer))
continue;
// Ok, at least one operand needs remapping.
SmallVector<Metadata *, 4> Elts;
Elts.reserve(Node->getNumOperands());
for (I = 0; I != E; ++I)
Elts.push_back(mapMetadataOp(Node->getOperand(I), VM, Flags, TypeMapper,
Materializer));
MDNode *NewMD = MDTuple::get(Node->getContext(), Elts);
Dummy->replaceAllUsesWith(NewMD);
MDNode::deleteTemporary(Dummy);
return mapToMetadata(VM, Node, NewMD);
}
// No operands needed remapping. Use an identity mapping.
mapToSelf(VM, Node);
MDNode::deleteTemporary(Dummy);
return const_cast<Metadata *>(static_cast<const Metadata *>(Node));
}
static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
RemapFlags Flags,
ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
// If the value already exists in the map, use it.
if (Metadata *NewMD = VM.MD().lookup(MD).get())
return NewMD;
if (isa<MDString>(MD))
return mapToSelf(VM, MD);
if (isa<ConstantAsMetadata>(MD))
if ((Flags & RF_NoModuleLevelChanges))
return mapToSelf(VM, MD);
if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
Value *MappedV =
MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
if (VMD->getValue() == MappedV ||
(!MappedV && (Flags & RF_IgnoreMissingEntries)))
return mapToSelf(VM, MD);
// FIXME: This assert crashes during bootstrap, but I think it should be
// correct. For now, just match behaviour from before the metadata/value
// split.
//
// assert(MappedV && "Referenced metadata not in value map!");
if (MappedV)
return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
return nullptr;
}
const UniquableMDNode *Node = cast<UniquableMDNode>(MD);
assert(Node->isResolved() && "Unexpected unresolved node");
// If this is a module-level metadata and we know that nothing at the
// module level is changing, then use an identity mapping.
if (Flags & RF_NoModuleLevelChanges)
return mapToSelf(VM, MD);
if (Node->isDistinct())
return mapDistinctNode(Node, VM, Flags, TypeMapper, Materializer);
return mapUniquedNode(Node, VM, Flags, TypeMapper, Materializer);
}
Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
Metadata *NewMD = MapMetadataImpl(MD, VM, Flags, TypeMapper, Materializer);
if (NewMD && NewMD != MD)
if (auto *N = dyn_cast<UniquableMDNode>(NewMD))
N->resolveCycles();
return NewMD;
}
MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer) {
return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
TypeMapper, Materializer));
}
/// RemapInstruction - Convert the instruction operands from referencing the
/// current values into those specified by VMap.
///
void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
ValueMaterializer *Materializer){
// Remap operands.
for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
// If we aren't ignoring missing entries, assert that something happened.
if (V)
*op = V;
else
assert((Flags & RF_IgnoreMissingEntries) &&
"Referenced value not in value map!");
}
// Remap phi nodes' incoming blocks.
if (PHINode *PN = dyn_cast<PHINode>(I)) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
// If we aren't ignoring missing entries, assert that something happened.
if (V)
PN->setIncomingBlock(i, cast<BasicBlock>(V));
else
assert((Flags & RF_IgnoreMissingEntries) &&
"Referenced block not in value map!");
}
}
// Remap attached metadata.
SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
I->getAllMetadata(MDs);
for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
MI = MDs.begin(),
ME = MDs.end();
MI != ME; ++MI) {
MDNode *Old = MI->second;
MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
if (New != Old)
I->setMetadata(MI->first, New);
}
// If the instruction's type is being remapped, do so now.
if (TypeMapper)
I->mutateType(TypeMapper->remapType(I->getType()));
}
<|endoftext|> |
<commit_before>#include "menu/option_mugen_menu.h"
#include "util/bitmap.h"
#include "util/font.h"
#include "menu/menu.h"
#include "util/token.h"
#include "return_exception.h"
#include "util/token_exception.h"
#include "util/funcs.h"
#include "globals.h"
#include "mugen/mugen_menu.h"
#include "mugen/mugen_exception.h"
#include "return_exception.h"
using namespace std;
OptionMugenMenu::OptionMugenMenu(Token *token) throw (LoadException): MenuOption(token, Event), _menu(0)
{
if ( *token != "mugen" ){
throw LoadException("Not a mugen motif menu");
}
while ( token->hasTokens() ){
try{
Token * tok;
*token >> tok;
if ( *tok == "name" ){
// Create an image and push it back on to vector
std::string temp;
*tok >> temp;
this->setText(temp);
} else if (*tok == "motif"){
// Load Motif from file
std::string temp;
// Filename
*tok >> temp;
_menu = new MugenMenu(temp);
}else {
Global::debug( 3 ) <<"Unhandled menu attribute: "<<endl;
if (Global::getDebug() >= 3){
tok->print(" ");
}
}
} catch ( const TokenException & ex ) {
// delete current;
string m( "Menu parse error: " );
m += ex.getReason();
throw LoadException( m );
}
}
// Set this menu as an option
_menu->setAsOption(true);
// Lets check if this menu is going bye bye
//if ( _menu->checkRemoval() ) setForRemoval(true);
}
OptionMugenMenu::~OptionMugenMenu()
{
// Delete our menu
if(_menu)delete _menu;
}
void OptionMugenMenu::logic()
{
// Nothing
}
void OptionMugenMenu::run(bool &endGame){
// Load er up and throw up a load box to inform the user
Box::msgDialog(*getParent()->getWork(),"Loading M.U.G.E.N.!",2);
try {
_menu->loadData();
} catch (const MugenException & ex){
string m("Problem with loading MUGEN menu: ");
m += ex.getFullReason();
throw LoadException(m);
}
try {
// Run
_menu->run();
} catch (const ReturnException & re){
// Say what?
// Do not quit game
}
}
<commit_msg>use normal loading screen when loading mugen<commit_after>#include "menu/option_mugen_menu.h"
#include "util/bitmap.h"
#include "util/font.h"
#include "menu/menu.h"
#include "util/token.h"
#include "return_exception.h"
#include "util/token_exception.h"
#include "util/funcs.h"
#include "globals.h"
#include "loading.h"
#include <pthread.h>
#include "mugen/mugen_menu.h"
#include "mugen/mugen_exception.h"
#include "return_exception.h"
using namespace std;
OptionMugenMenu::OptionMugenMenu(Token *token) throw (LoadException): MenuOption(token, Event), _menu(0){
if ( *token != "mugen" ){
throw LoadException("Not a mugen motif menu");
}
while ( token->hasTokens() ){
try{
Token * tok;
*token >> tok;
if ( *tok == "name" ){
// Create an image and push it back on to vector
std::string temp;
*tok >> temp;
this->setText(temp);
} else if (*tok == "motif"){
// Load Motif from file
std::string temp;
// Filename
*tok >> temp;
_menu = new MugenMenu(temp);
}else {
Global::debug( 3 ) <<"Unhandled menu attribute: "<<endl;
if (Global::getDebug() >= 3){
tok->print(" ");
}
}
} catch ( const TokenException & ex ) {
// delete current;
string m( "Menu parse error: " );
m += ex.getReason();
throw LoadException( m );
}
}
// Set this menu as an option
_menu->setAsOption(true);
// Lets check if this menu is going bye bye
//if ( _menu->checkRemoval() ) setForRemoval(true);
}
OptionMugenMenu::~OptionMugenMenu(){
// Delete our menu
if (_menu){
delete _menu;
}
}
void OptionMugenMenu::logic(){
// Nothing
}
void OptionMugenMenu::run(bool &endGame){
// Load er up and throw up a load box to inform the user
// Box::msgDialog(*getParent()->getWork(),"Loading M.U.G.E.N.!",2);
pthread_t loading;
Loader::startLoading(&loading);
try {
_menu->loadData();
} catch (const MugenException & ex){
string m("Problem with loading MUGEN menu: ");
m += ex.getFullReason();
Loader::stopLoading(loading);
throw LoadException(m);
}
Loader::stopLoading(loading);
try {
// Run
_menu->run();
} catch (const ReturnException & re){
// Say what?
// Do not quit game
}
}
<|endoftext|> |
<commit_before>#if defined(LINUX)
#include "user/util.h"
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#define O_CREATE O_CREAT
#define xfork() fork()
#define xexit() exit(EXIT_SUCCESS)
typedef uint64_t u64;
#else
#include "types.h"
#include "user.h"
#include "fcntl.h"
#include "amd64.h"
#define xfork() fork(0)
#define xexit() exit()
#endif
#define CHUNKSZ 512
#define FILESZ (NCPU*CHUNKSZ)
static const bool pinit = true;
static char chunkbuf[CHUNKSZ];
static void
bench(int tid, int nloop)
{
if (pinit)
setaffinity(tid);
int fd = open("filebenchx", O_RDONLY);
if (fd < 0)
die("open");
for (int i = 0; i < nloop; i++) {
ssize_t r;
r = pread(fd, chunkbuf, CHUNKSZ, CHUNKSZ*tid);
if (r != CHUNKSZ)
die("pread");
}
close(fd);
xexit();
}
int
main(int ac, char **av)
{
int nthread;
int nloop;
#ifdef HW_qemu
nloop = 50;
#else
nloop = 1000;
#endif
if (ac < 2)
die("usage: %s nthreads [nloop]", av[0]);
nthread = atoi(av[1]);
if (ac > 2)
nloop = atoi(av[2]);
// Setup shared file
int fd = open("filebenchx", O_CREATE|O_WRONLY);
if (fd < 0)
die("open O_CREAT failed");
for (int i = 0; i < FILESZ; i += CHUNKSZ) {
int r = write(fd, chunkbuf, CHUNKSZ);
if (r < CHUNKSZ)
die("write");
}
close(fd);
u64 t0 = rdtsc();
for (int i = 0; i < nthread; i++) {
int pid = xfork();
if (pid == 0)
bench(i, nloop);
else if (pid < 0)
die("fork");
}
for (int i = 0; i < nthread; i++)
wait();
u64 t1 = rdtsc();
printf("filebench: %lu\n", t1-t0);
return 0;
}
<commit_msg>A few more filebench tweaks<commit_after>#if defined(LINUX)
#include "user/util.h"
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#define O_CREATE O_CREAT
#define xfork() fork()
#define xexit() exit(EXIT_SUCCESS)
#define xcreat(name) open((name), O_CREATE|O_WRONLY, S_IRUSR|S_IWUSR)
typedef uint64_t u64;
#else
#include "types.h"
#include "user.h"
#include "fcntl.h"
#include "amd64.h"
#define xfork() fork(0)
#define xexit() exit()
#define xcreat(name) open((name), O_CREATE|O_WRONLY)
#endif
#define CHUNKSZ 512
#define FILESZ (NCPU*CHUNKSZ)
static const bool pinit = true;
static char chunkbuf[CHUNKSZ];
static void
bench(int tid, int nloop)
{
if (pinit)
setaffinity(tid);
int fd = open("filebenchx", O_RDWR);
if (fd < 0)
die("open");
for (int i = 0; i < nloop; i++) {
ssize_t r;
r = pread(fd, chunkbuf, CHUNKSZ, CHUNKSZ*tid);
if (r != CHUNKSZ)
die("pread");
}
close(fd);
xexit();
}
int
main(int ac, char **av)
{
int nthread;
int nloop;
#ifdef HW_qemu
nloop = 50;
#else
nloop = 1000;
#endif
if (ac < 2)
die("usage: %s nthreads [nloop]", av[0]);
nthread = atoi(av[1]);
if (ac > 2)
nloop = atoi(av[2]);
// Setup shared file
unlink("filebenchx");
int fd = xcreat("filebenchx");
if (fd < 0)
die("open O_CREAT failed");
for (int i = 0; i < FILESZ; i += CHUNKSZ) {
int r = write(fd, chunkbuf, CHUNKSZ);
if (r < CHUNKSZ)
die("write");
}
close(fd);
u64 t0 = rdtsc();
for (int i = 0; i < nthread; i++) {
int pid = xfork();
if (pid == 0)
bench(i, nloop);
else if (pid < 0)
die("fork");
}
for (int i = 0; i < nthread; i++)
wait();
u64 t1 = rdtsc();
printf("filebench: %lu\n", t1-t0);
return 0;
}
<|endoftext|> |
<commit_before>#include "json.h"
#include <boost/io/ios_state.hpp>
#include <boost/type_traits.hpp>
#include <cstdio>
namespace mfast {
namespace json {
namespace encode_detail {
struct quoted_string {
quoted_string(const char* str)
: str_(str)
{
}
const char* str_;
};
std::ostream& operator << (std::ostream& os, quoted_string str)
{
os.put('"');
const char* ptr = str.str_;
while (*ptr != '\x0') {
if (*ptr == '\\' || *ptr == '"')
os.put('\\');
os.put(*ptr++);
}
os.put('"');
return os;
}
class json_visitor
{
protected:
std::ostream& strm_;
char separator_[2];
unsigned json_object_tag_mask_;
public:
enum {
visit_absent = 0
};
json_visitor(std::ostream& strm,
unsigned json_object_tag_mask)
: strm_(strm)
, json_object_tag_mask_(json_object_tag_mask)
{
separator_[0] = 0;
separator_[1] = 0;
}
template <typename NumericTypeRef>
void visit(const NumericTypeRef& ref)
{
strm_ << separator_ << ref.value();
}
void visit(const decimal_cref& ref)
{
const decimal_value_storage& storage = *reinterpret_cast<const decimal_value_storage*>( field_cref_core_access::storage_of(ref) );
strm_ << separator_ << storage;
}
void visit(const enum_cref& ref)
{
if (ref.is_boolean())
strm_ << separator_ << ref.value_name();
else
strm_ << separator_ << ref.value();
}
template <typename Char>
void visit(const mfast::string_cref<Char>& ref)
{
strm_ << separator_ << quoted_string(ref.c_str());
}
void visit(const mfast::byte_vector_cref& ref)
{
if (ref.instruction()->tag().to_uint64() & json_object_tag_mask_)
{
// if the json_object_tag_mask is on, that means the field contains
// json encoded object already, just write it as it is without any processing.
strm_.rdbuf()->sputn( reinterpret_cast<const char*>(ref.data()), ref.size());
}
else
{
// json doesn't have byte vector, treat it as hex string now
strm_ << separator_ << "\"";
boost::io::ios_flags_saver ifs( strm_ );
strm_ << std::hex << std::setfill('0') << std::setw(2);
for (std::size_t i = 0; i < ref.size(); ++i)
{
// if the size is 16, we treat it as a UUID
if (ref.size() == 16 && (i==4 || i==6 || i==8 || i==10))
strm_ << '-';
strm_ << (0xFF & (int) ref[i]);
}
strm_ << "\"" << std::setfill(' ');
}
}
template <typename IntType>
void visit(const mfast::int_vector_cref<IntType>& ref)
{
strm_ << separator_ << "[";
separator_[0] = '\0';
for (std::size_t i = 0; i < ref.size(); ++i) {
strm_ << separator_ << ref[i];
separator_[0] = ',';
}
strm_ << "]";
}
void visit(const mfast::aggregate_cref& ref, int)
{
if (ref.num_fields() == 1) {
field_cref f0 = ref[0];
if (f0.instruction()->field_type() == mfast::field_type_templateref) {
if (f0.present())
this->visit(mfast::nested_message_cref(f0),0);
return;
}
}
strm_ << separator_ << "{";
separator_[0] = '\0';
for (std::size_t i = 0; i < ref.num_fields(); ++i) {
if (ref[i].present()) {
strm_ << separator_ << quoted_string(ref[i].name()) << ":";
separator_[0] = '\0';
ref[i].accept_accessor(*this);
separator_[0] = ',';
}
}
strm_ << "}";
}
void visit(const mfast::sequence_cref& ref, int)
{
strm_ << separator_ << "[";
if (ref.size()) {
separator_[0] = '\0';
ref.accept_accessor(*this);
}
strm_ << "]";
}
void visit(const mfast::sequence_element_cref& ref, int)
{
if (ref.element_unnamed()) {
ref[0].accept_accessor(*this);
}
else {
this->visit(mfast::aggregate_cref(ref), 0);
}
separator_[0] = ',';
}
void visit(const mfast::nested_message_cref& ref, int)
{
this->visit(mfast::aggregate_cref(ref), 0);
}
};
class json_visitor_with_ignore_tag
: public json_visitor
{
private:
unsigned ignore_tag_mask_;
public:
using json_visitor::visit;
json_visitor_with_ignore_tag(std::ostream& strm,
unsigned json_object_tag_mask,
unsigned ignore_tag_mask)
: json_visitor(strm, json_object_tag_mask)
, ignore_tag_mask_(ignore_tag_mask)
{
}
void visit(const mfast::aggregate_cref& ref, int)
{
if (ref.num_fields() == 1) {
field_cref f0 = ref[0];
if (f0.instruction()->field_type() == mfast::field_type_templateref) {
if (f0.present())
this->visit(mfast::nested_message_cref(f0),0);
return;
}
}
strm_ << separator_ << "{";
separator_[0] = '\0';
for (std::size_t i = 0; i < ref.num_fields(); ++i) {
if (ref[i].present() && 0 == (ref[i].instruction()->tag().to_uint64() & ignore_tag_mask_)) {
strm_ << separator_ << quoted_string(ref[i].name()) << ":";
separator_[0] = '\0';
ref[i].accept_accessor(*this);
separator_[0] = ',';
}
}
strm_ << "}";
}
};
} // namspace encode_detail
bool encode(std::ostream& os,
const mfast::aggregate_cref& msg,
unsigned json_object_tag_mask)
{
encode_detail::json_visitor visitor(os, json_object_tag_mask);
visitor.visit(msg, 0);
return os.good();
}
bool encode(std::ostream& os,
const mfast::sequence_cref& seq,
unsigned json_object_tag_mask)
{
encode_detail::json_visitor visitor(os, json_object_tag_mask);
visitor.visit(seq, 0);
return os.good();
}
bool encode(std::ostream& os,
const ::mfast::aggregate_cref& msg,
unsigned json_object_tag_mask,
unsigned ignore_tag_mask)
{
encode_detail::json_visitor_with_ignore_tag visitor(os, json_object_tag_mask, ignore_tag_mask);
visitor.visit(msg, 0);
return os.good();
}
} // namespace json
} // namespace mfast
<commit_msg>Fixed json encoder problem with nested fields not properly ignored.<commit_after>#include "json.h"
#include <boost/io/ios_state.hpp>
#include <boost/type_traits.hpp>
#include <cstdio>
namespace mfast {
namespace json {
namespace encode_detail {
struct quoted_string {
quoted_string(const char* str)
: str_(str)
{
}
const char* str_;
};
std::ostream& operator << (std::ostream& os, quoted_string str)
{
os.put('"');
const char* ptr = str.str_;
while (*ptr != '\x0') {
if (*ptr == '\\' || *ptr == '"')
os.put('\\');
os.put(*ptr++);
}
os.put('"');
return os;
}
class json_visitor
{
protected:
std::ostream& strm_;
char separator_[2];
unsigned json_object_tag_mask_;
public:
enum {
visit_absent = 0
};
json_visitor(std::ostream& strm,
unsigned json_object_tag_mask)
: strm_(strm)
, json_object_tag_mask_(json_object_tag_mask)
{
separator_[0] = 0;
separator_[1] = 0;
}
template <typename NumericTypeRef>
void visit(const NumericTypeRef& ref)
{
strm_ << separator_ << ref.value();
}
void visit(const decimal_cref& ref)
{
const decimal_value_storage& storage = *reinterpret_cast<const decimal_value_storage*>( field_cref_core_access::storage_of(ref) );
strm_ << separator_ << storage;
}
void visit(const enum_cref& ref)
{
if (ref.is_boolean())
strm_ << separator_ << ref.value_name();
else
strm_ << separator_ << ref.value();
}
template <typename Char>
void visit(const mfast::string_cref<Char>& ref)
{
strm_ << separator_ << quoted_string(ref.c_str());
}
void visit(const mfast::byte_vector_cref& ref)
{
if (ref.instruction()->tag().to_uint64() & json_object_tag_mask_)
{
// if the json_object_tag_mask is on, that means the field contains
// json encoded object already, just write it as it is without any processing.
strm_.rdbuf()->sputn( reinterpret_cast<const char*>(ref.data()), ref.size());
}
else
{
// json doesn't have byte vector, treat it as hex string now
strm_ << separator_ << "\"";
boost::io::ios_flags_saver ifs( strm_ );
strm_ << std::hex << std::setfill('0') << std::setw(2);
for (std::size_t i = 0; i < ref.size(); ++i)
{
// if the size is 16, we treat it as a UUID
if (ref.size() == 16 && (i==4 || i==6 || i==8 || i==10))
strm_ << '-';
strm_ << (0xFF & (int) ref[i]);
}
strm_ << "\"" << std::setfill(' ');
}
}
template <typename IntType>
void visit(const mfast::int_vector_cref<IntType>& ref)
{
strm_ << separator_ << "[";
separator_[0] = '\0';
for (std::size_t i = 0; i < ref.size(); ++i) {
strm_ << separator_ << ref[i];
separator_[0] = ',';
}
strm_ << "]";
}
virtual void visit(const mfast::aggregate_cref& ref, int)
{
if (ref.num_fields() == 1) {
field_cref f0 = ref[0];
if (f0.instruction()->field_type() == mfast::field_type_templateref) {
if (f0.present())
this->visit(mfast::nested_message_cref(f0),0);
return;
}
}
strm_ << separator_ << "{";
separator_[0] = '\0';
for (std::size_t i = 0; i < ref.num_fields(); ++i) {
if (ref[i].present()) {
strm_ << separator_ << quoted_string(ref[i].name()) << ":";
separator_[0] = '\0';
ref[i].accept_accessor(*this);
separator_[0] = ',';
}
}
strm_ << "}";
}
void visit(const mfast::sequence_cref& ref, int)
{
strm_ << separator_ << "[";
if (ref.size()) {
separator_[0] = '\0';
ref.accept_accessor(*this);
}
strm_ << "]";
}
void visit(const mfast::sequence_element_cref& ref, int)
{
if (ref.element_unnamed()) {
ref[0].accept_accessor(*this);
}
else {
this->visit(mfast::aggregate_cref(ref), 0);
}
separator_[0] = ',';
}
void visit(const mfast::nested_message_cref& ref, int)
{
this->visit(mfast::aggregate_cref(ref), 0);
}
};
class json_visitor_with_ignore_tag
: public json_visitor
{
private:
unsigned ignore_tag_mask_;
public:
using json_visitor::visit;
json_visitor_with_ignore_tag(std::ostream& strm,
unsigned json_object_tag_mask,
unsigned ignore_tag_mask)
: json_visitor(strm, json_object_tag_mask)
, ignore_tag_mask_(ignore_tag_mask)
{
}
virtual void visit(const mfast::aggregate_cref& ref, int)
{
if (ref.num_fields() == 1) {
field_cref f0 = ref[0];
if (f0.instruction()->field_type() == mfast::field_type_templateref) {
if (f0.present())
this->visit(mfast::nested_message_cref(f0),0);
return;
}
}
strm_ << separator_ << "{";
separator_[0] = '\0';
for (std::size_t i = 0; i < ref.num_fields(); ++i) {
if (ref[i].present() && 0 == (ref[i].instruction()->tag().to_uint64() & ignore_tag_mask_)) {
strm_ << separator_ << quoted_string(ref[i].name()) << ":";
separator_[0] = '\0';
ref[i].accept_accessor(*this);
separator_[0] = ',';
}
}
strm_ << "}";
}
};
} // namspace encode_detail
bool encode(std::ostream& os,
const mfast::aggregate_cref& msg,
unsigned json_object_tag_mask)
{
encode_detail::json_visitor visitor(os, json_object_tag_mask);
visitor.visit(msg, 0);
return os.good();
}
bool encode(std::ostream& os,
const mfast::sequence_cref& seq,
unsigned json_object_tag_mask)
{
encode_detail::json_visitor visitor(os, json_object_tag_mask);
visitor.visit(seq, 0);
return os.good();
}
bool encode(std::ostream& os,
const ::mfast::aggregate_cref& msg,
unsigned json_object_tag_mask,
unsigned ignore_tag_mask)
{
encode_detail::json_visitor_with_ignore_tag visitor(os, json_object_tag_mask, ignore_tag_mask);
visitor.visit(msg, 0);
return os.good();
}
} // namespace json
} // namespace mfast
<|endoftext|> |
<commit_before>/**
* @file consensushash.cpp
*
* This file contains the function to generate consensus hashes.
*/
#include "omnicore/consensushash.h"
#include "omnicore/dex.h"
#include "omnicore/mdex.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/sp.h"
#include <stdint.h>
#include <string>
#include <openssl/sha.h>
namespace mastercore
{
/**
* Obtains a hash of the active state to use for consensus verification and checkpointing.
*
* For increased flexibility, so other implementations like OmniWallet and OmniChest can
* also apply this methodology without necessarily using the same exact data types (which
* would be needed to hash the data bytes directly), create a string in the following
* format for each entry to use for hashing:
*
* ---STAGE 1 - BALANCES---
* Format specifiers & placeholders:
* "%s|%d|%d|%d|%d|%d" - "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
*
* Note: empty balance records and the pending tally are ignored. Addresses are sorted based
* on lexicographical order, and balance records are sorted by the property identifiers.
*
* ---STAGE 2 - DEX SELL OFFERS---
* Format specifiers & placeholders:
* "%s|%s|%d|%d|%d|%d|%d|%d|%d" - "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit|availableamount|acceptedamount"
*
* Note: ordered ascending by txid.
*
* ---STAGE 3 - DEX ACCEPTS---
* Format specifiers & placeholders:
* "%s|%s|%d|%d|%d" - "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock"
*
* Note: ordered ascending by matchedselloffertxid followed by buyer.
*
* ---STAGE 4 - METADEX TRADES---
* Format specifiers & placeholders:
* "%s|%s|%d|%d|%d|%d|%d" - "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining"
*
* Note: ordered ascending by txid.
*
* ---STAGE 5 - CROWDSALES---
* Format specifiers & placeholders:
* "%d|%d|%d|%d|%d" - "propertyid|propertyiddesired|deadline|usertokens|issuertokens"
*
* Note: ordered by property ID.
*
* ---STAGE 6 - PROPERTIES---
* Format specifiers & placeholders:
* "%d|%d" - "nextavailablepropertyidmaineco|nextavailablepropertyidtesteco"
*
* The byte order is important, and we assume:
* SHA256("abc") = "ad1500f261ff10b49c7a1796a36103b02322ae5dde404141eacf018fbf1678ba"
*
*/
uint256 GetConsensusHash()
{
// allocate and init a SHA256_CTX
SHA256_CTX shaCtx;
SHA256_Init(&shaCtx);
LOCK(cs_tally);
if (msc_debug_consensus_hash) PrintToLog("Beginning generation of current consensus hash...\n");
// Balances - loop through the tally map, updating the sha context with the data from each balance and tally type
// Placeholders: "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
for (std::map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it) {
const std::string& address = my_it->first;
CMPTally& tally = my_it->second;
tally.init();
uint32_t propertyId = 0;
while (0 != (propertyId = (tally.next()))) {
int64_t balance = tally.getMoney(propertyId, BALANCE);
int64_t sellOfferReserve = tally.getMoney(propertyId, SELLOFFER_RESERVE);
int64_t acceptReserve = tally.getMoney(propertyId, ACCEPT_RESERVE);
int64_t metaDExReserve = tally.getMoney(propertyId, METADEX_RESERVE);
// skip this entry if all balances are empty
if (!balance && !sellOfferReserve && !acceptReserve && !metaDExReserve) continue;
std::string dataStr = strprintf("%s|%d|%d|%d|%d|%d",
address, propertyId, balance, sellOfferReserve, acceptReserve, metaDExReserve);
if (msc_debug_consensus_hash) PrintToLog("Adding balance data to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
}
// DEx sell offers - loop through the DEx and add each sell offer to the consensus hash (ordered by txid)
// Placeholders: "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit|availableamount|acceptedamount"
std::vector<std::pair<uint256, std::string> > vecDExOffers;
for (OfferMap::iterator it = my_offers.begin(); it != my_offers.end(); ++it) {
const CMPOffer& selloffer = it->second;
const std::string& sellCombo = it->first;
uint32_t propertyId = selloffer.getProperty();
std::string seller = sellCombo.substr(0, sellCombo.size() - 2);
std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d|%d|%d",
selloffer.getHash().GetHex(), seller, propertyId, selloffer.getOfferAmountOriginal(),
selloffer.getBTCDesiredOriginal(), selloffer.getMinFee(), selloffer.getBlockTimeLimit(),
getMPbalance(seller, propertyId, SELLOFFER_RESERVE), getMPbalance(seller, propertyId, ACCEPT_RESERVE));
vecDExOffers.push_back(std::make_pair(selloffer.getHash(), dataStr));
}
std::sort (vecDExOffers.begin(), vecDExOffers.end());
for (std::vector<std::pair<uint256, std::string> >::iterator it = vecDExOffers.begin(); it != vecDExOffers.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding DEx offer data to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// DEx accepts - loop through the accepts map and add each accept to the consensus hash (ordered by matchedtxid then buyer)
// Placeholders: "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock"
std::vector<std::pair<std::string, std::string> > vecAccepts;
for (AcceptMap::const_iterator it = my_accepts.begin(); it != my_accepts.end(); ++it) {
const CMPAccept& accept = it->second;
const std::string& acceptCombo = it->first;
std::string buyer = acceptCombo.substr((acceptCombo.find("+") + 1), (acceptCombo.size()-(acceptCombo.find("+") + 1)));
std::string dataStr = strprintf("%s|%s|%d|%d|%d",
accept.getHash().GetHex(), buyer, accept.getAcceptAmount(), accept.getAcceptAmountRemaining(), accept.getAcceptBlock());
std::string sortKey = strprintf("%s-%s", accept.getHash().GetHex(), buyer);
vecAccepts.push_back(std::make_pair(sortKey, dataStr));
}
std::sort (vecAccepts.begin(), vecAccepts.end());
for (std::vector<std::pair<std::string, std::string> >::iterator it = vecAccepts.begin(); it != vecAccepts.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding DEx accept to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// MetaDEx trades - loop through the MetaDEx maps and add each open trade to the consensus hash (ordered by txid)
// Placeholders: "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining"
std::vector<std::pair<uint256, std::string> > vecMetaDExTrades;
for (md_PropertiesMap::const_iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
const md_PricesMap& prices = my_it->second;
for (md_PricesMap::const_iterator it = prices.begin(); it != prices.end(); ++it) {
const md_Set& indexes = it->second;
for (md_Set::const_iterator it = indexes.begin(); it != indexes.end(); ++it) {
const CMPMetaDEx& obj = *it;
std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d",
obj.getHash().GetHex(), obj.getAddr(), obj.getProperty(), obj.getAmountForSale(),
obj.getDesProperty(), obj.getAmountDesired(), obj.getAmountRemaining());
vecMetaDExTrades.push_back(std::make_pair(obj.getHash(), dataStr));
}
}
}
std::sort (vecMetaDExTrades.begin(), vecMetaDExTrades.end());
for (std::vector<std::pair<uint256, std::string> >::iterator it = vecMetaDExTrades.begin(); it != vecMetaDExTrades.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding MetaDEx trade data to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// Crowdsales - loop through open crowdsales and add to the consensus hash (ordered by property ID)
// Note: the variables of the crowdsale (amount, bonus etc) are not part of the crowdsale map and not included here to
// avoid additionalal loading of SP entries from the database
// Placeholders: "propertyid|propertyiddesired|deadline|usertokens|issuertokens"
std::vector<std::pair<uint32_t, std::string> > vecCrowds;
for (CrowdMap::const_iterator it = my_crowds.begin(); it != my_crowds.end(); ++it) {
const CMPCrowd& crowd = it->second;
uint32_t propertyId = crowd.getPropertyId();
std::string dataStr = strprintf("%d|%d|%d|%d|%d",
crowd.getPropertyId(), crowd.getCurrDes(), crowd.getDeadline(), crowd.getUserCreated(), crowd.getIssuerCreated());
vecCrowds.push_back(std::make_pair(propertyId, dataStr));
}
std::sort (vecCrowds.begin(), vecCrowds.end());
for (std::vector<std::pair<uint32_t, std::string> >::iterator it = vecCrowds.begin(); it != vecCrowds.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding Crowdsale entry to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// Properties - add the next available property ID in both the main and test ecosystems
// Placeholders: "nextavailablepropertyidmaineco|nextavailablepropertyidtesteco"
std::string dataStr = strprintf("%d|%d", _my_sps->peekNextSPID(1), _my_sps->peekNextSPID(2));
if (msc_debug_consensus_hash) PrintToLog("Adding property to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
// extract the final result and return the hash
uint256 consensusHash;
SHA256_Final((unsigned char*)&consensusHash, &shaCtx);
if (msc_debug_consensus_hash) PrintToLog("Finished generation of consensus hash. Result: %s\n", consensusHash.GetHex());
return consensusHash;
}
} // namespace mastercore
<commit_msg>Remove reserved amounts from DEx sell data added to consensus hash<commit_after>/**
* @file consensushash.cpp
*
* This file contains the function to generate consensus hashes.
*/
#include "omnicore/consensushash.h"
#include "omnicore/dex.h"
#include "omnicore/mdex.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/sp.h"
#include <stdint.h>
#include <string>
#include <openssl/sha.h>
namespace mastercore
{
/**
* Obtains a hash of the active state to use for consensus verification and checkpointing.
*
* For increased flexibility, so other implementations like OmniWallet and OmniChest can
* also apply this methodology without necessarily using the same exact data types (which
* would be needed to hash the data bytes directly), create a string in the following
* format for each entry to use for hashing:
*
* ---STAGE 1 - BALANCES---
* Format specifiers & placeholders:
* "%s|%d|%d|%d|%d|%d" - "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
*
* Note: empty balance records and the pending tally are ignored. Addresses are sorted based
* on lexicographical order, and balance records are sorted by the property identifiers.
*
* ---STAGE 2 - DEX SELL OFFERS---
* Format specifiers & placeholders:
* "%s|%s|%d|%d|%d|%d|%d" - "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit"
*
* Note: ordered ascending by txid.
*
* ---STAGE 3 - DEX ACCEPTS---
* Format specifiers & placeholders:
* "%s|%s|%d|%d|%d" - "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock"
*
* Note: ordered ascending by matchedselloffertxid followed by buyer.
*
* ---STAGE 4 - METADEX TRADES---
* Format specifiers & placeholders:
* "%s|%s|%d|%d|%d|%d|%d" - "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining"
*
* Note: ordered ascending by txid.
*
* ---STAGE 5 - CROWDSALES---
* Format specifiers & placeholders:
* "%d|%d|%d|%d|%d" - "propertyid|propertyiddesired|deadline|usertokens|issuertokens"
*
* Note: ordered by property ID.
*
* ---STAGE 6 - PROPERTIES---
* Format specifiers & placeholders:
* "%d|%d" - "nextavailablepropertyidmaineco|nextavailablepropertyidtesteco"
*
* The byte order is important, and we assume:
* SHA256("abc") = "ad1500f261ff10b49c7a1796a36103b02322ae5dde404141eacf018fbf1678ba"
*
*/
uint256 GetConsensusHash()
{
// allocate and init a SHA256_CTX
SHA256_CTX shaCtx;
SHA256_Init(&shaCtx);
LOCK(cs_tally);
if (msc_debug_consensus_hash) PrintToLog("Beginning generation of current consensus hash...\n");
// Balances - loop through the tally map, updating the sha context with the data from each balance and tally type
// Placeholders: "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
for (std::map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it) {
const std::string& address = my_it->first;
CMPTally& tally = my_it->second;
tally.init();
uint32_t propertyId = 0;
while (0 != (propertyId = (tally.next()))) {
int64_t balance = tally.getMoney(propertyId, BALANCE);
int64_t sellOfferReserve = tally.getMoney(propertyId, SELLOFFER_RESERVE);
int64_t acceptReserve = tally.getMoney(propertyId, ACCEPT_RESERVE);
int64_t metaDExReserve = tally.getMoney(propertyId, METADEX_RESERVE);
// skip this entry if all balances are empty
if (!balance && !sellOfferReserve && !acceptReserve && !metaDExReserve) continue;
std::string dataStr = strprintf("%s|%d|%d|%d|%d|%d",
address, propertyId, balance, sellOfferReserve, acceptReserve, metaDExReserve);
if (msc_debug_consensus_hash) PrintToLog("Adding balance data to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
}
// DEx sell offers - loop through the DEx and add each sell offer to the consensus hash (ordered by txid)
// Placeholders: "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit"
std::vector<std::pair<uint256, std::string> > vecDExOffers;
for (OfferMap::iterator it = my_offers.begin(); it != my_offers.end(); ++it) {
const CMPOffer& selloffer = it->second;
const std::string& sellCombo = it->first;
uint32_t propertyId = selloffer.getProperty();
std::string seller = sellCombo.substr(0, sellCombo.size() - 2);
std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d",
selloffer.getHash().GetHex(), seller, propertyId, selloffer.getOfferAmountOriginal(),
selloffer.getBTCDesiredOriginal(), selloffer.getMinFee(), selloffer.getBlockTimeLimit());
vecDExOffers.push_back(std::make_pair(selloffer.getHash(), dataStr));
}
std::sort (vecDExOffers.begin(), vecDExOffers.end());
for (std::vector<std::pair<uint256, std::string> >::iterator it = vecDExOffers.begin(); it != vecDExOffers.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding DEx offer data to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// DEx accepts - loop through the accepts map and add each accept to the consensus hash (ordered by matchedtxid then buyer)
// Placeholders: "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock"
std::vector<std::pair<std::string, std::string> > vecAccepts;
for (AcceptMap::const_iterator it = my_accepts.begin(); it != my_accepts.end(); ++it) {
const CMPAccept& accept = it->second;
const std::string& acceptCombo = it->first;
std::string buyer = acceptCombo.substr((acceptCombo.find("+") + 1), (acceptCombo.size()-(acceptCombo.find("+") + 1)));
std::string dataStr = strprintf("%s|%s|%d|%d|%d",
accept.getHash().GetHex(), buyer, accept.getAcceptAmount(), accept.getAcceptAmountRemaining(), accept.getAcceptBlock());
std::string sortKey = strprintf("%s-%s", accept.getHash().GetHex(), buyer);
vecAccepts.push_back(std::make_pair(sortKey, dataStr));
}
std::sort (vecAccepts.begin(), vecAccepts.end());
for (std::vector<std::pair<std::string, std::string> >::iterator it = vecAccepts.begin(); it != vecAccepts.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding DEx accept to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// MetaDEx trades - loop through the MetaDEx maps and add each open trade to the consensus hash (ordered by txid)
// Placeholders: "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining"
std::vector<std::pair<uint256, std::string> > vecMetaDExTrades;
for (md_PropertiesMap::const_iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
const md_PricesMap& prices = my_it->second;
for (md_PricesMap::const_iterator it = prices.begin(); it != prices.end(); ++it) {
const md_Set& indexes = it->second;
for (md_Set::const_iterator it = indexes.begin(); it != indexes.end(); ++it) {
const CMPMetaDEx& obj = *it;
std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d",
obj.getHash().GetHex(), obj.getAddr(), obj.getProperty(), obj.getAmountForSale(),
obj.getDesProperty(), obj.getAmountDesired(), obj.getAmountRemaining());
vecMetaDExTrades.push_back(std::make_pair(obj.getHash(), dataStr));
}
}
}
std::sort (vecMetaDExTrades.begin(), vecMetaDExTrades.end());
for (std::vector<std::pair<uint256, std::string> >::iterator it = vecMetaDExTrades.begin(); it != vecMetaDExTrades.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding MetaDEx trade data to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// Crowdsales - loop through open crowdsales and add to the consensus hash (ordered by property ID)
// Note: the variables of the crowdsale (amount, bonus etc) are not part of the crowdsale map and not included here to
// avoid additionalal loading of SP entries from the database
// Placeholders: "propertyid|propertyiddesired|deadline|usertokens|issuertokens"
std::vector<std::pair<uint32_t, std::string> > vecCrowds;
for (CrowdMap::const_iterator it = my_crowds.begin(); it != my_crowds.end(); ++it) {
const CMPCrowd& crowd = it->second;
uint32_t propertyId = crowd.getPropertyId();
std::string dataStr = strprintf("%d|%d|%d|%d|%d",
crowd.getPropertyId(), crowd.getCurrDes(), crowd.getDeadline(), crowd.getUserCreated(), crowd.getIssuerCreated());
vecCrowds.push_back(std::make_pair(propertyId, dataStr));
}
std::sort (vecCrowds.begin(), vecCrowds.end());
for (std::vector<std::pair<uint32_t, std::string> >::iterator it = vecCrowds.begin(); it != vecCrowds.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding Crowdsale entry to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// Properties - add the next available property ID in both the main and test ecosystems
// Placeholders: "nextavailablepropertyidmaineco|nextavailablepropertyidtesteco"
std::string dataStr = strprintf("%d|%d", _my_sps->peekNextSPID(1), _my_sps->peekNextSPID(2));
if (msc_debug_consensus_hash) PrintToLog("Adding property to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
// extract the final result and return the hash
uint256 consensusHash;
SHA256_Final((unsigned char*)&consensusHash, &shaCtx);
if (msc_debug_consensus_hash) PrintToLog("Finished generation of consensus hash. Result: %s\n", consensusHash.GetHex());
return consensusHash;
}
} // namespace mastercore
<|endoftext|> |
<commit_before>// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP
#define OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP
#include "openMVG/image/image_container.hpp"
#include "openMVG/image/pixel_types.hpp"
namespace openMVG {
enum Format {
Pnm, Png, Jpg, Unknown
};
Format GetFormat(const char *c);
/// Try to load the given file in the image<T> openMVG image.
template<typename T>
int ReadImage(const char *, Image<T> *);
/// Open an png image with unsigned char as memory target.
/// The memory point must be null as input.
int ReadImage(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPng(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPngStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);
template<typename T>
int WriteImage(const char *, const Image<T>&);
int WriteImage(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePng(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePngStream(FILE *, const std::vector<unsigned char>& array, int w, int h, int depth);
template<typename T>
int WriteJpg(const char *, const Image<T>&, int quality=90);
int WriteJpg(const char *, const std::vector<unsigned char>& array, int w, int h, int depth, int quality=90);
int WriteJpgStream(FILE *, const std::vector<unsigned char>& array, int w, int h, int depth, int quality=90);
/// Open a jpg image with unsigned char as memory target.
/// The memory point must be null as input.
int ReadJpg(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadJpgStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPnm(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPnmStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int WritePnm(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePnmStream(FILE *, const std::vector<unsigned char>& array, int w, int h, int depth);
template<>
inline int ReadImage(const char * path, Image<unsigned char> * im)
{
std::vector<unsigned char> ptr;
int w, h, depth;
int res = ReadImage(path, &ptr, &w, &h, &depth);
if (res == 1 && depth == 1) {
//convert raw array to Image
(*im) = Eigen::Map<Image<unsigned char>::Base>(&ptr[0], h, w);
}
else
if (res == 1 && depth == 3) {
//-- Must convert RGB to gray
RGBColor * ptrCol = (RGBColor*) &ptr[0];
Image<RGBColor> rgbColIm;
rgbColIm = Eigen::Map<Image<RGBColor>::Base>(ptrCol, h, w);
//convert RGB to gray
ConvertPixelType(rgbColIm, im);
}
else
if (res == 1 && depth == 4) {
//-- Must convert RGBA to gray
RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
Image<RGBAColor> rgbaColIm;
rgbaColIm = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
//convert RGBA to gray
ConvertPixelType(rgbaColIm, im);
}
else if (depth!=1)
return 0;
return res;
}
template<>
inline int ReadImage(const char * path, Image<RGBColor> * im)
{
std::vector<unsigned char> ptr;
int w, h, depth;
int res = ReadImage(path, &ptr, &w, &h, &depth);
if (res == 1 && depth == 3) {
RGBColor * ptrCol = (RGBColor*) &ptr[0];
//convert raw array to Image
(*im) = Eigen::Map<Image<RGBColor>::Base>(ptrCol, h, w);
}
if (res == 1 && depth == 4) {
//-- Must convert RGBA to RGB
RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
Image<RGBAColor> rgbaColIm;
rgbaColIm = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
//convert RGBA to RGB
ConvertPixelType(rgbaColIm, im);
}
else
return 0;
return res;
}
template<>
inline int ReadImage(const char * path, Image<RGBAColor> * im)
{
std::vector<unsigned char> ptr;
int w, h, depth;
int res = ReadImage(path, &ptr, &w, &h, &depth);
if (depth !=4) return 0;
if (res == 1) {
RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
//convert raw array to Image
(*im) = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
}
return res;
}
//--------
//-- Image Writing
//--------
/// Write image to disk, support only unsigned char based type (gray, rgb, rgba)
template<typename T>
int WriteImage(const char * filename, const Image<T>& im)
{
const unsigned char * ptr = (unsigned char*)(im.GetMat().data());
int depth = sizeof( T ) / sizeof(unsigned char);
std::vector<unsigned char> array( ptr , ptr + im.Width()*im.Height()*depth );
int w = im.Width(), h = im.Height();
return WriteImage(filename, array, w, h, depth);
}
template<typename T>
int WriteJpg(const char * filename, const Image<T>& im, int quality)
{
const unsigned char * ptr = (unsigned char*)(im.GetMat().data());
const int w = im.Width(), h = im.Height();
const int depth = sizeof( T ) / sizeof(unsigned char);
std::vector<unsigned char> array( ptr , ptr + w*h*depth );
return WriteJpg(filename, array, w, h, depth, quality);
}
} // namespace openMVG
#endif // OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP
<commit_msg>Fix if else condition when reading RGB image. #121<commit_after>// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP
#define OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP
#include "openMVG/image/image_container.hpp"
#include "openMVG/image/pixel_types.hpp"
namespace openMVG {
enum Format {
Pnm, Png, Jpg, Unknown
};
Format GetFormat(const char *c);
/// Try to load the given file in the image<T> openMVG image.
template<typename T>
int ReadImage(const char *, Image<T> *);
/// Open an png image with unsigned char as memory target.
/// The memory point must be null as input.
int ReadImage(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPng(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPngStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);
template<typename T>
int WriteImage(const char *, const Image<T>&);
int WriteImage(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePng(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePngStream(FILE *, const std::vector<unsigned char>& array, int w, int h, int depth);
template<typename T>
int WriteJpg(const char *, const Image<T>&, int quality=90);
int WriteJpg(const char *, const std::vector<unsigned char>& array, int w, int h, int depth, int quality=90);
int WriteJpgStream(FILE *, const std::vector<unsigned char>& array, int w, int h, int depth, int quality=90);
/// Open a jpg image with unsigned char as memory target.
/// The memory point must be null as input.
int ReadJpg(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadJpgStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPnm(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPnmStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int WritePnm(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePnmStream(FILE *, const std::vector<unsigned char>& array, int w, int h, int depth);
template<>
inline int ReadImage(const char * path, Image<unsigned char> * im)
{
std::vector<unsigned char> ptr;
int w, h, depth;
int res = ReadImage(path, &ptr, &w, &h, &depth);
if (res == 1 && depth == 1) {
//convert raw array to Image
(*im) = Eigen::Map<Image<unsigned char>::Base>(&ptr[0], h, w);
}
else
if (res == 1 && depth == 3) {
//-- Must convert RGB to gray
RGBColor * ptrCol = (RGBColor*) &ptr[0];
Image<RGBColor> rgbColIm;
rgbColIm = Eigen::Map<Image<RGBColor>::Base>(ptrCol, h, w);
//convert RGB to gray
ConvertPixelType(rgbColIm, im);
}
else
if (res == 1 && depth == 4) {
//-- Must convert RGBA to gray
RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
Image<RGBAColor> rgbaColIm;
rgbaColIm = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
//convert RGBA to gray
ConvertPixelType(rgbaColIm, im);
}
else if (depth!=1)
return 0;
return res;
}
template<>
inline int ReadImage(const char * path, Image<RGBColor> * im)
{
std::vector<unsigned char> ptr;
int w, h, depth;
int res = ReadImage(path, &ptr, &w, &h, &depth);
if (res == 1 && depth == 3) {
RGBColor * ptrCol = (RGBColor*) &ptr[0];
//convert raw array to Image
(*im) = Eigen::Map<Image<RGBColor>::Base>(ptrCol, h, w);
}
else
if (res == 1 && depth == 4) {
//-- Must convert RGBA to RGB
RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
Image<RGBAColor> rgbaColIm;
rgbaColIm = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
//convert RGBA to RGB
ConvertPixelType(rgbaColIm, im);
}
else
return 0;
return res;
}
template<>
inline int ReadImage(const char * path, Image<RGBAColor> * im)
{
std::vector<unsigned char> ptr;
int w, h, depth;
int res = ReadImage(path, &ptr, &w, &h, &depth);
if (depth !=4) return 0;
if (res == 1) {
RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
//convert raw array to Image
(*im) = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
}
return res;
}
//--------
//-- Image Writing
//--------
/// Write image to disk, support only unsigned char based type (gray, rgb, rgba)
template<typename T>
int WriteImage(const char * filename, const Image<T>& im)
{
const unsigned char * ptr = (unsigned char*)(im.GetMat().data());
int depth = sizeof( T ) / sizeof(unsigned char);
std::vector<unsigned char> array( ptr , ptr + im.Width()*im.Height()*depth );
int w = im.Width(), h = im.Height();
return WriteImage(filename, array, w, h, depth);
}
template<typename T>
int WriteJpg(const char * filename, const Image<T>& im, int quality)
{
const unsigned char * ptr = (unsigned char*)(im.GetMat().data());
const int w = im.Width(), h = im.Height();
const int depth = sizeof( T ) / sizeof(unsigned char);
std::vector<unsigned char> array( ptr , ptr + w*h*depth );
return WriteJpg(filename, array, w, h, depth, quality);
}
} // namespace openMVG
#endif // OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#define FLEXIBLE_DiffusionShapeFunction_CPP
#include "../initFlexible.h"
#include "../shapeFunction/DiffusionShapeFunction.h"
#include <sofa/core/ObjectFactory.h>
namespace sofa
{
namespace component
{
namespace shapefunction
{
using namespace defaulttype;
using namespace core::behavior;
template<class ShapeFunctionTypes,class ImageTypes>
const typename DiffusionShapeFunction<ShapeFunctionTypes,ImageTypes>::DistT DiffusionShapeFunction<ShapeFunctionTypes,ImageTypes>::MAXTEMP = (DistT)1.0;
SOFA_DECL_CLASS(DiffusionShapeFunction)
// Register in the Factory
int DiffusionShapeFunctionClass = core::RegisterObject("Computes shape functions based on diffusion in images")
.add< DiffusionShapeFunction<ShapeFunction,ImageUC> >(true)
.add< DiffusionShapeFunction<ShapeFunction,ImageD> >()
;
template class SOFA_Flexible_API DiffusionShapeFunction<ShapeFunction,ImageUC>;
template class SOFA_Flexible_API DiffusionShapeFunction<ShapeFunction,ImageD>;
}
}
}
<commit_msg>Flexible: add missing (I think) SOFA_Flexible_API<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#define FLEXIBLE_DiffusionShapeFunction_CPP
#include "../initFlexible.h"
#include "../shapeFunction/DiffusionShapeFunction.h"
#include <sofa/core/ObjectFactory.h>
namespace sofa
{
namespace component
{
namespace shapefunction
{
using namespace defaulttype;
using namespace core::behavior;
template<class ShapeFunctionTypes,class ImageTypes>
SOFA_Flexible_API const typename DiffusionShapeFunction<ShapeFunctionTypes,ImageTypes>::DistT DiffusionShapeFunction<ShapeFunctionTypes,ImageTypes>::MAXTEMP = (DistT)1.0;
SOFA_DECL_CLASS(DiffusionShapeFunction)
// Register in the Factory
int DiffusionShapeFunctionClass = core::RegisterObject("Computes shape functions based on diffusion in images")
.add< DiffusionShapeFunction<ShapeFunction,ImageUC> >(true)
.add< DiffusionShapeFunction<ShapeFunction,ImageD> >()
;
template class SOFA_Flexible_API DiffusionShapeFunction<ShapeFunction,ImageUC>;
template class SOFA_Flexible_API DiffusionShapeFunction<ShapeFunction,ImageD>;
}
}
}
<|endoftext|> |
<commit_before>#include "FltFile.h"
#include "Registry.h"
#include "Record.h"
#include "RecordVisitor.h"
#include "ExternalRecord.h"
#include "flt2osg.h" // ConvertFromFLT
#include "Input.h"
#include <osg/Node>
#include <osg/NodeVisitor>
#include <osg/Notify>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgSim/GeographicLocation>
#include <string>
using namespace flt;
FltFile::FltFile(
ColorPool* pColorPool,
TexturePool* pTexturePool,
MaterialPool* pMaterialPool,
LtPtAppearancePool* pLtPtAppearancePool,
LtPtAnimationPool* pLtPtAnimationPool,
osgDB::ReaderWriter::Options* options)
{
_useTextureAlphaForTransparancyBinning = true;
_doUnitsConversion = true;
_desiredUnits = ConvertToMeters;
if (pColorPool)
{
// use external color palette, ignore internal
_useInternalColorPalette = false;
setColorPool( pColorPool );
}
else
{
// use internal color palette
_useInternalColorPalette = true;
setColorPool( new ColorPool );
}
if (pTexturePool)
{
// use external texture palette, ignore internal
_useInternalTexturePalette = false;
setTexturePool( pTexturePool );
}
else
{
// use internal texture palette
_useInternalTexturePalette = true;
setTexturePool( new TexturePool );
}
if (pMaterialPool)
{
// use external material palette, ignore internal
_useInternalMaterialPalette = false;
setMaterialPool( pMaterialPool );
}
else
{
// use internal material palette
_useInternalMaterialPalette = true;
setMaterialPool( new MaterialPool );
}
if (pLtPtAppearancePool && pLtPtAnimationPool) // Can only be non-NULL if parent is 15.8.
{
// use external light point appearance and animation palettes, ignore internal
_useInternalLtPtPalettes = false;
setLtPtAppearancePool( pLtPtAppearancePool );
setLtPtAnimationPool( pLtPtAnimationPool );
}
else
{
// If they aren't both set, then they must both be NULL.
assert( (pLtPtAppearancePool==NULL) && (pLtPtAppearancePool==NULL) );
// use internal light point palettes
_useInternalLtPtPalettes = true;
setLtPtAppearancePool( new LtPtAppearancePool );
setLtPtAnimationPool( new LtPtAnimationPool );
}
// no support for external light palettes
setLightPool( new LightPool );
// instances are always internally defined
setInstancePool( new InstancePool );
_options = options;
}
osg::Object* FltFile::readObject(const std::string& fileName)
{
return readNode(fileName);
}
osg::Node* FltFile::readNode(const std::string& fileName)
{
_directory = osgDB::getFilePath(fileName);
if (readModel(fileName))
{
// Convert record tree to osg scene graph
osg::Node* model = convert();
if (model)
{
// Store model origin in returned Node userData.
osg::ref_ptr<osgSim::GeographicLocation> loc = new osgSim::GeographicLocation;
double lat, lon;
getOrigin( lat, lon );
loc->set( lat, lon );
model->setUserData( loc.get() );
osg::notify(osg::INFO)<<"FltFile::readNode("<<fileName<<") lat="<<lat<<" lon="<<lon<<std::endl;
return model;
}
}
return NULL;
}
osg::Group* FltFile::convert()
{
ConvertFromFLT visit;
visit.setUseTextureAlphaForTransparancyBinning(getUseTextureAlphaForTransparancyBinning());
visit.setDoUnitsConversion(getDoUnitsConversion());
return visit.convert(getHeaderRecord());
}
// Read flight model (include externals)
bool FltFile::readModel(const std::string& fileName)
{
if (readFile(fileName))
{
readExternals();
return getHeaderRecord() ? true : false;
}
return false;
}
bool FltFile::readFile(const std::string& fileName)
{
// havn't found file, look in OSGFILEPATH
std::string foundFileName = osgDB::findDataFile(fileName, _options.get());
if (foundFileName.empty()) return false;
FileInput fin;
if (!fin.open(foundFileName)) return false;
Record* pRec = fin.readCreateRecord(this);
if (pRec == NULL)
{
osg::notify(osg::WARN) << "File not found " << fileName << std::endl;
return false;
}
_headerRecord = (HeaderRecord*)pRec;
if (pRec->isPrimaryNode()) // Header
pRec->readLocalData(fin);// Read rest of file
fin.close();
return true;
}
#define REGISTER_FLT 1
// This class was originally scoped within FltFile::readExternals() function.
// Irix 7.3 compilers hork on this.
class ReadExternal : public RecordVisitor
{
public:
ReadExternal(FltFile* fltFile)
{
_pFltFile = fltFile;
setTraverseMode(RecordVisitor::TRAVERSE_ALL_CHILDREN);
}
virtual void apply(ExternalRecord& rec)
{
SExternalReference* pSExternal = (SExternalReference*)rec.getData();
if (pSExternal)
{
FltFile* pExternalFltFile = NULL;
ColorPool* pColorPool = NULL;
TexturePool* pTexturePool = NULL;
MaterialPool* pMaterialPool = NULL;
LtPtAppearancePool* pLtPtAppearancePool = NULL;
LtPtAnimationPool* pLtPtAnimationPool = NULL;
std::string filename( rec.getFilename() );
osg::notify(osg::INFO) << "External=" << filename << std::endl;
if (rec.getFlightVersion() > 13)
{
if (!(pSExternal->dwFlags & ExternalRecord::COLOR_PALETTE_OVERRIDE))
pColorPool = _pFltFile->getColorPool();
if (!(pSExternal->dwFlags & ExternalRecord::TEXTURE_PALETTE_OVERRIDE))
pTexturePool = _pFltFile->getTexturePool();
if (!(pSExternal->dwFlags & ExternalRecord::MATERIAL_PALETTE_OVERRIDE))
pMaterialPool = _pFltFile->getMaterialPool();
if (rec.getFlightVersion() >= 1580)
{
if (!(pSExternal->dwFlags & ExternalRecord::LIGHT_POINT_PALETTE_OVERRIDE))
{
pLtPtAppearancePool = _pFltFile->getLtPtAppearancePool();
pLtPtAnimationPool = _pFltFile->getLtPtAnimationPool();
}
}
}
#if REGISTER_FLT
bool registerFLT = true;
#else
bool registerFLT = false;
#endif
pExternalFltFile = registerFLT ? Registry::instance()->getFltFile(filename) : NULL;
if (pExternalFltFile == NULL)
{
osg::ref_ptr<osgDB::ReaderWriter::Options> options =
_pFltFile->getOptions() ? _pFltFile->getOptions() :
new osgDB::ReaderWriter::Options;
//Path for Nested external references
osgDB::FilePathList& fpl = options->getDatabasePathList();
const std::string& filePath = osgDB::getFilePath(filename);
std::string pushAndPopPath;
//If absolute path
if( (filePath.length()>0 && filePath.find_first_of("/\\")==0) ||
(filePath.length()>2 && filePath.substr(1,1)==":" && filePath.find_first_of("/\\")==2) )
{
pushAndPopPath = filePath;
}
else
{
pushAndPopPath = (fpl.empty() | fpl.back().empty() ? "." : fpl.back()) + "/" + filePath;
}
char optionsString[256];
sprintf(optionsString,"FLT_VER %d",rec.getFlightVersion());
options->setOptionString(optionsString);
//osg::notify(osg::NOTICE)<<"Create local path"<<pushAndPopPath<<std::endl;
fpl.push_back(pushAndPopPath);
pExternalFltFile = new FltFile( pColorPool, pTexturePool, pMaterialPool,
pLtPtAppearancePool, pLtPtAnimationPool, options.get() );
if (registerFLT)
{
Registry::instance()->addFltFile(filename, pExternalFltFile);
}
pExternalFltFile->readModel(filename);
fpl.pop_back();
}
rec.setExternal(pExternalFltFile);
}
}
public:
FltFile* _pFltFile;
};
void FltFile::readExternals()
{
ReadExternal visitor(this);
_headerRecord->accept(visitor);
}
int FltFile::getFlightVersion() const
{
if (_headerRecord.get())
{
SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();
if (pSHeader)
return pSHeader->diFormatRevLev;
}
return 0;
}
void FltFile::getOrigin( double& latitude, double& longitude ) const
{
if (_headerRecord.get())
{
SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();
if (pSHeader)
{
latitude = pSHeader->Origin.x();
longitude = pSHeader->Origin.y();
}
}
}
std::string FltFile::getDesiredUnitsString() const
{
switch (_desiredUnits)
{
case ConvertToMeters:
return "ConvertToMeters";
break;
case ConvertToKilometers:
return "ConvertToKilometers";
break;
case ConvertToFeet:
return "ConvertToFeet";
break;
case ConvertToInches:
return "ConvertToInches";
break;
case ConvertToNauticalMiles:
return "ConvertToNauticalMiles";
break;
default:
return "Invalid";
break;
}
}
<commit_msg>From Alberto Farre, nested files bug fix.<commit_after>#include "FltFile.h"
#include "Registry.h"
#include "Record.h"
#include "RecordVisitor.h"
#include "ExternalRecord.h"
#include "flt2osg.h" // ConvertFromFLT
#include "Input.h"
#include <osg/Node>
#include <osg/NodeVisitor>
#include <osg/Notify>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgSim/GeographicLocation>
#include <string>
using namespace flt;
FltFile::FltFile(
ColorPool* pColorPool,
TexturePool* pTexturePool,
MaterialPool* pMaterialPool,
LtPtAppearancePool* pLtPtAppearancePool,
LtPtAnimationPool* pLtPtAnimationPool,
osgDB::ReaderWriter::Options* options)
{
_useTextureAlphaForTransparancyBinning = true;
_doUnitsConversion = true;
_desiredUnits = ConvertToMeters;
if (pColorPool)
{
// use external color palette, ignore internal
_useInternalColorPalette = false;
setColorPool( pColorPool );
}
else
{
// use internal color palette
_useInternalColorPalette = true;
setColorPool( new ColorPool );
}
if (pTexturePool)
{
// use external texture palette, ignore internal
_useInternalTexturePalette = false;
setTexturePool( pTexturePool );
}
else
{
// use internal texture palette
_useInternalTexturePalette = true;
setTexturePool( new TexturePool );
}
if (pMaterialPool)
{
// use external material palette, ignore internal
_useInternalMaterialPalette = false;
setMaterialPool( pMaterialPool );
}
else
{
// use internal material palette
_useInternalMaterialPalette = true;
setMaterialPool( new MaterialPool );
}
if (pLtPtAppearancePool && pLtPtAnimationPool) // Can only be non-NULL if parent is 15.8.
{
// use external light point appearance and animation palettes, ignore internal
_useInternalLtPtPalettes = false;
setLtPtAppearancePool( pLtPtAppearancePool );
setLtPtAnimationPool( pLtPtAnimationPool );
}
else
{
// If they aren't both set, then they must both be NULL.
assert( (pLtPtAppearancePool==NULL) && (pLtPtAppearancePool==NULL) );
// use internal light point palettes
_useInternalLtPtPalettes = true;
setLtPtAppearancePool( new LtPtAppearancePool );
setLtPtAnimationPool( new LtPtAnimationPool );
}
// no support for external light palettes
setLightPool( new LightPool );
// instances are always internally defined
setInstancePool( new InstancePool );
_options = options;
}
osg::Object* FltFile::readObject(const std::string& fileName)
{
return readNode(fileName);
}
osg::Node* FltFile::readNode(const std::string& fileName)
{
_directory = osgDB::getFilePath(fileName);
if (readModel(fileName))
{
// Convert record tree to osg scene graph
osg::Node* model = convert();
if (model)
{
// Store model origin in returned Node userData.
osg::ref_ptr<osgSim::GeographicLocation> loc = new osgSim::GeographicLocation;
double lat, lon;
getOrigin( lat, lon );
loc->set( lat, lon );
model->setUserData( loc.get() );
osg::notify(osg::INFO)<<"FltFile::readNode("<<fileName<<") lat="<<lat<<" lon="<<lon<<std::endl;
return model;
}
}
return NULL;
}
osg::Group* FltFile::convert()
{
ConvertFromFLT visit;
visit.setUseTextureAlphaForTransparancyBinning(getUseTextureAlphaForTransparancyBinning());
visit.setDoUnitsConversion(getDoUnitsConversion());
return visit.convert(getHeaderRecord());
}
// Read flight model (include externals)
bool FltFile::readModel(const std::string& fileName)
{
if (readFile(fileName))
{
readExternals();
return getHeaderRecord() ? true : false;
}
return false;
}
bool FltFile::readFile(const std::string& fileName)
{
// havn't found file, look in OSGFILEPATH
std::string foundFileName = osgDB::findDataFile(fileName, _options.get());
if (foundFileName.empty()) return false;
FileInput fin;
if (!fin.open(foundFileName)) return false;
Record* pRec = fin.readCreateRecord(this);
if (pRec == NULL)
{
osg::notify(osg::WARN) << "File not found " << fileName << std::endl;
return false;
}
_headerRecord = (HeaderRecord*)pRec;
if (pRec->isPrimaryNode()) // Header
pRec->readLocalData(fin);// Read rest of file
fin.close();
return true;
}
#define REGISTER_FLT 1
// This class was originally scoped within FltFile::readExternals() function.
// Irix 7.3 compilers hork on this.
class ReadExternal : public RecordVisitor
{
public:
ReadExternal(FltFile* fltFile)
{
_pFltFile = fltFile;
setTraverseMode(RecordVisitor::TRAVERSE_ALL_CHILDREN);
}
virtual void apply(ExternalRecord& rec)
{
SExternalReference* pSExternal = (SExternalReference*)rec.getData();
if (pSExternal)
{
FltFile* pExternalFltFile = NULL;
ColorPool* pColorPool = NULL;
TexturePool* pTexturePool = NULL;
MaterialPool* pMaterialPool = NULL;
LtPtAppearancePool* pLtPtAppearancePool = NULL;
LtPtAnimationPool* pLtPtAnimationPool = NULL;
std::string filename( rec.getFilename() );
osg::notify(osg::INFO) << "External=" << filename << std::endl;
if (rec.getFlightVersion() > 13)
{
if (!(pSExternal->dwFlags & ExternalRecord::COLOR_PALETTE_OVERRIDE))
pColorPool = _pFltFile->getColorPool();
if (!(pSExternal->dwFlags & ExternalRecord::TEXTURE_PALETTE_OVERRIDE))
pTexturePool = _pFltFile->getTexturePool();
if (!(pSExternal->dwFlags & ExternalRecord::MATERIAL_PALETTE_OVERRIDE))
pMaterialPool = _pFltFile->getMaterialPool();
if (rec.getFlightVersion() >= 1580)
{
if (!(pSExternal->dwFlags & ExternalRecord::LIGHT_POINT_PALETTE_OVERRIDE))
{
pLtPtAppearancePool = _pFltFile->getLtPtAppearancePool();
pLtPtAnimationPool = _pFltFile->getLtPtAnimationPool();
}
}
}
#if REGISTER_FLT
bool registerFLT = true;
#else
bool registerFLT = false;
#endif
pExternalFltFile = registerFLT ? Registry::instance()->getFltFile(filename) : NULL;
if (pExternalFltFile == NULL)
{
osg::ref_ptr<osgDB::ReaderWriter::Options> options =
_pFltFile->getOptions() ? _pFltFile->getOptions() :
new osgDB::ReaderWriter::Options;
//Path for Nested external references
osgDB::FilePathList& fpl = options->getDatabasePathList();
const std::string& filePath = osgDB::getFilePath(filename);
std::string pushAndPopPath;
//If absolute path
if( (filePath.length()>0 && filePath.find_first_of("/\\")==0) ||
(filePath.length()>2 && filePath.substr(1,1)==":" && filePath.find_first_of("/\\")==2) )
{
pushAndPopPath = filePath;
}
else
{
pushAndPopPath = (fpl.empty() | fpl.back().empty() ? "." : fpl.back()) + "/" + filePath;
}
char optionsString[256];
sprintf(optionsString,"FLT_VER %d",rec.getFlightVersion());
options->setOptionString(optionsString);
//osg::notify(osg::NOTICE)<<"Create local path"<<pushAndPopPath<<std::endl;
fpl.push_back(pushAndPopPath);
pExternalFltFile = new FltFile( pColorPool, pTexturePool, pMaterialPool,
pLtPtAppearancePool, pLtPtAnimationPool, options.get() );
if (registerFLT)
{
Registry::instance()->addFltFile(filename, pExternalFltFile);
}
pExternalFltFile->readModel(filename);
}
rec.setExternal(pExternalFltFile);
}
}
public:
FltFile* _pFltFile;
};
void FltFile::readExternals()
{
ReadExternal visitor(this);
_headerRecord->accept(visitor);
}
int FltFile::getFlightVersion() const
{
if (_headerRecord.get())
{
SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();
if (pSHeader)
return pSHeader->diFormatRevLev;
}
return 0;
}
void FltFile::getOrigin( double& latitude, double& longitude ) const
{
if (_headerRecord.get())
{
SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();
if (pSHeader)
{
latitude = pSHeader->Origin.x();
longitude = pSHeader->Origin.y();
}
}
}
std::string FltFile::getDesiredUnitsString() const
{
switch (_desiredUnits)
{
case ConvertToMeters:
return "ConvertToMeters";
break;
case ConvertToKilometers:
return "ConvertToKilometers";
break;
case ConvertToFeet:
return "ConvertToFeet";
break;
case ConvertToInches:
return "ConvertToInches";
break;
case ConvertToNauticalMiles:
return "ConvertToNauticalMiles";
break;
default:
return "Invalid";
break;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2013 Martin Klapetek <mklapetek@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "persons-presence-model.h"
#include "persons-model.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>
#include <KTp/contact-factory.h>
#include <KTp/global-contact-manager.h>
#include <KDebug>
PersonsPresenceModel::PersonsPresenceModel(QObject *parent)
: QIdentityProxyModel(parent)
{
Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
Tp::Features() << Tp::Account::FeatureCore
<< Tp::Account::FeatureCapabilities
<< Tp::Account::FeatureProtocolInfo
<< Tp::Account::FeatureProfile);
Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),
Tp::Features() << Tp::Connection::FeatureCore
<< Tp::Connection::FeatureRoster
<< Tp::Connection::FeatureSelfContact);
Tp::ContactFactoryPtr contactFactory = KTp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias
<< Tp::Contact::FeatureSimplePresence
<< Tp::Contact::FeatureCapabilities
<< Tp::Contact::FeatureClientTypes);
Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());
m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),
accountFactory,
connectionFactory,
channelFactory,
contactFactory);
connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}
PersonsPresenceModel::~PersonsPresenceModel()
{
}
void PersonsPresenceModel::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
kWarning() << "Failed to initialize AccountManager:" << op->errorName();
kWarning() << op->errorMessage();
return;
}
kDebug() << "Account manager ready";
m_contactManager = new KTp::GlobalContactManager(m_accountManager, this);
connect(m_contactManager, SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),
this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));
onAllKnownContactsChanged(m_contactManager->allKnownContacts(), Tp::Contacts());
}
void PersonsPresenceModel::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)
{
if (!m_presences.isEmpty()) {
Q_FOREACH (const Tp::ContactPtr &contact, contactsRemoved) {
m_presences.remove(contact->id());
}
}
Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {
m_presences.insert(contact->id(), contact);
connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)),
this, SLOT(onContactChanged()));
connect(contact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),
this, SLOT(onContactChanged()));
//TODO: add other stuff here etc
QModelIndex index = qobject_cast<PersonsModel*>(sourceModel())->findRecursively(PersonsModel::IMRole, contact->id());
Q_EMIT dataChanged(index, index);
}
}
void PersonsPresenceModel::onContactChanged()
{
QString id = qobject_cast<Tp::Contact*>(sender())->id();
QModelIndex index = qobject_cast<PersonsModel*>(sourceModel())->findRecursively(PersonsModel::IMRole, id);
Q_EMIT dataChanged(index, index);
}
QVariant PersonsPresenceModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
if (role == PersonsModel::StatusRole) {
if (index.data(PersonsModel::ResourceTypeRole).toUInt() == PersonsModel::Contact) {
QString contactId = index.data(PersonsModel::IMRole).toString();
if (m_presences.keys().contains(contactId)) {
return m_presences.value(contactId)->presence().status();
} else {
return QLatin1String("unknown");
}
} else if (index.data(PersonsModel::ResourceTypeRole).toUInt() == PersonsModel::Person) {
QVariantList ret;
for (int i = 0; i < rowCount(); i++) {
QVariant value = index.child(i, 0).data(role);
if (!value.isNull()) {
ret += value;
}
}
return ret;
}
}
return QIdentityProxyModel::data(index, role);
}
<commit_msg>Return "offline" presence before we have presences ready<commit_after>/*
Copyright (C) 2013 Martin Klapetek <mklapetek@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "persons-presence-model.h"
#include "persons-model.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>
#include <KTp/contact-factory.h>
#include <KTp/global-contact-manager.h>
#include <KDebug>
PersonsPresenceModel::PersonsPresenceModel(QObject *parent)
: QIdentityProxyModel(parent)
{
Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
Tp::Features() << Tp::Account::FeatureCore
<< Tp::Account::FeatureCapabilities
<< Tp::Account::FeatureProtocolInfo
<< Tp::Account::FeatureProfile);
Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),
Tp::Features() << Tp::Connection::FeatureCore
<< Tp::Connection::FeatureRoster
<< Tp::Connection::FeatureSelfContact);
Tp::ContactFactoryPtr contactFactory = KTp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias
<< Tp::Contact::FeatureSimplePresence
<< Tp::Contact::FeatureCapabilities
<< Tp::Contact::FeatureClientTypes);
Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());
m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),
accountFactory,
connectionFactory,
channelFactory,
contactFactory);
connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}
PersonsPresenceModel::~PersonsPresenceModel()
{
}
void PersonsPresenceModel::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
kWarning() << "Failed to initialize AccountManager:" << op->errorName();
kWarning() << op->errorMessage();
return;
}
kDebug() << "Account manager ready";
m_contactManager = new KTp::GlobalContactManager(m_accountManager, this);
connect(m_contactManager, SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),
this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));
onAllKnownContactsChanged(m_contactManager->allKnownContacts(), Tp::Contacts());
}
void PersonsPresenceModel::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)
{
if (!m_presences.isEmpty()) {
Q_FOREACH (const Tp::ContactPtr &contact, contactsRemoved) {
m_presences.remove(contact->id());
}
}
Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {
m_presences.insert(contact->id(), contact);
connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)),
this, SLOT(onContactChanged()));
connect(contact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),
this, SLOT(onContactChanged()));
//TODO: add other stuff here etc
QModelIndex index = qobject_cast<PersonsModel*>(sourceModel())->findRecursively(PersonsModel::IMRole, contact->id());
Q_EMIT dataChanged(index, index);
}
}
void PersonsPresenceModel::onContactChanged()
{
QString id = qobject_cast<Tp::Contact*>(sender())->id();
QModelIndex index = qobject_cast<PersonsModel*>(sourceModel())->findRecursively(PersonsModel::IMRole, id);
Q_EMIT dataChanged(index, index);
}
QVariant PersonsPresenceModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
if (role == PersonsModel::StatusRole) {
if (index.data(PersonsModel::ResourceTypeRole).toUInt() == PersonsModel::Contact) {
QString contactId = index.data(PersonsModel::IMRole).toString();
if (m_presences.keys().contains(contactId)) {
return m_presences.value(contactId)->presence().status();
} else if (!contactId.isEmpty()) {
return QLatin1String("offline");
} else if (contactId.isEmpty()) {
return QLatin1String("unknown");
}
} else if (index.data(PersonsModel::ResourceTypeRole).toUInt() == PersonsModel::Person) {
QVariantList ret;
for (int i = 0; i < rowCount(); i++) {
QVariant value = index.child(i, 0).data(role);
if (!value.isNull()) {
ret += value;
}
}
return ret;
}
}
return QIdentityProxyModel::data(index, role);
}
<|endoftext|> |
<commit_before>#include "../include/carta.h"
#include "../include/textura.h"
#include "../include/to_string.h"
#define CARD_WIDTH 125
#define CARD_HEIGHT 164
using namespace std;
Carta::Carta(int num, SDL_Renderer* renderer){
string dir = "../textures/cards/";
int i = (num-1)/13;
this->value = num-13*i;
this->suit = 65+i;
dir.append(to_string(this->value));
dir.push_back(this->suit);
dir.append(".png");
this->gTexture = Textura(dir, renderer, 0, 0, CARD_WIDTH, CARD_HEIGHT);
}
void Carta::setPosition(int x, int y){
this->gTexture.setPosition(x, y);
}
void Carta::renderCard() {
this->gTexture.render();
}
int Carta::getValue(){
return this->value;
}
char Carta::getSuit(){
return this->suit;
}
<commit_msg>textura.h já está em carta.h<commit_after>#include "../include/carta.h"
#include "../include/to_string.h"
#define CARD_WIDTH 125
#define CARD_HEIGHT 164
using namespace std;
Carta::Carta(int num, SDL_Renderer* renderer){
string dir = "../textures/cards/";
int i = (num-1)/13;
this->value = num-13*i;
this->suit = 65+i;
dir.append(to_string(this->value));
dir.push_back(this->suit);
dir.append(".png");
this->gTexture = Textura(dir, renderer, 0, 0, CARD_WIDTH, CARD_HEIGHT);
}
void Carta::setPosition(int x, int y){
this->gTexture.setPosition(x, y);
}
void Carta::renderCard() {
this->gTexture.render();
}
int Carta::getValue(){
return this->value;
}
char Carta::getSuit(){
return this->suit;
}
<|endoftext|> |
<commit_before>#include "clustering.hpp"
Clustering::Clustering( std::vector<IndexTransition> const & vIndexTransition, double (*distance_function)(IndexTransitionCluster const &, IndexTransitionCluster const &), double eps, uint minPts):
eps{eps}, minPts{minPts}, nowClusterNumber{0}, distance_function{distance_function}
{
std::for_each(vIndexTransition.begin(), vIndexTransition.end(), [ this ]( IndexTransition const & indexTransition ){
vIndexTransitionCluster.push_back( IndexTransitionCluster( indexTransition ) );
});
std::stable_sort( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), []( IndexTransitionCluster const & p1, IndexTransitionCluster const & p2 ){
if( p1.row < p2.row )
{
return true;
}
else
{
return false;
}
});
}
uint Clustering::create_new_cluster()
{
nowClusterNumber += 1;
return nowClusterNumber;
}
uint Clustering::get_cluster_number()
{
return nowClusterNumber;
}
void Clustering::points_clustering( void (Clustering::*check_point_zone_function)(int) )
{
for( int indexX = 0; indexX < vIndexTransitionCluster.size(); ++indexX )
{
(this->*check_point_zone_function)(indexX);
}
concatenate_clusters();
remove_small_clusters_and_noise();
}
void Clustering::check_point_zone_linear( int indexX )
{
std::vector<uint> linkedClusters;
uint currentClusterNumber = 0;
IndexTransitionCluster point = vIndexTransitionCluster[indexX];
if( point.clusterNumber == 0 )
{
currentClusterNumber = create_new_cluster();
point.clusterNumber = currentClusterNumber;
}
else
{
currentClusterNumber = point.clusterNumber;
}
linkedClusters.push_back(currentClusterNumber);
double minX = point.row - eps;
double maxX = point.row + eps;
for( int i = 0; i < vIndexTransitionCluster.size(); ++i )
{
if( vIndexTransitionCluster[i].row < minX)
continue;
else
{
if( maxX < vIndexTransitionCluster[i].row )
{
break;
}
else
{
if (distance_function(point, vIndexTransitionCluster[i]) <= eps )
{
if( vIndexTransitionCluster[i].clusterNumber == 0 )
{
vIndexTransitionCluster[i].clusterNumber = currentClusterNumber;
}
else
{
linkedClusters.push_back( vIndexTransitionCluster[i].clusterNumber );
}
}
}
}
}
std::sort(linkedClusters.begin(),linkedClusters.end());
linkedClusters.erase(std::unique(linkedClusters.begin(), linkedClusters.end()), linkedClusters.end());
linkedTransform.resize(std::max(linkedClusters.back() + 1, (uint)(linkedTransform.size())), UINT32_MAX);//UINT32_MAX is one to one map (ex. if linkedTransform[2]==UINT32_MAX then cluster 2 maped to cluster2)
uint minLinkedTransformByLinkedClusters = linkedClusters.front();//only for start, could be back() or what ever
std::for_each( linkedClusters.begin(), linkedClusters.end(), [ this, &minLinkedTransformByLinkedClusters ]( uint cl){
minLinkedTransformByLinkedClusters = std::min( minLinkedTransformByLinkedClusters, linkedTransform[cl] );
});
std::for_each( linkedClusters.begin(), linkedClusters.end(), [ this, &minLinkedTransformByLinkedClusters ]( uint cl){
uint oldValue = linkedTransform[cl];
std::replace( linkedTransform.begin() + 1, linkedTransform.end(), oldValue, minLinkedTransformByLinkedClusters);// +1 reserved element [0]
});
return;
}
void Clustering::concatenate_clusters()
{
for(uint i = 0; i < linkedTransform.size(); ++i)//zeroes is one to one map (ex. if linkedTransform[2]==0 then cluster 2 maped to cluster 2)
{
if(linkedTransform[i] == UINT32_MAX)
{
linkedTransform[i] = i;
}
}
//raw cluster numbers or not
std::vector<uint> distinctClusters(linkedTransform);
std::sort(distinctClusters.begin(), distinctClusters.end());
distinctClusters.erase(std::unique(distinctClusters.begin(), distinctClusters.end()), distinctClusters.end());
std::vector<uint> transLinkedTransform(distinctClusters.back() + 1, 0);
for(int i = 0; i < distinctClusters.size(); ++i)
{
transLinkedTransform[distinctClusters[i]] = i;
}
std::for_each(linkedTransform.begin(), linkedTransform.end(), [&transLinkedTransform](auto& lt){
lt = transLinkedTransform[lt];
});
std::for_each(vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [this](auto& itc){
itc.clusterNumber = linkedTransform[ itc.clusterNumber ];
});
}
void Clustering::remove_small_clusters_and_noise()
{
auto maxClusterNumberIterator = std::max_element( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), []( IndexTransitionCluster const & itc1, IndexTransitionCluster const & itc2){
if( itc1.clusterNumber < itc2.clusterNumber )
{
return true;
}
else
{
return false;
}
});
uint maxClusterNumber = maxClusterNumberIterator->clusterNumber;
std::vector<uint>clusterOccurences(maxClusterNumber + 1, 0);
for_each( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [&clusterOccurences]( IndexTransitionCluster const & itc ){
if( itc.clusterNumber != 0 )// new itc without cluster occurrrence
{
clusterOccurences[itc.clusterNumber] += 1;
}
});
vIndexTransitionCluster.erase(std::remove_if(vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [this, &clusterOccurences](IndexTransitionCluster const & itc){//remove small clusters
if( clusterOccurences[itc.clusterNumber] < minPts )
{
return true;
}
else
{
return false;
}
}), vIndexTransitionCluster.end());
}
double Distance::distance_fast( IndexTransitionCluster const & pixelA, IndexTransitionCluster const & pixelB )
{
return abs( pixelA.row - pixelB.row ) + abs( pixelA.col - pixelB.col );
}
double Distance::distance_slow( IndexTransitionCluster const & pixelA, IndexTransitionCluster const & pixelB )
{
return sqrt( pow( ( pixelA.row - pixelB.row ), 2.0 ) + pow( ( pixelA.col - pixelB.col ), 2.0 ) );
}<commit_msg>break if linked cluster size 0<commit_after>#include "clustering.hpp"
Clustering::Clustering( std::vector<IndexTransition> const & vIndexTransition, double (*distance_function)(IndexTransitionCluster const &, IndexTransitionCluster const &), double eps, uint minPts):
eps{eps}, minPts{minPts}, nowClusterNumber{0}, distance_function{distance_function}
{
std::for_each(vIndexTransition.begin(), vIndexTransition.end(), [ this ]( IndexTransition const & indexTransition ){
vIndexTransitionCluster.push_back( IndexTransitionCluster( indexTransition ) );
});
std::stable_sort( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), []( IndexTransitionCluster const & p1, IndexTransitionCluster const & p2 ){
if( p1.row < p2.row )
{
return true;
}
else
{
return false;
}
});
}
uint Clustering::create_new_cluster()
{
nowClusterNumber += 1;
return nowClusterNumber;
}
uint Clustering::get_cluster_number()
{
return nowClusterNumber;
}
void Clustering::points_clustering( void (Clustering::*check_point_zone_function)(int) )
{
for( int indexX = 0; indexX < vIndexTransitionCluster.size(); ++indexX )
{
(this->*check_point_zone_function)(indexX);
}
if( linkedTransform.size() == 0 )
return;
concatenate_clusters();
remove_small_clusters_and_noise();
}
void Clustering::check_point_zone_linear( int indexX )
{
std::vector<uint> linkedClusters;
uint currentClusterNumber = 0;
IndexTransitionCluster point = vIndexTransitionCluster[indexX];
if( point.clusterNumber == 0 )
{
currentClusterNumber = create_new_cluster();
point.clusterNumber = currentClusterNumber;
}
else
{
currentClusterNumber = point.clusterNumber;
}
linkedClusters.push_back(currentClusterNumber);
double minX = point.row - eps;
double maxX = point.row + eps;
for( int i = 0; i < vIndexTransitionCluster.size(); ++i )
{
if( vIndexTransitionCluster[i].row < minX)
continue;
else
{
if( maxX < vIndexTransitionCluster[i].row )
{
break;
}
else
{
if (distance_function(point, vIndexTransitionCluster[i]) <= eps )
{
if( vIndexTransitionCluster[i].clusterNumber == 0 )
{
vIndexTransitionCluster[i].clusterNumber = currentClusterNumber;
}
else
{
linkedClusters.push_back( vIndexTransitionCluster[i].clusterNumber );
}
}
}
}
}
std::sort(linkedClusters.begin(),linkedClusters.end());
linkedClusters.erase(std::unique(linkedClusters.begin(), linkedClusters.end()), linkedClusters.end());
linkedTransform.resize(std::max(linkedClusters.back() + 1, (uint)(linkedTransform.size())), UINT32_MAX);//UINT32_MAX is one to one map (ex. if linkedTransform[2]==UINT32_MAX then cluster 2 maped to cluster2)
uint minLinkedTransformByLinkedClusters = linkedClusters.front();//only for start, could be back() or what ever
std::for_each( linkedClusters.begin(), linkedClusters.end(), [ this, &minLinkedTransformByLinkedClusters ]( uint cl){
minLinkedTransformByLinkedClusters = std::min( minLinkedTransformByLinkedClusters, linkedTransform[cl] );
});
std::for_each( linkedClusters.begin(), linkedClusters.end(), [ this, &minLinkedTransformByLinkedClusters ]( uint cl){
uint oldValue = linkedTransform[cl];
std::replace( linkedTransform.begin() + 1, linkedTransform.end(), oldValue, minLinkedTransformByLinkedClusters);// +1 reserved element [0]
});
return;
}
void Clustering::concatenate_clusters()
{
for(uint i = 0; i < linkedTransform.size(); ++i)//zeroes is one to one map (ex. if linkedTransform[2]==0 then cluster 2 maped to cluster 2)
{
if(linkedTransform[i] == UINT32_MAX)
{
linkedTransform[i] = i;
}
}
//raw cluster numbers or not code below
std::vector<uint> distinctClusters(linkedTransform);
std::sort(distinctClusters.begin(), distinctClusters.end());
distinctClusters.erase(std::unique(distinctClusters.begin(), distinctClusters.end()), distinctClusters.end());
std::vector<uint> transLinkedTransform(distinctClusters.back() + 1, 0);
for(int i = 0; i < distinctClusters.size(); ++i)
{
transLinkedTransform[distinctClusters[i]] = i;
}
std::for_each(linkedTransform.begin(), linkedTransform.end(), [&transLinkedTransform](auto& lt){
lt = transLinkedTransform[lt];
});
std::for_each(vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [this](auto& itc){
itc.clusterNumber = linkedTransform[ itc.clusterNumber ];
});
}
void Clustering::remove_small_clusters_and_noise()
{
auto maxClusterNumberIterator = std::max_element( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), []( IndexTransitionCluster const & itc1, IndexTransitionCluster const & itc2){
if( itc1.clusterNumber < itc2.clusterNumber )
{
return true;
}
else
{
return false;
}
});
uint maxClusterNumber = maxClusterNumberIterator->clusterNumber;
std::vector<uint>clusterOccurences(maxClusterNumber + 1, 0);
for_each( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [&clusterOccurences]( IndexTransitionCluster const & itc ){
if( itc.clusterNumber != 0 )// new itc without cluster occurrrence
{
clusterOccurences[itc.clusterNumber] += 1;
}
});
vIndexTransitionCluster.erase(std::remove_if(vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [this, &clusterOccurences](IndexTransitionCluster const & itc){//remove small clusters
if( clusterOccurences[itc.clusterNumber] < minPts )
{
return true;
}
else
{
return false;
}
}), vIndexTransitionCluster.end());
}
double Distance::distance_fast( IndexTransitionCluster const & pixelA, IndexTransitionCluster const & pixelB )
{
return abs( pixelA.row - pixelB.row ) + abs( pixelA.col - pixelB.col );
}
double Distance::distance_slow( IndexTransitionCluster const & pixelA, IndexTransitionCluster const & pixelB )
{
return sqrt( pow( ( pixelA.row - pixelB.row ), 2.0 ) + pow( ( pixelA.col - pixelB.col ), 2.0 ) );
}<|endoftext|> |
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include <bse/bsemain.hh>
#include <bse/testing.hh>
#include "bse/internal.hh"
using Bse::printerr;
typedef Bse::IntegrityCheck::TestFunc TestFunc;
// == BSE_INTEGRITY_TEST Registry ==
struct TestEntry {
TestFunc test;
const char *func;
const char *file;
int line;
TestEntry (const char *_file, int _line, const char *_func, TestFunc _test) :
test (_test), func (_func), file (_file), line (_line)
{}
};
static std::vector<TestEntry> *tests = NULL; // NOTE, this must be available for high priority early constructors
// == BSE_INTEGRITY_CHECK Activation ==
namespace Bse {
// Override Bse weak symbol to enable Bse's internal integrity tests, see bcore.hh
const bool IntegrityCheck::enabled = true;
// Registration function called for all integrity tests
void
IntegrityCheck::Test::register_test (const char *file, int line, const char *func, TestFunc test)
{
if (!tests)
tests = new std::vector<TestEntry>();
tests->push_back (TestEntry (file, line, func, test));
}
} // Bse
static int // for backtrace tests
my_compare_func (const void*, const void*)
{
BSE_BACKTRACE();
_Exit (0);
}
// == Main test program ==
static int
test_main (int argc, char *argv[])
{
if (argc >= 2 && String ("--backtrace") == argv[1])
{
char dummy_array[3] = { 1, 2, 3 };
qsort (dummy_array, 3, 1, my_compare_func);
}
else if (argc >= 2 && String ("--assert_return1") == argv[1])
{
assert_return (1, 0);
return 0;
}
else if (argc >= 2 && String ("--assert_return0") == argv[1])
{
assert_return (0, 0);
return 0;
}
else if (argc >= 2 && String ("--assert_return_unreached") == argv[1])
{
assert_return_unreached (0);
return 0;
}
else if (argc >= 2 && String ("--fatal_error") == argv[1])
{
Bse::fatal_error ("got argument --fatal_error");
return 0;
}
else if (argc >= 2 && String ("--return_unless0") == argv[1])
{
return_unless (0, 7);
return 0;
}
else if (argc >= 2 && String ("--return_unless1") == argv[1])
{
return_unless (1, 8);
return 0;
}
// integrity tests
assert_return (Bse::IntegrityCheck::checks_enabled() == true, -1);
if (tests)
for (const auto &te : *tests)
{ // note, more than one space after "TESTING:" confuses emacs file:line matches
printerr (" TESTING: %s:%u: %s…\n", te.file, te.line, te.func);
te.test();
printerr (" …DONE (%s)\n", te.func);
}
return 0;
}
int
main (int argc, char *argv[])
{
Bse::set_debug_flags (Bse::DebugFlags::SIGQUIT_ON_ABORT);
return bse_init_and_test (&argc, argv, [&]() { return test_main (argc, argv); });
}
<commit_msg>BSE: integrity.cc: sort integrity tests by function name<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include <bse/bsemain.hh>
#include <bse/testing.hh>
#include "bse/internal.hh"
using Bse::printerr;
typedef Bse::IntegrityCheck::TestFunc TestFunc;
// == BSE_INTEGRITY_TEST Registry ==
struct TestEntry {
TestFunc test;
const char *func;
const char *file;
int line;
TestEntry (const char *_file, int _line, const char *_func, TestFunc _test) :
test (_test), func (_func), file (_file), line (_line)
{}
};
static std::vector<TestEntry> *tests = NULL; // NOTE, this must be available for high priority early constructors
// == BSE_INTEGRITY_CHECK Activation ==
namespace Bse {
// Override Bse weak symbol to enable Bse's internal integrity tests, see bcore.hh
const bool IntegrityCheck::enabled = true;
// Registration function called for all integrity tests
void
IntegrityCheck::Test::register_test (const char *file, int line, const char *func, TestFunc test)
{
if (!tests)
tests = new std::vector<TestEntry>();
tests->push_back (TestEntry (file, line, func, test));
}
} // Bse
static int // for backtrace tests
my_compare_func (const void*, const void*)
{
BSE_BACKTRACE();
_Exit (0);
}
// == Main test program ==
static int
test_main (int argc, char *argv[])
{
if (argc >= 2 && String ("--backtrace") == argv[1])
{
char dummy_array[3] = { 1, 2, 3 };
qsort (dummy_array, 3, 1, my_compare_func);
}
else if (argc >= 2 && String ("--assert_return1") == argv[1])
{
assert_return (1, 0);
return 0;
}
else if (argc >= 2 && String ("--assert_return0") == argv[1])
{
assert_return (0, 0);
return 0;
}
else if (argc >= 2 && String ("--assert_return_unreached") == argv[1])
{
assert_return_unreached (0);
return 0;
}
else if (argc >= 2 && String ("--fatal_error") == argv[1])
{
Bse::fatal_error ("got argument --fatal_error");
return 0;
}
else if (argc >= 2 && String ("--return_unless0") == argv[1])
{
return_unless (0, 7);
return 0;
}
else if (argc >= 2 && String ("--return_unless1") == argv[1])
{
return_unless (1, 8);
return 0;
}
// integrity tests
assert_return (Bse::IntegrityCheck::checks_enabled() == true, -1);
if (!tests)
return 0;
std::sort (tests->begin(), tests->end(), [] (const TestEntry &a, const TestEntry &b) { return strcmp (a.func ? a.func : "", b.func ? b.func : "") < 0; });
for (const auto &te : *tests)
{ // note, more than one space after "TESTING:" confuses emacs file:line matches
printerr (" TESTING: %s:%u: %s…\n", te.file, te.line, te.func);
te.test();
printerr (" …DONE (%s)\n", te.func);
}
return 0;
}
int
main (int argc, char *argv[])
{
Bse::set_debug_flags (Bse::DebugFlags::SIGQUIT_ON_ABORT);
return bse_init_and_test (&argc, argv, [&]() { return test_main (argc, argv); });
}
<|endoftext|> |
<commit_before>//MIT License
//
//Copyright(c) 2016 Matthias Moeller
//
//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 __TYTI_STEAM_VDF_PARSER_H__
#define __TYTI_STEAM_VDF_PARSER_H__
#include <vector>
#include <unordered_map>
#include <utility>
#include <fstream>
#include <memory>
#include <stack>
namespace tyti
{
namespace vdf
{
template<typename CharT>
struct basic_object;
template<typename iStreamT, typename charT = typename iStreamT::char_type>
basic_object<charT> read(iStreamT& inStream, bool *ok = 0);
namespace detail
{
///////////////////////////////////////////////////////////////////////////
// Helper functions selecting the right encoding (char/wchar_T)
///////////////////////////////////////////////////////////////////////////
template<typename T>
struct literal_macro_help
{
static const char* result(const char* c, const wchar_t* wc)
{
return c;
}
static const char result(char c, wchar_t wc)
{
return c;
}
};
template<>
struct literal_macro_help<wchar_t>
{
static const wchar_t* result(const char* c, const wchar_t* wc)
{
return wc;
}
static const wchar_t result(char c, wchar_t wc)
{
return wc;
}
};
#define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text)
///////////////////////////////////////////////////////////////////////////
// Writer helper functions
///////////////////////////////////////////////////////////////////////////
struct tabs
{
size_t t;
tabs(size_t i) :t(i) {}
};
template<typename oStreamT>
oStreamT& operator<<(oStreamT& s, tabs t)
{
for (; t.t > 0; --t.t)
s << "\t";
return s;
}
} // end namespace detail
///////////////////////////////////////////////////////////////////////////
// Interface
///////////////////////////////////////////////////////////////////////////
/// basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens
template<typename CharT>
struct basic_object
{
typedef CharT char_type;
std::basic_string<char_type> name;
std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type> > attribs;
std::unordered_map<std::basic_string<char_type>, std::shared_ptr< basic_object<char_type> > > childs;
};
typedef basic_object<char> object;
typedef basic_object<wchar_t> wobject;
/** \brief writes given object tree in vdf format to given stream.
Uses tabs instead of whitespaces.
*/
template<typename oStreamT, typename charT = typename oStreamT::char_type>
void write(oStreamT& s, const basic_object<charT>& r, size_t t = 0)
{
using namespace detail;
s << tabs(t) << TYTI_L(charT, '"') << r.name << TYTI_L(charT, "\"\n") << tabs(t) << TYTI_L(charT, "{\n");
for (auto& i : r.attribs)
s << tabs(t + 1) << TYTI_L(charT, '"') << i.first << TYTI_L(charT, "\"\t\t\"") << i.second << TYTI_L(charT, "\"\n");
for (auto& i : r.childs)
write(s, i, t + 1);
s << tabs(t) << TYTI_L(charT, "}\n");
}
/** \brief Read VDF formatted sequences defined by the range [first, last).
If the file is mailformatted, parser will try to read it until it can.
@param first begin iterator
@param end end iterator
@param ok output bool. true, if parser successed, false, if parser failed
*/
template<typename IterT, typename charT = typename IterT::value_type>
basic_object<charT> read(IterT first, IterT last, bool* ok = 0)
{
if (ok)
*ok = true;
basic_object<charT> root;
basic_object<charT>* cur = &root;
std::stack< basic_object<charT>* > lvls;
//read header
// first, quoted name
auto b = std::find(first, last, TYTI_L(charT, '\"'));
auto bend = std::find(b + 1, last, TYTI_L(charT, '\"'));
root.name = std::basic_string<charT>(b+1, bend);
// second, get {}
b = std::find(bend, last, TYTI_L(charT,'{'));
lvls.push(&root);
while (!lvls.empty() && b != last)
{
const std::basic_string<charT> startsym = TYTI_L(charT, "\"}");
//find first starting attrib/child, or ending
b = std::find_first_of(b, last, std::cbegin(startsym), std::cend(startsym));
if (*b == '\"')
{
bend = std::find(b+1, last, TYTI_L(charT, '\"'));
std::basic_string<charT> curName(b + 1, bend);
b = bend + 1;
const std::basic_string<charT> ecspsym = TYTI_L(charT, "\"{");
b = std::find_first_of(b, last, std::cbegin(ecspsym), std::cend(ecspsym));
if (*b == '\"')
{
bend = std::find(b+1, last, TYTI_L(charT, '\"'));
auto value = std::basic_string<charT>(b + 1, bend);
b = bend + 1;
if (curName != TYTI_L(charT, "#include") && curName != TYTI_L(charT, "#base"))
cur->attribs[curName] = value;
else
{
std::basic_ifstream<charT> i(value);
auto n = std::make_shared<basic_object<charT>>(read(i, ok));
cur->childs[n->name] = n;
}
}
else if (*b == '{')
{
lvls.push(cur);
auto n = std::make_shared<basic_object<charT>>();
cur->childs[curName] = n;
cur = n.get();
cur->name = curName;
++b;
}
}
else if (*b == '}')
{
cur = lvls.top();
lvls.pop();
++b;
}
}
return root;
}
/** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.
*/
template<typename iStreamT, typename charT>
basic_object<charT> read(iStreamT& inStream, bool *ok)
{
// cache the file
std::basic_string<charT> str;
inStream.seekg(0, std::ios::end);
str.resize(inStream.tellg());
if (str.empty())
return basic_object<charT>();
inStream.seekg(0, std::ios::beg);
inStream.read(&str[0], str.size());
inStream.close();
// parse it
return read(str.begin(), str.end(), ok);
}
} // end namespace vdf
} // end namespace tyti
#ifndef TYTI_NO_L_UNDEF
#undef TYTI_L
#endif
#endif //__TYTI_STEAM_VDF_PARSER_H__<commit_msg>remove forward decl<commit_after>//MIT License
//
//Copyright(c) 2016 Matthias Moeller
//
//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 __TYTI_STEAM_VDF_PARSER_H__
#define __TYTI_STEAM_VDF_PARSER_H__
#include <vector>
#include <unordered_map>
#include <utility>
#include <fstream>
#include <memory>
#include <stack>
namespace tyti
{
namespace vdf
{
namespace detail
{
///////////////////////////////////////////////////////////////////////////
// Helper functions selecting the right encoding (char/wchar_T)
///////////////////////////////////////////////////////////////////////////
template<typename T>
struct literal_macro_help
{
static const char* result(const char* c, const wchar_t* wc)
{
return c;
}
static const char result(char c, wchar_t wc)
{
return c;
}
};
template<>
struct literal_macro_help<wchar_t>
{
static const wchar_t* result(const char* c, const wchar_t* wc)
{
return wc;
}
static const wchar_t result(char c, wchar_t wc)
{
return wc;
}
};
#define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text)
///////////////////////////////////////////////////////////////////////////
// Writer helper functions
///////////////////////////////////////////////////////////////////////////
struct tabs
{
size_t t;
tabs(size_t i) :t(i) {}
};
template<typename oStreamT>
oStreamT& operator<<(oStreamT& s, tabs t)
{
for (; t.t > 0; --t.t)
s << "\t";
return s;
}
} // end namespace detail
///////////////////////////////////////////////////////////////////////////
// Interface
///////////////////////////////////////////////////////////////////////////
/// basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens
template<typename CharT>
struct basic_object
{
typedef CharT char_type;
std::basic_string<char_type> name;
std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type> > attribs;
std::unordered_map<std::basic_string<char_type>, std::shared_ptr< basic_object<char_type> > > childs;
};
typedef basic_object<char> object;
typedef basic_object<wchar_t> wobject;
/** \brief writes given object tree in vdf format to given stream.
Uses tabs instead of whitespaces.
*/
template<typename oStreamT, typename charT = typename oStreamT::char_type>
void write(oStreamT& s, const basic_object<charT>& r, size_t t = 0)
{
using namespace detail;
s << tabs(t) << TYTI_L(charT, '"') << r.name << TYTI_L(charT, "\"\n") << tabs(t) << TYTI_L(charT, "{\n");
for (auto& i : r.attribs)
s << tabs(t + 1) << TYTI_L(charT, '"') << i.first << TYTI_L(charT, "\"\t\t\"") << i.second << TYTI_L(charT, "\"\n");
for (auto& i : r.childs)
write(s, i, t + 1);
s << tabs(t) << TYTI_L(charT, "}\n");
}
/** \brief Read VDF formatted sequences defined by the range [first, last).
If the file is mailformatted, parser will try to read it until it can.
@param first begin iterator
@param end end iterator
@param ok output bool. true, if parser successed, false, if parser failed
*/
template<typename IterT, typename charT = typename IterT::value_type>
basic_object<charT> read(IterT first, IterT last, bool* ok = 0)
{
//todo: error handling
if (ok)
*ok = true;
basic_object<charT> root;
basic_object<charT>* cur = &root;
std::stack< basic_object<charT>* > lvls;
//read header
// first, quoted name
auto b = std::find(first, last, TYTI_L(charT, '\"'));
auto bend = std::find(b + 1, last, TYTI_L(charT, '\"'));
root.name = std::basic_string<charT>(b+1, bend);
// second, get {}
b = std::find(bend, last, TYTI_L(charT,'{'));
lvls.push(&root);
while (!lvls.empty() && b != last)
{
const std::basic_string<charT> startsym = TYTI_L(charT, "\"}");
//find first starting attrib/child, or ending
b = std::find_first_of(b, last, std::cbegin(startsym), std::cend(startsym));
if (*b == '\"')
{
bend = std::find(b+1, last, TYTI_L(charT, '\"'));
std::basic_string<charT> curName(b + 1, bend);
b = bend + 1;
const std::basic_string<charT> ecspsym = TYTI_L(charT, "\"{");
b = std::find_first_of(b, last, std::cbegin(ecspsym), std::cend(ecspsym));
if (*b == '\"')
{
bend = std::find(b+1, last, TYTI_L(charT, '\"'));
auto value = std::basic_string<charT>(b + 1, bend);
b = bend + 1;
if (curName != TYTI_L(charT, "#include") && curName != TYTI_L(charT, "#base"))
cur->attribs[curName] = value;
else
{
std::basic_ifstream<charT> i(value);
auto n = std::make_shared<basic_object<charT>>(read(i, ok));
cur->childs[n->name] = n;
}
}
else if (*b == '{')
{
lvls.push(cur);
auto n = std::make_shared<basic_object<charT>>();
cur->childs[curName] = n;
cur = n.get();
cur->name = curName;
++b;
}
}
else if (*b == '}')
{
cur = lvls.top();
lvls.pop();
++b;
}
}
return root;
}
/** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.
*/
template<typename iStreamT, typename charT = iStreamT::char_type >
basic_object<charT> read(iStreamT& inStream, bool *ok = 0)
{
// cache the file
std::basic_string<charT> str;
inStream.seekg(0, std::ios::end);
str.resize(inStream.tellg());
if (str.empty())
return basic_object<charT>();
inStream.seekg(0, std::ios::beg);
inStream.read(&str[0], str.size());
inStream.close();
// parse it
return read(str.begin(), str.end(), ok);
}
} // end namespace vdf
} // end namespace tyti
#ifndef TYTI_NO_L_UNDEF
#undef TYTI_L
#endif
#endif //__TYTI_STEAM_VDF_PARSER_H__<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/system/configuration.hpp"
#include <algorithm>
#include <iostream>
#include "vast/config.hpp"
#include <caf/message_builder.hpp>
#include <caf/io/middleman.hpp>
#ifdef VAST_USE_OPENCL
#include <caf/opencl/manager.hpp>
#endif
#ifdef VAST_USE_OPENSSL
#include <caf/openssl/manager.hpp>
#endif
#include "vast/detail/add_error_categories.hpp"
#include "vast/detail/add_message_types.hpp"
#include "vast/detail/adjust_resource_consumption.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/string.hpp"
#include "vast/detail/system.hpp"
#include "vast/filesystem.hpp"
#include "vast/synopsis_factory.hpp"
#include "vast/table_slice_builder_factory.hpp"
#include "vast/table_slice_factory.hpp"
#include "vast/value_index.hpp"
#include "vast/value_index_factory.hpp"
using namespace caf;
namespace vast::system {
namespace {
template <class... Ts>
void initialize_factories() {
(factory<Ts>::initialize(), ...);
}
} // namespace <anonymous>
configuration::configuration() {
detail::add_message_types(*this);
detail::add_error_categories(*this);
// Use 'vast.conf' instead of generic 'caf-application.ini' and fall back to
// $PREFIX/etc/vast if no local vast.conf exists.
if ((path::current() / "vast.conf").is_regular_file()) {
config_file_path = "vast.conf";
} else {
auto global_conf = path{VAST_INSTALL_PREFIX} / "etc" / "vast";
config_file_path = global_conf.str();
}
// Load I/O module.
load<io::middleman>();
// GPU acceleration.
#ifdef VAST_USE_OPENCL
load<opencl::manager>();
#endif
opt_group{custom_options_, "vast"}
.add<size_t>("table-slice-size",
"Maximum size for sources that generate table slices.");
initialize_factories<synopsis, table_slice, table_slice_builder,
value_index>();
}
caf::error configuration::parse(int argc, char** argv) {
VAST_ASSERT(argc > 0);
VAST_ASSERT(argv != nullptr);
command_line.assign(argv + 1, argv + argc);
// Move CAF options to the end of the command line, parse them, and then
// remove them.
auto is_vast_opt = [](auto& x) { return !starts_with(x, "--caf#"); };
auto caf_opt = std::stable_partition(command_line.begin(),
command_line.end(), is_vast_opt);
std::vector<std::string> caf_args;
std::move(caf_opt, command_line.end(), std::back_inserter(caf_args));
command_line.erase(caf_opt, command_line.end());
// Remove caf# suffix for CAF parser.
for (auto& arg : caf_args)
arg.erase(2, 4);
return actor_system_config::parse(std::move(caf_args));
}
} // namespace vast::system
<commit_msg>Put global config file in its own directory<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/system/configuration.hpp"
#include <algorithm>
#include <iostream>
#include "vast/config.hpp"
#include <caf/message_builder.hpp>
#include <caf/io/middleman.hpp>
#ifdef VAST_USE_OPENCL
#include <caf/opencl/manager.hpp>
#endif
#ifdef VAST_USE_OPENSSL
#include <caf/openssl/manager.hpp>
#endif
#include "vast/detail/add_error_categories.hpp"
#include "vast/detail/add_message_types.hpp"
#include "vast/detail/adjust_resource_consumption.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/string.hpp"
#include "vast/detail/system.hpp"
#include "vast/filesystem.hpp"
#include "vast/synopsis_factory.hpp"
#include "vast/table_slice_builder_factory.hpp"
#include "vast/table_slice_factory.hpp"
#include "vast/value_index.hpp"
#include "vast/value_index_factory.hpp"
using namespace caf;
namespace vast::system {
namespace {
template <class... Ts>
void initialize_factories() {
(factory<Ts>::initialize(), ...);
}
} // namespace <anonymous>
configuration::configuration() {
detail::add_message_types(*this);
detail::add_error_categories(*this);
// Use 'vast.conf' instead of generic 'caf-application.ini' and fall back to
// $PREFIX/etc/vast if no local vast.conf exists.
if ((path::current() / "vast.conf").is_regular_file()) {
config_file_path = "vast.conf";
} else {
auto global_conf = path{VAST_INSTALL_PREFIX} / "etc" / "vast" / "vast.conf";
config_file_path = global_conf.str();
}
// Load I/O module.
load<io::middleman>();
// GPU acceleration.
#ifdef VAST_USE_OPENCL
load<opencl::manager>();
#endif
opt_group{custom_options_, "vast"}
.add<size_t>("table-slice-size",
"Maximum size for sources that generate table slices.");
initialize_factories<synopsis, table_slice, table_slice_builder,
value_index>();
}
caf::error configuration::parse(int argc, char** argv) {
VAST_ASSERT(argc > 0);
VAST_ASSERT(argv != nullptr);
command_line.assign(argv + 1, argv + argc);
// Move CAF options to the end of the command line, parse them, and then
// remove them.
auto is_vast_opt = [](auto& x) { return !starts_with(x, "--caf#"); };
auto caf_opt = std::stable_partition(command_line.begin(),
command_line.end(), is_vast_opt);
std::vector<std::string> caf_args;
std::move(caf_opt, command_line.end(), std::back_inserter(caf_args));
command_line.erase(caf_opt, command_line.end());
// Remove caf# suffix for CAF parser.
for (auto& arg : caf_args)
arg.erase(2, 4);
return actor_system_config::parse(std::move(caf_args));
}
} // namespace vast::system
<|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 "chrome/browser/extensions/api/autotest_private/autotest_private_api.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/extensions/api/autotest_private/autotest_private_api_factory.h"
#include "chrome/browser/extensions/extension_function_registry.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/common/extensions/api/autotest_private.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#endif
namespace extensions {
bool AutotestPrivateLogoutFunction::RunImpl() {
DVLOG(1) << "AutotestPrivateLogoutFunction";
if (!AutotestPrivateAPIFactory::GetForProfile(profile())->test_mode())
chrome::AttemptUserExit();
return true;
}
bool AutotestPrivateRestartFunction::RunImpl() {
DVLOG(1) << "AutotestPrivateRestartFunction";
if (!AutotestPrivateAPIFactory::GetForProfile(profile())->test_mode())
chrome::AttemptRestart();
return true;
}
bool AutotestPrivateShutdownFunction::RunImpl() {
scoped_ptr<api::autotest_private::Shutdown::Params> params(
api::autotest_private::Shutdown::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
DVLOG(1) << "AutotestPrivateShutdownFunction " << params->force;
#if defined(OS_CHROME)
if (params->force) {
if (!AutotestPrivateAPIFactory::GetForProfile(profile())->test_mode())
chrome::ExitCleanly();
return true;
}
#endif
if (!AutotestPrivateAPIFactory::GetForProfile(profile())->test_mode())
chrome::AttemptExit();
return true;
}
bool AutotestPrivateLoginStatusFunction::RunImpl() {
DVLOG(1) << "AutotestPrivateLoginStatusFunction";
DictionaryValue* result(new DictionaryValue);
#if defined(OS_CHROMEOS)
const chromeos::UserManager* user_manager = chromeos::UserManager::Get();
const bool is_screen_locked =
!!chromeos::ScreenLocker::default_screen_locker();
if (user_manager) {
result->SetBoolean("isLoggedIn", user_manager->IsUserLoggedIn());
result->SetBoolean("isOwner", user_manager->IsCurrentUserOwner());
result->SetBoolean("isScreenLocked", is_screen_locked);
if (user_manager->IsUserLoggedIn()) {
result->SetBoolean("isRegularUser",
user_manager->IsLoggedInAsRegularUser());
result->SetBoolean("isGuest", user_manager->IsLoggedInAsGuest());
result->SetBoolean("isKiosk", user_manager->IsLoggedInAsKioskApp());
const chromeos::User* user = user_manager->GetLoggedInUser();
result->SetString("email", user->email());
result->SetString("displayEmail", user->display_email());
std::string user_image;
switch (user->image_index()) {
case chromeos::User::kExternalImageIndex:
user_image = "file";
break;
case chromeos::User::kProfileImageIndex:
user_image = "profile";
break;
default:
user_image = base::IntToString(user->image_index());
break;
}
result->SetString("userImage", user_image);
}
}
#endif
SetResult(result);
return true;
}
AutotestPrivateAPI::AutotestPrivateAPI() : test_mode_(false) {
}
AutotestPrivateAPI::~AutotestPrivateAPI() {
}
} // namespace extensions
<commit_msg>Cleanup a few probably-incorrect OS_<random> uses.<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 "chrome/browser/extensions/api/autotest_private/autotest_private_api.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/extensions/api/autotest_private/autotest_private_api_factory.h"
#include "chrome/browser/extensions/extension_function_registry.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/common/extensions/api/autotest_private.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#endif
namespace extensions {
bool AutotestPrivateLogoutFunction::RunImpl() {
DVLOG(1) << "AutotestPrivateLogoutFunction";
if (!AutotestPrivateAPIFactory::GetForProfile(profile())->test_mode())
chrome::AttemptUserExit();
return true;
}
bool AutotestPrivateRestartFunction::RunImpl() {
DVLOG(1) << "AutotestPrivateRestartFunction";
if (!AutotestPrivateAPIFactory::GetForProfile(profile())->test_mode())
chrome::AttemptRestart();
return true;
}
bool AutotestPrivateShutdownFunction::RunImpl() {
scoped_ptr<api::autotest_private::Shutdown::Params> params(
api::autotest_private::Shutdown::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
DVLOG(1) << "AutotestPrivateShutdownFunction " << params->force;
#if defined(OS_CHROMEOS)
if (params->force) {
if (!AutotestPrivateAPIFactory::GetForProfile(profile())->test_mode())
chrome::ExitCleanly();
return true;
}
#endif
if (!AutotestPrivateAPIFactory::GetForProfile(profile())->test_mode())
chrome::AttemptExit();
return true;
}
bool AutotestPrivateLoginStatusFunction::RunImpl() {
DVLOG(1) << "AutotestPrivateLoginStatusFunction";
DictionaryValue* result(new DictionaryValue);
#if defined(OS_CHROMEOS)
const chromeos::UserManager* user_manager = chromeos::UserManager::Get();
const bool is_screen_locked =
!!chromeos::ScreenLocker::default_screen_locker();
if (user_manager) {
result->SetBoolean("isLoggedIn", user_manager->IsUserLoggedIn());
result->SetBoolean("isOwner", user_manager->IsCurrentUserOwner());
result->SetBoolean("isScreenLocked", is_screen_locked);
if (user_manager->IsUserLoggedIn()) {
result->SetBoolean("isRegularUser",
user_manager->IsLoggedInAsRegularUser());
result->SetBoolean("isGuest", user_manager->IsLoggedInAsGuest());
result->SetBoolean("isKiosk", user_manager->IsLoggedInAsKioskApp());
const chromeos::User* user = user_manager->GetLoggedInUser();
result->SetString("email", user->email());
result->SetString("displayEmail", user->display_email());
std::string user_image;
switch (user->image_index()) {
case chromeos::User::kExternalImageIndex:
user_image = "file";
break;
case chromeos::User::kProfileImageIndex:
user_image = "profile";
break;
default:
user_image = base::IntToString(user->image_index());
break;
}
result->SetString("userImage", user_image);
}
}
#endif
SetResult(result);
return true;
}
AutotestPrivateAPI::AutotestPrivateAPI() : test_mode_(false) {
}
AutotestPrivateAPI::~AutotestPrivateAPI() {
}
} // namespace extensions
<|endoftext|> |
<commit_before>#ifndef __WORD_TAG_HPP__
#define __WORD_TAG_HPP__
#include <vector>
#include <map>
#include <set>
#include "link-includes.h"
extern "C" {
#include "count.h"
#include "prune.h"
#include "word-utils.h"
};
#include "variables.hpp"
struct PositionConnector
{
PositionConnector(Exp* e, Connector* c, char d, int w, int p,
double cst, double pcst, bool lr, bool ll,
const std::vector<int>& er, const std::vector<int>& el, const X_node *w_xnode)
: exp(e), dir(d), word(w), position(p),
cost(cst), parent_cost(pcst),
leading_right(lr), leading_left(ll),
eps_right(er), eps_left(el), word_xnode(w_xnode)
{
// Initialize some fields in the connector struct.
connector.string = c->string;
connector.multi = c->multi;
connector.length_limit = c->length_limit;
if (word_xnode == NULL) {
cerr << "Internal error: Word" << w << ": " << "; connector: '" << c->string << "'; X_node: " << (word_xnode?word_xnode->string: "(null)") << endl;
}
/*
cout << c->string << " : ." << w << ". : ." << p << ". ";
if (leading_right) {
cout << "lr: ";
copy(er.begin(), er.end(), ostream_iterator<int>(cout, " "));
}
if (leading_left) {
cout << "ll: ";
copy(el.begin(), el.end(), ostream_iterator<int>(cout, " "));
}
cout << endl;
*/
}
// Original expression that this connector came from
Exp* exp;
// Connector itself
Connector connector;
// Direction
char dir;
// word in a sentence that this connector belongs to
size_t word;
// position in the word tag
int position;
// cost of the connector
double cost;
// parent cost
double parent_cost;
bool leading_right;
bool leading_left;
std::vector<int> eps_right;
std::vector<int> eps_left;
// The corresponding X_node - chosen-disjuncts[]
const X_node *word_xnode;
// Matches with other words
std::vector<PositionConnector*> matches;
};
// XXX TODO: Hash connectors for faster matching
class WordTag
{
private:
std::vector<PositionConnector> _left_connectors;
std::vector<PositionConnector> _right_connectors;
std::vector<char> _dir;
std::vector<int> _position;
int _word;
Variables* _variables;
Sentence _sent;
Parse_Options _opts;
// Could this word tag match a connector (wi, pi)?
// For each word wi I keep a set of positions pi that can be matched
std::vector< std::set<int> > _match_possible;
void set_match_possible(int wj, int pj) {
_match_possible[wj].insert(pj);
}
public:
WordTag(int word, Variables* variables, Sentence sent, Parse_Options opts)
: _word(word), _variables(variables), _sent(sent), _opts(opts) {
_match_possible.resize(_sent->length);
verbosity = opts->verbosity;
debug = opts->debug;
test = opts->test;
}
const std::vector<PositionConnector>& get_left_connectors() const {
return _left_connectors;
}
const std::vector<PositionConnector>& get_right_connectors() const {
return _right_connectors;
}
PositionConnector* get(int dfs_position)
{
switch (_dir[dfs_position - 1]) {
case '+':
return &_right_connectors[_position[dfs_position - 1]];
case '-':
return &_left_connectors[_position[dfs_position - 1]];
}
return NULL;
}
void set_connector_length_limit(Connector* c)
{
unsigned int len = _opts->short_length;
Connector_set * conset = _sent->dict->unlimited_connector_set;
if (len > UNLIMITED_LEN) len = UNLIMITED_LEN;
if (_opts->all_short ||
!(conset == NULL || match_in_connector_set(conset, c)))
{
c->length_limit = len;
}
}
bool match(int w1, Connector& cntr1, char dir, int w2, Connector& cntr2)
{
int dist = w2 - w1;
assert(0 < dist, "match() did not receive words in the natural order.");
if (dist > cntr1.length_limit || dist > cntr2.length_limit) return false;
return easy_match(cntr1.string, cntr2.string);
}
void insert_connectors(Exp* exp, int& dfs_position,
bool& leading_right, bool& leading_left,
std::vector<int>& eps_right,
std::vector<int>& eps_left,
char* var, bool root, double parent_cost,
Exp* parent, const X_node *word_xnode);
// Caches information about the found matches to the _matches vector, and also
// updates the _matches vector of all connectors in the given tag.
// In order to have all possible matches correctly cached, the function assumes that it is
// iteratively called for all words in the sentence, where the tag is on the right side of
// this word
void add_matches_with_word(WordTag& tag);
// Find matches in this word tag with the connector (name, dir).
void find_matches(int w, const char* C, char dir, std::vector<PositionConnector*>& matches);
// A simpler function: Can any connector in this word match a connector wi, pi?
// It is assumed that
bool match_possible(int wi, int pi)
{
return _match_possible[wi].find(pi) != _match_possible[wi].end();
}
private:
int verbosity;
const char *debug;
const char *test;
};
#endif
<commit_msg>SAT-solver: Revert the last change of setting length_limit<commit_after>#ifndef __WORD_TAG_HPP__
#define __WORD_TAG_HPP__
#include <vector>
#include <map>
#include <set>
#include "link-includes.h"
extern "C" {
#include "count.h"
#include "prune.h"
#include "word-utils.h"
};
#include "variables.hpp"
struct PositionConnector
{
PositionConnector(Exp* e, Connector* c, char d, int w, int p,
double cst, double pcst, bool lr, bool ll,
const std::vector<int>& er, const std::vector<int>& el, const X_node *w_xnode)
: exp(e), dir(d), word(w), position(p),
cost(cst), parent_cost(pcst),
leading_right(lr), leading_left(ll),
eps_right(er), eps_left(el), word_xnode(w_xnode)
{
// Initialize some fields in the connector struct.
connector.string = c->string;
connector.multi = c->multi;
connector.length_limit = c->length_limit;
if (word_xnode == NULL) {
cerr << "Internal error: Word" << w << ": " << "; connector: '" << c->string << "'; X_node: " << (word_xnode?word_xnode->string: "(null)") << endl;
}
/*
cout << c->string << " : ." << w << ". : ." << p << ". ";
if (leading_right) {
cout << "lr: ";
copy(er.begin(), er.end(), ostream_iterator<int>(cout, " "));
}
if (leading_left) {
cout << "ll: ";
copy(el.begin(), el.end(), ostream_iterator<int>(cout, " "));
}
cout << endl;
*/
}
// Original expression that this connector came from
Exp* exp;
// Connector itself
Connector connector;
// Direction
char dir;
// word in a sentence that this connector belongs to
size_t word;
// position in the word tag
int position;
// cost of the connector
double cost;
// parent cost
double parent_cost;
bool leading_right;
bool leading_left;
std::vector<int> eps_right;
std::vector<int> eps_left;
// The corresponding X_node - chosen-disjuncts[]
const X_node *word_xnode;
// Matches with other words
std::vector<PositionConnector*> matches;
};
// XXX TODO: Hash connectors for faster matching
class WordTag
{
private:
std::vector<PositionConnector> _left_connectors;
std::vector<PositionConnector> _right_connectors;
std::vector<char> _dir;
std::vector<int> _position;
int _word;
Variables* _variables;
Sentence _sent;
Parse_Options _opts;
// Could this word tag match a connector (wi, pi)?
// For each word wi I keep a set of positions pi that can be matched
std::vector< std::set<int> > _match_possible;
void set_match_possible(int wj, int pj) {
_match_possible[wj].insert(pj);
}
public:
WordTag(int word, Variables* variables, Sentence sent, Parse_Options opts)
: _word(word), _variables(variables), _sent(sent), _opts(opts) {
_match_possible.resize(_sent->length);
verbosity = opts->verbosity;
debug = opts->debug;
test = opts->test;
}
const std::vector<PositionConnector>& get_left_connectors() const {
return _left_connectors;
}
const std::vector<PositionConnector>& get_right_connectors() const {
return _right_connectors;
}
PositionConnector* get(int dfs_position)
{
switch (_dir[dfs_position - 1]) {
case '+':
return &_right_connectors[_position[dfs_position - 1]];
case '-':
return &_left_connectors[_position[dfs_position - 1]];
}
return NULL;
}
void set_connector_length_limit(Connector* c)
{
unsigned int len = _opts->short_length;
Connector_set * conset = _sent->dict->unlimited_connector_set;
if (len > UNLIMITED_LEN) len = UNLIMITED_LEN;
if (_opts->all_short ||
(conset != NULL && !match_in_connector_set(conset, c)))
{
c->length_limit = len;
}
else {
c->length_limit = UNLIMITED_LEN;
}
}
bool match(int w1, Connector& cntr1, char dir, int w2, Connector& cntr2)
{
int dist = w2 - w1;
assert(0 < dist, "match() did not receive words in the natural order.");
if (dist > cntr1.length_limit || dist > cntr2.length_limit) return false;
return easy_match(cntr1.string, cntr2.string);
}
void insert_connectors(Exp* exp, int& dfs_position,
bool& leading_right, bool& leading_left,
std::vector<int>& eps_right,
std::vector<int>& eps_left,
char* var, bool root, double parent_cost,
Exp* parent, const X_node *word_xnode);
// Caches information about the found matches to the _matches vector, and also
// updates the _matches vector of all connectors in the given tag.
// In order to have all possible matches correctly cached, the function assumes that it is
// iteratively called for all words in the sentence, where the tag is on the right side of
// this word
void add_matches_with_word(WordTag& tag);
// Find matches in this word tag with the connector (name, dir).
void find_matches(int w, const char* C, char dir, std::vector<PositionConnector*>& matches);
// A simpler function: Can any connector in this word match a connector wi, pi?
// It is assumed that
bool match_possible(int wi, int pi)
{
return _match_possible[wi].find(pi) != _match_possible[wi].end();
}
private:
int verbosity;
const char *debug;
const char *test;
};
#endif
<|endoftext|> |
<commit_before>// Copyright(c) Andre Caron, 2009-2010
//
// This document is covered by the Artistic License 2.0 (Open Source Initiative
// approved license). A copy of the license should have been provided alongside
// this software package (see "license.rtf"). If not, the license is available
// online at "http://www.opensource.org/licenses/artistic-license-2.0.php".
#include <w32/string.hpp>
#include <w32/astring.hpp>
#include <w32/Error.hpp>
#include <algorithm>
#include <iostream>
#include <limits>
#include <cstring>
namespace {
// Allocate a string and automatically terminate it.
template<typename T>
T * allocate ( ::DWORD size )
{
T *const result = new T[size+1];
result[size] = T(0);
return (result);
}
// Returns the number of characters to allocate.
template<typename T>
::DWORD count ( const T * value )
{
static const T terminator(0);
::DWORD result = 0;
for ( ; (*value != terminator); ++value ) {
++result;
}
return (result);
}
// Allocate a fresh copy of a string.
template<typename T>
T * duplicate ( ::DWORD size, const T * value )
{
T *const result = allocate<T>(size);
::memcpy(result, value, sizeof(T)*size);
return (result);
}
// Request the number of characters to allocate.
::DWORD count ( ::UINT codepage, const char * value )
{
const int result = ::MultiByteToWideChar(
codepage, 0, value, -1, 0, 0
);
if ( result == 0 ) {
const ::DWORD error = ::GetLastError();
UNCHECKED_WIN32C_ERROR(MultiByteToWideChar,error);
}
return (result);
}
// Codepage is source encoding!
::WCHAR * decode ( ::UINT codepage, ::DWORD size, const char * value )
{
::WCHAR *const data = allocate<::WCHAR>(size);
const int result = ::MultiByteToWideChar(codepage,0,value,-1,data,size+1);
if ( result == 0 ) {
const ::DWORD error = ::GetLastError();
UNCHECKED_WIN32C_ERROR(MultiByteToWideChar,error);
}
return (data);
}
}
namespace w32 {
const string::size_type string::npos =
std::numeric_limits< string::size_type >::max();
string::string ()
: mySize(0),
myData(::duplicate(mySize, L""))
{
}
string::string ( const char * other, Codepage encoding )
: mySize(::count(other)),
myData(::decode(encoding, mySize, other))
{
}
string::string ( const char * other, size_type size, Codepage encoding )
: mySize(size),
myData(::decode(encoding, mySize, other))
{
}
string::string ( const astring& other )
: mySize(other.size()),
myData(decode(other.encoding(), mySize, other.data()))
{
}
string::string ( const std::string& other, Codepage encoding )
: mySize(other.size()),
myData(::decode(encoding, mySize, other.data()))
{
}
string::string ( const_pointer other )
: mySize(count(other)),
myData(duplicate(mySize,other))
{
}
string::string ( const_pointer other, size_type size )
: mySize(size),
myData(duplicate(mySize,other))
{
}
string::string ( const box& value )
: mySize(value.size()),
myData(value.data())
{
}
string::string ( size_type size, char_type filler )
: mySize(size),
myData(::allocate<wchar_t>(size))
{
std::fill(begin(), end(), filler);
}
string::string ( const string& other )
: mySize(other.size()),
myData(duplicate(mySize,other.data()))
{
}
string::~string ()
{
delete [] myData;
myData = 0;
mySize = 0;
}
string::size_type string::size() const
{
return (mySize);
}
string::size_type string::length() const
{
return (mySize);
}
bool string::empty () const
{
return (size() == 0);
}
string::pointer string::data ()
{
return (myData);
}
string::const_pointer string::data () const
{
return (myData);
}
string::pointer string::c_str ()
{
return (myData);
}
string::const_pointer string::c_str () const
{
return (myData);
}
void string::erase ( iterator begin, iterator end )
{
// Copy trailing characters.
end = std::copy(end, myData+mySize, begin);
// Terminate string.
myData[mySize = (end-myData)] = L'\0';
}
void string::resize ( size_type length, wchar_t filler )
{
// Don't reallocate when not required to.
if ( length <= size() ) {
erase(begin()+size(), end());
}
else {
string other(length, filler);
std::copy(begin(), end(), other.begin());
swap(other);
}
}
void string::clear ()
{
erase(begin(), end());
}
string string::substr ( size_type offset, size_type length ) const
{
offset = std::min(offset, size());
length = std::min(offset+length, size());
return (string(data()+offset, length));
}
string::iterator string::begin ()
{
return (data());
}
string::iterator string::end ()
{
return (data() + size());
}
string::const_iterator string::begin () const
{
return (data());
}
string::const_iterator string::end () const
{
return (data() + size());
}
void string::swap ( string& other )
{
std::swap(mySize,other.mySize);
std::swap(myData,other.myData);
}
string& string::operator= ( const string& other )
{
string copy(other);
copy.swap(*this);
return (*this);
}
string& string::operator= ( const_pointer other )
{
string copy(other);
copy.swap(*this);
return (*this);
}
string& string::operator= ( const std::wstring& other )
{
string copy(other.c_str());
copy.swap(*this);
return (*this);
}
bool string::operator== ( const string& rhs ) const
{
return (std::wcscmp(data(), rhs.data()) == 0);
}
bool string::operator!= ( const string& rhs ) const
{
return (std::wcscmp(data(), rhs.data()) != 0);
}
string& string::operator+= ( const string& rhs )
{
if ( length() == 0 ) {
return ((*this) = rhs);
}
string result(length() + rhs.length());
std::copy(rhs.begin(), rhs.end(),
std::copy(begin(), end(), result.begin()));
result.swap(*this);
return (*this);
}
string string::operator+ ( const string& rhs ) const
{
string result(*this);
result += rhs;
return (result);
}
string& string::operator+= ( wchar_t rhs )
{
resize(1+size());
(*this)[size()-1] = rhs;
return (*this);
}
string string::operator+ ( wchar_t rhs ) const
{
string result(*this);
result += rhs;
return (result);
}
string operator+ ( const wchar_t * lhs, const string& rhs )
{
return (string(lhs) + rhs);
}
std::wostream& operator<< ( std::wostream& out, const string& value )
{
return (out << value.data());
}
string::box::box ( pointer data )
: mySize(std::wcslen(data)), myData(data)
{
}
string::box::box ( pointer data, size_type size )
: mySize(size), myData(data)
{
}
string::size_type string::box::size() const
{
return (mySize);
}
string::pointer string::box::data () const
{
return (myData);
}
}
<commit_msg>Prevented crash on null pointer in string constructor.<commit_after>// Copyright(c) Andre Caron, 2009-2010
//
// This document is covered by the Artistic License 2.0 (Open Source Initiative
// approved license). A copy of the license should have been provided alongside
// this software package (see "license.rtf"). If not, the license is available
// online at "http://www.opensource.org/licenses/artistic-license-2.0.php".
#include <w32/string.hpp>
#include <w32/astring.hpp>
#include <w32/Error.hpp>
#include <algorithm>
#include <iostream>
#include <limits>
#include <cstring>
namespace {
// Allocate a string and automatically terminate it.
template<typename T>
T * allocate ( ::DWORD size )
{
T *const result = new T[size+1];
result[size] = T(0);
return (result);
}
// Returns the number of characters to allocate.
template<typename T>
::DWORD count ( const T * value )
{
if ( value == 0 ) {
return (0);
}
static const T terminator(0);
::DWORD result = 0;
for ( ; (*value != terminator); ++value ) {
++result;
}
return (result);
}
// Allocate a fresh copy of a string.
template<typename T>
T * duplicate ( ::DWORD size, const T * value )
{
T *const result = allocate<T>(size);
::memcpy(result, value, sizeof(T)*size);
return (result);
}
// Request the number of characters to allocate.
::DWORD count ( ::UINT codepage, const char * value )
{
const int result = ::MultiByteToWideChar
(codepage, 0, value, -1, 0, 0);
if ( result == 0 ) {
const ::DWORD error = ::GetLastError();
UNCHECKED_WIN32C_ERROR(MultiByteToWideChar,error);
}
return (result);
}
// Codepage is source encoding!
::WCHAR * decode ( ::UINT codepage, ::DWORD size, const char * value )
{
::WCHAR *const data = allocate<::WCHAR>(size);
const int result = ::MultiByteToWideChar(codepage,0,value,-1,data,size+1);
if ( result == 0 ) {
const ::DWORD error = ::GetLastError();
UNCHECKED_WIN32C_ERROR(MultiByteToWideChar,error);
}
return (data);
}
}
namespace w32 {
const string::size_type string::npos =
std::numeric_limits< string::size_type >::max();
string::string ()
: mySize(0),
myData(::duplicate(mySize, L""))
{
}
string::string ( const char * other, Codepage encoding )
: mySize(::count(other)),
myData(::decode(encoding, mySize, other))
{
}
string::string ( const char * other, size_type size, Codepage encoding )
: mySize(size),
myData(::decode(encoding, mySize, other))
{
}
string::string ( const astring& other )
: mySize(other.size()),
myData(decode(other.encoding(), mySize, other.data()))
{
}
string::string ( const std::string& other, Codepage encoding )
: mySize(other.size()),
myData(::decode(encoding, mySize, other.data()))
{
}
string::string ( const_pointer other )
: mySize(count(other)),
myData(duplicate(mySize,other))
{
}
string::string ( const_pointer other, size_type size )
: mySize(size),
myData(duplicate(mySize,other))
{
}
string::string ( const box& value )
: mySize(value.size()),
myData(value.data())
{
}
string::string ( size_type size, char_type filler )
: mySize(size),
myData(::allocate<wchar_t>(size))
{
std::fill(begin(), end(), filler);
}
string::string ( const string& other )
: mySize(other.size()),
myData(duplicate(mySize,other.data()))
{
}
string::~string ()
{
delete [] myData;
myData = 0;
mySize = 0;
}
string::size_type string::size() const
{
return (mySize);
}
string::size_type string::length() const
{
return (mySize);
}
bool string::empty () const
{
return (size() == 0);
}
string::pointer string::data ()
{
return (myData);
}
string::const_pointer string::data () const
{
return (myData);
}
string::pointer string::c_str ()
{
return (myData);
}
string::const_pointer string::c_str () const
{
return (myData);
}
void string::erase ( iterator begin, iterator end )
{
// Copy trailing characters.
end = std::copy(end, myData+mySize, begin);
// Terminate string.
myData[mySize = (end-myData)] = L'\0';
}
void string::resize ( size_type length, wchar_t filler )
{
// Don't reallocate when not required to.
if ( length <= size() ) {
erase(begin()+size(), end());
}
else {
string other(length, filler);
std::copy(begin(), end(), other.begin());
swap(other);
}
}
void string::clear ()
{
erase(begin(), end());
}
string string::substr ( size_type offset, size_type length ) const
{
offset = std::min(offset, size());
length = std::min(offset+length, size());
return (string(data()+offset, length));
}
string::iterator string::begin ()
{
return (data());
}
string::iterator string::end ()
{
return (data() + size());
}
string::const_iterator string::begin () const
{
return (data());
}
string::const_iterator string::end () const
{
return (data() + size());
}
void string::swap ( string& other )
{
std::swap(mySize,other.mySize);
std::swap(myData,other.myData);
}
string& string::operator= ( const string& other )
{
string copy(other);
copy.swap(*this);
return (*this);
}
string& string::operator= ( const_pointer other )
{
string copy(other);
copy.swap(*this);
return (*this);
}
string& string::operator= ( const std::wstring& other )
{
string copy(other.c_str());
copy.swap(*this);
return (*this);
}
bool string::operator== ( const string& rhs ) const
{
return (std::wcscmp(data(), rhs.data()) == 0);
}
bool string::operator!= ( const string& rhs ) const
{
return (std::wcscmp(data(), rhs.data()) != 0);
}
string& string::operator+= ( const string& rhs )
{
if ( length() == 0 ) {
return ((*this) = rhs);
}
string result(length() + rhs.length());
std::copy(rhs.begin(), rhs.end(),
std::copy(begin(), end(), result.begin()));
result.swap(*this);
return (*this);
}
string string::operator+ ( const string& rhs ) const
{
string result(*this);
result += rhs;
return (result);
}
string& string::operator+= ( wchar_t rhs )
{
resize(1+size());
(*this)[size()-1] = rhs;
return (*this);
}
string string::operator+ ( wchar_t rhs ) const
{
string result(*this);
result += rhs;
return (result);
}
string operator+ ( const wchar_t * lhs, const string& rhs )
{
return (string(lhs) + rhs);
}
std::wostream& operator<< ( std::wostream& out, const string& value )
{
return (out << value.data());
}
string::box::box ( pointer data )
: mySize(std::wcslen(data)), myData(data)
{
}
string::box::box ( pointer data, size_type size )
: mySize(size), myData(data)
{
}
string::size_type string::box::size() const
{
return (mySize);
}
string::pointer string::box::data () const
{
return (myData);
}
}
<|endoftext|> |
<commit_before>#include "ncserver.h"
#include "networkcodingheader.h"
#include "finite_field.h"
#include <exception>
#include <string.h>
ncserver::ncserver(unsigned int client_ip, unsigned short int port, unsigned char max_block_size, unsigned int timeout):\
_CTRL_ADDR(build_addr(INADDR_ANY, port)), _DATA_ADDR(build_addr(client_ip, port)), \
_MAX_BLOCK_SIZE(max_block_size), _TX_TIMEOUT(timeout){
_socket = 0;
_tx_cnt = 0;
_blk_seq = 0;
_pkt_seq = 0;
_redundant_pkts = 2;
/*
* TODO: 1) Encode meaningful pkts in _buffer. (_buffer may not be full when _flush_pkts is triggered by timeout)
* 2) The length of remedy packet should be as most that of the longest pkt in _buffer.
* 3) Parallelize the encoding process using OpenMP.
* NOTE: 1) This function should be called by singleshottimer. Otherwise, its operation is undefied.
*/
_cancel_callback = _timeout_callback = [&](){
std::lock_guard<std::mutex> lock(_lock);
int ret;
for(unsigned int tx = 0 ; tx < _redundant_pkts ; tx++){
for(unsigned int code = 0 ; code < _MAX_BLOCK_SIZE ; code++){
_rand_coef[code] = 1+rand()%255;
}
GET_BLK_SEQ(_remedy_pkt) = _blk_seq;
GET_PKT_SEQ(_remedy_pkt) = _pkt_seq++;
GET_BLK_SIZE(_remedy_pkt) = _MAX_BLOCK_SIZE;
for(unsigned int position = OUTERHEADER_SIZE ; position < HEADER_SIZE(_MAX_BLOCK_SIZE)+MAX_PAYLOAD_SIZE(_MAX_BLOCK_SIZE) ; position++){
for(unsigned int pkt = 0 ; pkt < _MAX_BLOCK_SIZE ; pkt++){
(pkt == 0?
_remedy_pkt[pos] = FiniteField::instance()->mul(_buffer[pkt][position], _rand_coef[pkt]):
_remedy_pkt[pos] ^= FiniteField::instance()->mul(_buffer[pkt][position], _rand_coef[pkt]));
}
}
ret = sendto(_socket, _remedy_pkt, HEADER_SIZE(_MAX_BLOCK_SIZE)+MAX_PAYLOAD_SIZE(_MAX_BLOCK_SIZE), 0, (sockaddr*)&_DATA_ADDR, sizeof(_DATA_ADDR));
if(ret == -1){
std::cout << "Cannot send remedy pkt" << std::endl;
}
}
_blk_seq++;
_tx_cnt = 0;
};
}
ncserver::~ncserver(){
close_server();
}
sockaddr_in ncserver::build_addr(unsigned int ip, unsigned short int port){
sockaddr_in ret = {0};
ret.sin_family = AF_INET;
ret.sin_addr.s_addr = htonl(ip);
ret.sin_port = htons(port);
return ret;
}
bool ncserver::open_server(){
_socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(_socket == -1){
return false;
}
int opt = 1;
if(setsockopt(_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1){
close(_socket);
return false;
}
if(bind(_socket, (sockaddr*)&_CTRL_ADDR, sizeof(_CTRL_ADDR)) == -1){
close(_socket);
return false;
}
try{
_buffer = new unsigned char*[_MAX_BLOCK_SIZE];
for(unsigned int i = 0 ; i < _MAX_BLOCK_SIZE ; i++){
_buffer[i] = new unsigned char[HEADER_SIZE(_MAX_BLOCK_SIZE)+MAX_PAYLOAD_SIZE(_MAX_BLOCK_SIZE)];
}
_remedy_pkt = new unsigned char[HEADER_SIZE(_MAX_BLOCK_SIZE)+MAX_PAYLOAD_SIZE(_MAX_BLOCK_SIZE)];
_rand_coef = new unsigned char[_MAX_BLOCK_SIZE];
}catch(std::exception &ex){
return false;
}
return true;
}
/*
* TODO: Check if this function can be further optimized using rvalue reference using std::move()
*/
unsigned short int ncserver::send(unsigned char* pkt, unsigned short int pkt_size){
std::lock_guard<std::mutex> lock(_lock);
unsigned short int ret = 0;
if(pkt_size > MAX_PAYLOAD_SIZE){
return 0; // I will support pkt_size larger than MAX_PAYLOAD_SIZE in the next phase.
}
GET_BLK_SEQ(_buffer[_tx_cnt]) = _blk_seq;
GET_PKT_SEQ(_buffer[_tx_cnt]) = _pkt_seq++;
GET_BLK_SIZE(_buffer[_tx_cnt]) = _MAX_BLOCK_SIZE;
GET_SIZE(_buffer[_tx_cnt]) = pkt_size;
GET_LAST_INDICATOR(_buffer[_tx_cnt]) = 1; // I will support pkt_size larger than MAX_PAYLOAD_SIZE in the next phase.
memset(GET_CODE(_buffer[_tx_cnt]), 0x0, _MAX_BLOCK_SIZE);
GET_CODE(_buffer[_tx_cnt])[_tx_cnt] = 1;
memcpy(GET_PAYLOAD(_buffer[_tx_cnt], _MAX_BLOCK_SIZE), pkt, pkt_size);
if(sendto(_socket, _buffer[_tx_cnt], pkt_size + HEADER_SIZE(_MAX_BLOCK_SIZE), 0, (sockaddr*)&_DATA_ADDR, sizeof(_DATA_ADDR)) == pkt_size + HEADER_SIZE(_MAX_BLOCK_SIZE)){
ret = pkt_size;
}else{
ret = 0;
}
if(_tx_cnt == 0){
_timer.start(_TX_TIMEOUT, _cancel_callback, _timeout_callback);
}else if(_tx_cnt == _MAX_BLOCK_SIZE-1){
_timer.cancel();
}
_tx_cnt++;
return ret;
}
void ncserver::close_server(){
delete [] _rand_coef;
delete [] _remedy_pkt;
for(unsigned int i = 0 ; i < _MAX_BLOCK_SIZE ; i++){
delete [] _buffer[i];
}
delete []_buffer;
if(_socket){
close(_socket);
}
}
<commit_msg>Update ncserver.cpp<commit_after>#include "ncserver.h"
#include "networkcodingheader.h"
#include "finite_field.h"
#include <exception>
#include <string.h>
ncserver::ncserver(unsigned int client_ip, unsigned short int port, unsigned char max_block_size, unsigned int timeout):\
_CTRL_ADDR(build_addr(INADDR_ANY, port)), _DATA_ADDR(build_addr(client_ip, port)), \
_MAX_BLOCK_SIZE(max_block_size), _TX_TIMEOUT(timeout){
_socket = 0;
_tx_cnt = 0;
_largest_pkt_size = 0;
_blk_seq = 0;
_pkt_seq = 0;
_redundant_pkts = 2;
/*
* TODO: 1) Encode meaningful pkts in _buffer. (_buffer may not be full when _flush_pkts is triggered by timeout) => resolved: for(unsigned int pkt = 0 ; pkt < _tx_cnt ; pkt++){
* 2) The length of remedy packet should be as most that of the longest pkt in _buffer. => resolved: HEADER_SIZE(_MAX_BLOCK_SIZE)+_largest_pkt_size
* 3) Parallelize the encoding process using OpenMP.
* NOTE: 1) This function should be called by singleshottimer. Otherwise, its operation is undefied.
*/
_cancel_callback = _timeout_callback = [&](){
std::lock_guard<std::mutex> lock(_lock);
int ret;
for(unsigned int tx = 0 ; tx < _redundant_pkts ; tx++){
for(unsigned int code = 0 ; code < _MAX_BLOCK_SIZE ; code++){
_rand_coef[code] = 1+rand()%255;
}
GET_BLK_SEQ(_remedy_pkt) = _blk_seq;
GET_PKT_SEQ(_remedy_pkt) = _pkt_seq++;
GET_BLK_SIZE(_remedy_pkt) = _MAX_BLOCK_SIZE;
for(unsigned int position = OUTERHEADER_SIZE ; position < HEADER_SIZE(_MAX_BLOCK_SIZE)+_largest_pkt_size ; position++){
for(unsigned int pkt = 0 ; pkt < _tx_cnt ; pkt++){
(pkt == 0?
_remedy_pkt[pos] = FiniteField::instance()->mul(_buffer[pkt][position], _rand_coef[pkt]):
_remedy_pkt[pos] ^= FiniteField::instance()->mul(_buffer[pkt][position], _rand_coef[pkt]));
}
}
ret = sendto(_socket, _remedy_pkt, HEADER_SIZE(_MAX_BLOCK_SIZE)+MAX_PAYLOAD_SIZE(_MAX_BLOCK_SIZE), 0, (sockaddr*)&_DATA_ADDR, sizeof(_DATA_ADDR));
if(ret == -1){
std::cout << "Cannot send remedy pkt" << std::endl;
}
}
_blk_seq++;
_tx_cnt = 0;
_largest_pkt_size = 0;
};
}
ncserver::~ncserver(){
close_server();
}
sockaddr_in ncserver::build_addr(unsigned int ip, unsigned short int port){
sockaddr_in ret = {0};
ret.sin_family = AF_INET;
ret.sin_addr.s_addr = htonl(ip);
ret.sin_port = htons(port);
return ret;
}
bool ncserver::open_server(){
_socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(_socket == -1){
return false;
}
int opt = 1;
if(setsockopt(_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1){
close(_socket);
return false;
}
if(bind(_socket, (sockaddr*)&_CTRL_ADDR, sizeof(_CTRL_ADDR)) == -1){
close(_socket);
return false;
}
try{
_buffer = new unsigned char*[_MAX_BLOCK_SIZE];
for(unsigned int i = 0 ; i < _MAX_BLOCK_SIZE ; i++){
_buffer[i] = new unsigned char[HEADER_SIZE(_MAX_BLOCK_SIZE)+MAX_PAYLOAD_SIZE(_MAX_BLOCK_SIZE)];
}
_remedy_pkt = new unsigned char[HEADER_SIZE(_MAX_BLOCK_SIZE)+MAX_PAYLOAD_SIZE(_MAX_BLOCK_SIZE)];
_rand_coef = new unsigned char[_MAX_BLOCK_SIZE];
}catch(std::exception &ex){
return false;
}
return true;
}
/*
* TODO: Check if this function can be further optimized using rvalue reference using std::move()
*/
unsigned short int ncserver::send(unsigned char* pkt, unsigned short int pkt_size){
std::lock_guard<std::mutex> lock(_lock);
unsigned short int ret = 0;
if(pkt_size > MAX_PAYLOAD_SIZE){
return 0; // I will support pkt_size larger than MAX_PAYLOAD_SIZE in the next phase.
}
if(_largest_pkt_size < pkt_size){
_largest_pkt_size = pkt_size;
}
GET_BLK_SEQ(_buffer[_tx_cnt]) = _blk_seq;
GET_PKT_SEQ(_buffer[_tx_cnt]) = _pkt_seq++;
GET_BLK_SIZE(_buffer[_tx_cnt]) = _MAX_BLOCK_SIZE;
GET_SIZE(_buffer[_tx_cnt]) = pkt_size;
GET_LAST_INDICATOR(_buffer[_tx_cnt]) = 1; // I will support pkt_size larger than MAX_PAYLOAD_SIZE in the next phase.
memset(GET_CODE(_buffer[_tx_cnt]), 0x0, _MAX_BLOCK_SIZE);
GET_CODE(_buffer[_tx_cnt])[_tx_cnt] = 1;
memcpy(GET_PAYLOAD(_buffer[_tx_cnt], _MAX_BLOCK_SIZE), pkt, pkt_size);
if(sendto(_socket, _buffer[_tx_cnt], pkt_size + HEADER_SIZE(_MAX_BLOCK_SIZE), 0, (sockaddr*)&_DATA_ADDR, sizeof(_DATA_ADDR)) == pkt_size + HEADER_SIZE(_MAX_BLOCK_SIZE)){
ret = pkt_size;
}else{
ret = 0;
}
if(_tx_cnt == 0){
_timer.start(_TX_TIMEOUT, _cancel_callback, _timeout_callback);
}else if(_tx_cnt == _MAX_BLOCK_SIZE-1){
_timer.cancel();
}
_tx_cnt++;
return ret;
}
void ncserver::close_server(){
delete [] _rand_coef;
delete [] _remedy_pkt;
for(unsigned int i = 0 ; i < _MAX_BLOCK_SIZE ; i++){
delete [] _buffer[i];
}
delete []_buffer;
if(_socket){
close(_socket);
}
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "shadingresultframebuffer.h"
// appleseed.renderer headers.
#include "renderer/kernel/aov/tilestack.h"
#include "renderer/kernel/shading/shadingresult.h"
// appleseed.foundation headers.
#include "foundation/image/color.h"
#include "foundation/image/colorspace.h"
#include "foundation/image/tile.h"
#include "foundation/platform/compiler.h"
// Standard headers.
#include <cassert>
using namespace foundation;
using namespace std;
namespace renderer
{
ShadingResultFrameBuffer::ShadingResultFrameBuffer(
const size_t width,
const size_t height,
const size_t aov_count,
const Filter2d& filter)
: FilteredTile(
width,
height,
4 + aov_count * 3,
filter)
, m_aov_count(aov_count)
, m_scratch(4 + aov_count * 3)
{
}
ShadingResultFrameBuffer::ShadingResultFrameBuffer(
const size_t width,
const size_t height,
const size_t aov_count,
const AABB2u& crop_window,
const Filter2d& filter)
: FilteredTile(
width,
height,
4 + aov_count * 3,
crop_window,
filter)
, m_aov_count(aov_count)
, m_scratch(4 + aov_count * 3)
{
}
void ShadingResultFrameBuffer::add(
const double x,
const double y,
const ShadingResult& sample)
{
assert(sample.m_color_space == ColorSpaceLinearRGB);
float* ptr = &m_scratch[0];
*ptr++ = sample.m_alpha[0];
*ptr++ = sample.m_color[0];
*ptr++ = sample.m_color[1];
*ptr++ = sample.m_color[2];
for (size_t i = 0; i < m_aov_count; ++i)
{
*ptr++ = sample.m_aovs[i][0];
*ptr++ = sample.m_aovs[i][1];
*ptr++ = sample.m_aovs[i][2];
}
FilteredTile::add(x, y, &m_scratch[0]);
}
void ShadingResultFrameBuffer::merge(
const size_t dest_x,
const size_t dest_y,
const ShadingResultFrameBuffer& source,
const size_t source_x,
const size_t source_y,
const float scaling)
{
assert(m_channel_count == source.m_channel_count);
const float* RESTRICT source_ptr = source.pixel(source_x, source_y);
float* RESTRICT dest_ptr = pixel(dest_x, dest_y);
for (size_t i = 0; i < m_channel_count + 1; ++i)
dest_ptr[i] += source_ptr[i] * scaling;
}
void ShadingResultFrameBuffer::develop_to_tile_premult_alpha(
Tile& tile,
TileStack& aov_tiles) const
{
const float* ptr = pixel(0);
for (size_t y = 0; y < m_height; ++y)
{
for (size_t x = 0; x < m_width; ++x)
{
const float weight = *ptr++;
const float rcp_weight = weight == 0.0f ? 0.0f : 1.0f / weight;
const float alpha = *ptr++;
const Color4f color(ptr[0], ptr[1], ptr[2], alpha);
tile.set_pixel(x, y, color * rcp_weight);
ptr += 3;
for (size_t i = 0; i < m_aov_count; ++i)
{
const Color4f aov(ptr[0], ptr[1], ptr[2], alpha);
aov_tiles.set_pixel(x, y, i, aov * rcp_weight);
ptr += 3;
}
}
}
}
void ShadingResultFrameBuffer::develop_to_tile_straight_alpha(
Tile& tile,
TileStack& aov_tiles) const
{
const float* ptr = pixel(0);
for (size_t y = 0; y < m_height; ++y)
{
for (size_t x = 0; x < m_width; ++x)
{
const float weight = *ptr++;
const float rcp_weight = weight == 0.0f ? 0.0f : 1.0f / weight;
const float alpha = *ptr++;
const float rcp_weight_alpha = alpha == 0.0f ? 0.0f : 1.0f / alpha;
Color4f color(ptr[0], ptr[1], ptr[2], alpha);
color.rgb() *= rcp_weight_alpha;
color.a *= rcp_weight;
tile.set_pixel(x, y, color);
ptr += 3;
for (size_t i = 0; i < m_aov_count; ++i)
{
Color4f aov(ptr[0], ptr[1], ptr[2], alpha);
aov.rgb() *= rcp_weight_alpha;
aov.a *= rcp_weight;
aov_tiles.set_pixel(x, y, i, aov);
ptr += 3;
}
}
}
}
} // namespace renderer
<commit_msg>fixed regression.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "shadingresultframebuffer.h"
// appleseed.renderer headers.
#include "renderer/kernel/aov/tilestack.h"
#include "renderer/kernel/shading/shadingresult.h"
// appleseed.foundation headers.
#include "foundation/image/color.h"
#include "foundation/image/colorspace.h"
#include "foundation/image/tile.h"
#include "foundation/platform/compiler.h"
// Standard headers.
#include <cassert>
using namespace foundation;
using namespace std;
namespace renderer
{
ShadingResultFrameBuffer::ShadingResultFrameBuffer(
const size_t width,
const size_t height,
const size_t aov_count,
const Filter2d& filter)
: FilteredTile(
width,
height,
4 + aov_count * 3,
filter)
, m_aov_count(aov_count)
, m_scratch(4 + aov_count * 3)
{
}
ShadingResultFrameBuffer::ShadingResultFrameBuffer(
const size_t width,
const size_t height,
const size_t aov_count,
const AABB2u& crop_window,
const Filter2d& filter)
: FilteredTile(
width,
height,
4 + aov_count * 3,
crop_window,
filter)
, m_aov_count(aov_count)
, m_scratch(4 + aov_count * 3)
{
}
void ShadingResultFrameBuffer::add(
const double x,
const double y,
const ShadingResult& sample)
{
assert(sample.m_color_space == ColorSpaceLinearRGB);
float* ptr = &m_scratch[0];
*ptr++ = sample.m_alpha[0];
*ptr++ = sample.m_color[0];
*ptr++ = sample.m_color[1];
*ptr++ = sample.m_color[2];
for (size_t i = 0; i < m_aov_count; ++i)
{
*ptr++ = sample.m_aovs[i][0];
*ptr++ = sample.m_aovs[i][1];
*ptr++ = sample.m_aovs[i][2];
}
FilteredTile::add(x, y, &m_scratch[0]);
}
void ShadingResultFrameBuffer::merge(
const size_t dest_x,
const size_t dest_y,
const ShadingResultFrameBuffer& source,
const size_t source_x,
const size_t source_y,
const float scaling)
{
assert(m_channel_count == source.m_channel_count);
const float* RESTRICT source_ptr = source.pixel(source_x, source_y);
float* RESTRICT dest_ptr = pixel(dest_x, dest_y);
for (size_t i = 0; i < m_channel_count; ++i)
dest_ptr[i] += source_ptr[i] * scaling;
}
void ShadingResultFrameBuffer::develop_to_tile_premult_alpha(
Tile& tile,
TileStack& aov_tiles) const
{
const float* ptr = pixel(0);
for (size_t y = 0; y < m_height; ++y)
{
for (size_t x = 0; x < m_width; ++x)
{
const float weight = *ptr++;
const float rcp_weight = weight == 0.0f ? 0.0f : 1.0f / weight;
const float alpha = *ptr++;
const Color4f color(ptr[0], ptr[1], ptr[2], alpha);
tile.set_pixel(x, y, color * rcp_weight);
ptr += 3;
for (size_t i = 0; i < m_aov_count; ++i)
{
const Color4f aov(ptr[0], ptr[1], ptr[2], alpha);
aov_tiles.set_pixel(x, y, i, aov * rcp_weight);
ptr += 3;
}
}
}
}
void ShadingResultFrameBuffer::develop_to_tile_straight_alpha(
Tile& tile,
TileStack& aov_tiles) const
{
const float* ptr = pixel(0);
for (size_t y = 0; y < m_height; ++y)
{
for (size_t x = 0; x < m_width; ++x)
{
const float weight = *ptr++;
const float rcp_weight = weight == 0.0f ? 0.0f : 1.0f / weight;
const float alpha = *ptr++;
const float rcp_weight_alpha = alpha == 0.0f ? 0.0f : 1.0f / alpha;
Color4f color(ptr[0], ptr[1], ptr[2], alpha);
color.rgb() *= rcp_weight_alpha;
color.a *= rcp_weight;
tile.set_pixel(x, y, color);
ptr += 3;
for (size_t i = 0; i < m_aov_count; ++i)
{
Color4f aov(ptr[0], ptr[1], ptr[2], alpha);
aov.rgb() *= rcp_weight_alpha;
aov.a *= rcp_weight;
aov_tiles.set_pixel(x, y, i, aov);
ptr += 3;
}
}
}
}
} // namespace renderer
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_setup_runtime_wakeup_mode.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_setup_runtime_wakeup_mode.H
/// @brief describes HWP interface that configures runtime wakeup mode of core.
///
/// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot
//
#include <p9_setup_runtime_wakeup_mode.H>
#include <p9_quad_scom_addresses.H>
enum
{
RUN_TIME_WAKEUP_MODE_BIT_POS = 3,
HV_COMPATIBILITY_MODE_BIT_POS = 4,
};
fapi2::ReturnCode p9_setup_runtime_wakeup_mode(
const fapi2::Target < fapi2::TARGET_TYPE_PROC_CHIP>& i_procTarget )
{
FAPI_INF("> p9_setup_runtime_wakeup_mode" );
fapi2::buffer<uint64_t> l_wakeupMode;
uint8_t l_smfEnabled;
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
auto l_coreList =
i_procTarget.getChildren<fapi2::TARGET_TYPE_CORE>(fapi2::TARGET_STATE_FUNCTIONAL);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SMF_ENABLED,
FAPI_SYSTEM,
l_smfEnabled),
"Error from FAPI_ATTR_GET for attribute ATTR_SMF_ENABLED ");
FAPI_DBG("SMF Status : %s", l_smfEnabled ? "Enabled" : "Disabled" );
for( auto core : l_coreList )
{
FAPI_TRY(fapi2::getScom(i_procTarget, C_CPPM_CPMMR, l_wakeupMode),
"Failed To Read CPMMR");
FAPI_DBG( "Initial CPMMR Value 0x%016llx", l_wakeupMode );
if( l_smfEnabled )
{
//Wakeup in Ultravisor mode
l_wakeupMode.clearBit( RUN_TIME_WAKEUP_MODE_BIT_POS );
l_wakeupMode.clearBit( HV_COMPATIBILITY_MODE_BIT_POS );
}
else
{
//Wakeup in Hypervisor mode
l_wakeupMode.setBit( RUN_TIME_WAKEUP_MODE_BIT_POS );
l_wakeupMode.setBit( HV_COMPATIBILITY_MODE_BIT_POS );
}
FAPI_TRY(fapi2::putScom(core, C_CPPM_CPMMR, l_wakeupMode),
"Failed To Write CPMMR");
FAPI_DBG( "Final CPMMR Value 0x%016llx", l_wakeupMode );
}
fapi_try_exit:
FAPI_INF("< p9_setup_runtime_wakeup_mode" );
return fapi2::current_err;
}
<commit_msg>UV Support: Fixed target issue in setup runtime wakeup mode HWP.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_setup_runtime_wakeup_mode.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_setup_runtime_wakeup_mode.H
/// @brief describes HWP interface that configures runtime wakeup mode of core.
///
/// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot
//
#include <p9_setup_runtime_wakeup_mode.H>
#include <p9_quad_scom_addresses.H>
enum
{
RUN_TIME_WAKEUP_MODE_BIT_POS = 3,
HV_COMPATIBILITY_MODE_BIT_POS = 4,
};
fapi2::ReturnCode p9_setup_runtime_wakeup_mode(
const fapi2::Target < fapi2::TARGET_TYPE_PROC_CHIP>& i_procTarget )
{
FAPI_INF("> p9_setup_runtime_wakeup_mode" );
fapi2::buffer<uint64_t> l_wakeupMode;
uint8_t l_smfEnabled;
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
auto l_coreList =
i_procTarget.getChildren<fapi2::TARGET_TYPE_CORE>(fapi2::TARGET_STATE_FUNCTIONAL);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SMF_ENABLED,
FAPI_SYSTEM,
l_smfEnabled),
"Error from FAPI_ATTR_GET for attribute ATTR_SMF_ENABLED ");
FAPI_DBG("SMF Status : %s", l_smfEnabled ? "Enabled" : "Disabled" );
for( auto core : l_coreList )
{
FAPI_TRY(fapi2::getScom( core, C_CPPM_CPMMR, l_wakeupMode),
"Failed To Read CPMMR");
FAPI_DBG( "Initial CPMMR Value 0x%016llx", l_wakeupMode );
if( l_smfEnabled )
{
//Wakeup in Ultravisor mode
l_wakeupMode.clearBit( RUN_TIME_WAKEUP_MODE_BIT_POS );
l_wakeupMode.clearBit( HV_COMPATIBILITY_MODE_BIT_POS );
}
else
{
//Wakeup in Hypervisor mode
l_wakeupMode.setBit( RUN_TIME_WAKEUP_MODE_BIT_POS );
l_wakeupMode.setBit( HV_COMPATIBILITY_MODE_BIT_POS );
}
FAPI_TRY(fapi2::putScom(core, C_CPPM_CPMMR, l_wakeupMode),
"Failed To Write CPMMR");
FAPI_DBG( "Final CPMMR Value 0x%016llx", l_wakeupMode );
}
fapi_try_exit:
FAPI_INF("< p9_setup_runtime_wakeup_mode" );
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>#pragma once
#include "detect_type.hpp"
#include "lubee/meta/enable_if.hpp"
#include "lubee/none.hpp"
#include "argholder.hpp"
#include <utility>
#include "none.hpp"
namespace spi {
template <class... Ts>
auto construct(Ts&&... ts) {
return ArgHolder<decltype(ts)...>(std::forward<Ts>(ts)...);
}
template <class P>
using IsRP = std::integral_constant<bool, std::is_reference<P>{} || std::is_pointer<P>{}>;
namespace opt_tmp {
template <class T>
struct alignas(alignof(T)) Buffer {
uint8_t _data[sizeof(T)];
Buffer() = default;
template <class T2>
Buffer(T2&& t) {
new(ptr()) T(std::forward<T2>(t));
}
T* ptr() noexcept {
// Debug時は中身が有効かチェック
#ifdef DEBUG
#endif
return reinterpret_cast<T*>(_data);
}
const T* ptr() const noexcept {
// Debug時は中身が有効かチェック
#ifdef DEBUG
#endif
return reinterpret_cast<const T*>(_data);
}
T& get() noexcept {
return *ptr();
}
const T& get() const noexcept {
return *ptr();
}
template <class... Ts>
void ctor(Ts&&... ts) {
new(ptr()) T(std::forward<Ts>(ts)...);
}
void dtor() noexcept {
ptr()->~T();
}
#define NOEXCEPT_WHEN_RAW(t) noexcept(noexcept(IsRP<t>{}))
template <class T2>
Buffer& operator = (T2&& t) NOEXCEPT_WHEN_RAW(T2) {
get() = std::forward<T2>(t);
return *this;
}
#undef NOEXCEPT_WHEN_RAW
template <class Ar, class T2>
friend void serialize(Ar&, Buffer<T2>&);
};
template <class T>
struct Buffer<T&> {
T* _data;
Buffer() = default;
Buffer(T& t) noexcept: _data(&t) {}
T* ptr() noexcept {
return _data;
}
const T* ptr() const noexcept {
return _data;
}
T& get() noexcept {
return *ptr();
}
const T& get() const noexcept {
return *ptr();
}
void ctor() noexcept {}
void ctor(T& t) noexcept{
_data = &t;
}
void dtor() noexcept {}
Buffer& operator = (T& t) noexcept {
_data = &t;
return *this;
}
template <class Ar, class T2>
friend void serialize(Ar&, opt_tmp::Buffer<T2&>&);
};
template <class T>
struct Buffer<T*> {
T* _data;
Buffer() = default;
Buffer(T* t) noexcept: _data(t) {}
T* ptr() noexcept {
return _data;
}
const T* ptr() const noexcept {
return _data;
}
T*& get() noexcept {
return _data;
}
T* const& get() const noexcept {
return _data;
}
void ctor() noexcept {}
void ctor(T* t) noexcept {
_data = t;
}
void dtor() noexcept {}
Buffer& operator = (T* t) noexcept {
_data = t;
return *this;
}
template <class Ar, class T2>
friend void serialize(Ar&, opt_tmp::Buffer<T2*>&);
};
}
template <class T>
class Optional {
private:
using value_t = T;
constexpr static bool Is_RP = IsRP<T>{};
using Buffer = opt_tmp::Buffer<T>;
Buffer _buffer;
bool _bInit;
void _force_release() noexcept {
D_Assert0(_bInit);
_buffer.dtor();
_bInit = false;
}
void _release() noexcept {
if(_bInit)
_force_release();
}
value_t&& _takeOut() && noexcept {
return std::move(get());
}
const value_t& _takeOut() const& noexcept {
return get();
}
constexpr bool isRvalue() && noexcept {
return true;
}
constexpr bool isRvalue() const& noexcept {
return false;
}
public:
const static struct _AsInitialized{} AsInitialized;
//! コンストラクタは呼ばないが初期化された物として扱う
/*! ユーザーが自分でコンストラクタを呼ばないとエラーになる */
Optional(_AsInitialized) noexcept: _bInit(true) {}
Optional(const Optional& opt):
_bInit(opt._bInit)
{
if(_bInit) {
_buffer.ctor(opt._buffer.get());
}
}
Optional(Optional&& opt) noexcept:
_bInit(opt._bInit)
{
if(_bInit) {
_buffer.ctor(std::move(opt)._takeOut());
opt._bInit = false;
}
}
template <class T2, ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))>
Optional(T2&& v) noexcept(!IsRP<T2>{}):
_buffer(std::forward<T2>(v)),
_bInit(true)
{}
template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>
Optional(T2&& v) noexcept(!IsRP<T2>{}):
_bInit(v._bInit)
{
if(_bInit) {
const bool bR = std::forward<T2>(v).isRvalue();
_buffer.ctor(std::forward<T2>(v)._takeOut());
if(bR)
v._bInit = false;
}
}
//! デフォルト初期化: 中身は無効
Optional() noexcept: _bInit(false) {}
//! none_tを渡して初期化するとデフォルトと同じ挙動
Optional(none_t) noexcept: Optional() {}
~Optional() {
_release();
}
decltype(auto) get() & noexcept {
return _buffer.get();
}
decltype(auto) get() const& noexcept {
return _buffer.get();
}
decltype(auto) get() && noexcept {
return std::move(_buffer.get());
}
decltype(auto) operator * () & noexcept { return get(); }
decltype(auto) operator * () const& noexcept { return get(); }
decltype(auto) operator * () && noexcept { return std::move(get()); }
explicit operator bool () const noexcept {
return _bInit;
}
decltype(auto) operator -> () noexcept {
return _buffer.ptr();
}
decltype(auto) operator -> () const noexcept {
return _buffer.ptr();
}
bool operator == (const Optional& t) const noexcept {
const bool b = _bInit;
if(b == t._bInit) {
if(b)
return get() == t.get();
return true;
}
return false;
}
bool operator != (const Optional& t) const noexcept {
return !(this->operator == (t));
}
Optional& operator = (none_t) noexcept {
_release();
return *this;
}
template <class T2>
bool construct(std::true_type, T2&& t) {
_buffer.ctor(std::forward<T2>(t));
return true;
}
template <class T2>
bool construct(std::false_type, T2&&) {
_buffer.ctor();
return false;
}
template <
class T2,
ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))
>
Optional& operator = (T2&& t) {
if(!_bInit) {
_bInit = true;
using CanConstruct = std::is_constructible<value_t, decltype(std::forward<T2>(t))>;
if(construct(CanConstruct{}, std::forward<T2>(t)))
return *this;
}
_buffer = std::forward<T2>(t);
return *this;
}
template <class... Ts>
Optional& operator = (ArgHolder<Ts...>&& ah) {
if(_bInit)
_release();
const auto fn = [&buff = _buffer](auto&&... ts) {
buff.ctor(std::forward<decltype(ts)>(ts)...);
};
ah.inorder(fn);
_bInit = true;
return *this;
}
template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>
Optional& operator = (T2&& t) noexcept(Is_RP) {
if(!t)
_release();
else {
_bInit = true;
_buffer = std::forward<T2>(t).get();
}
return *this;
}
template <class Ar, class T2>
friend void load(Ar&, Optional<T2>&);
template <class Ar, class T2>
friend void save(Ar&, const Optional<T2>&);
};
template <class T>
const typename Optional<T>::_AsInitialized Optional<T>::AsInitialized{};
}
<commit_msg>Optional: リファクタリング<commit_after>#pragma once
#include "detect_type.hpp"
#include "lubee/meta/enable_if.hpp"
#include "lubee/none.hpp"
#include "argholder.hpp"
#include <utility>
#include "none.hpp"
namespace spi {
template <class... Ts>
auto construct(Ts&&... ts) {
return ArgHolder<decltype(ts)...>(std::forward<Ts>(ts)...);
}
template <class P>
using IsRP = std::integral_constant<bool, std::is_reference<P>{} || std::is_pointer<P>{}>;
namespace opt_tmp {
template <class T>
struct alignas(alignof(T)) Buffer {
uint8_t _data[sizeof(T)];
Buffer() = default;
template <class T2>
Buffer(T2&& t) {
new(ptr()) T(std::forward<T2>(t));
}
T* ptr() noexcept {
// Debug時は中身が有効かチェック
#ifdef DEBUG
#endif
return reinterpret_cast<T*>(_data);
}
const T* ptr() const noexcept {
// Debug時は中身が有効かチェック
#ifdef DEBUG
#endif
return reinterpret_cast<const T*>(_data);
}
T& get() noexcept {
return *ptr();
}
const T& get() const noexcept {
return *ptr();
}
template <class... Ts>
void ctor(Ts&&... ts) noexcept(noexcept(new T(std::forward<Ts>(ts)...))) {
new(ptr()) T(std::forward<Ts>(ts)...);
}
void dtor() noexcept {
ptr()->~T();
}
#define NOEXCEPT_WHEN_RAW(t) noexcept(noexcept(IsRP<t>{}))
template <class T2>
Buffer& operator = (T2&& t) NOEXCEPT_WHEN_RAW(T2) {
get() = std::forward<T2>(t);
return *this;
}
#undef NOEXCEPT_WHEN_RAW
template <class Ar, class T2>
friend void serialize(Ar&, Buffer<T2>&);
};
template <class T>
struct Buffer<T&> {
T* _data;
Buffer() = default;
Buffer(T& t) noexcept: _data(&t) {}
T* ptr() noexcept {
return _data;
}
const T* ptr() const noexcept {
return _data;
}
T& get() noexcept {
return *ptr();
}
const T& get() const noexcept {
return *ptr();
}
void ctor() noexcept {}
void ctor(T& t) noexcept{
_data = &t;
}
void dtor() noexcept {}
Buffer& operator = (T& t) noexcept {
_data = &t;
return *this;
}
template <class Ar, class T2>
friend void serialize(Ar&, opt_tmp::Buffer<T2&>&);
};
template <class T>
struct Buffer<T*> {
T* _data;
Buffer() = default;
Buffer(T* t) noexcept: _data(t) {}
T* ptr() noexcept {
return _data;
}
const T* ptr() const noexcept {
return _data;
}
T*& get() noexcept {
return _data;
}
T* const& get() const noexcept {
return _data;
}
void ctor() noexcept {}
void ctor(T* t) noexcept {
_data = t;
}
void dtor() noexcept {}
Buffer& operator = (T* t) noexcept {
_data = t;
return *this;
}
template <class Ar, class T2>
friend void serialize(Ar&, opt_tmp::Buffer<T2*>&);
};
}
template <class T>
class Optional {
private:
using value_t = T;
constexpr static bool Is_RP = IsRP<T>{};
using Buffer = opt_tmp::Buffer<T>;
Buffer _buffer;
bool _bInit;
void _force_release() noexcept {
D_Assert0(_bInit);
_buffer.dtor();
_bInit = false;
}
void _release() noexcept {
if(_bInit)
_force_release();
}
constexpr bool isRvalue() && noexcept {
return true;
}
constexpr bool isRvalue() const& noexcept {
return false;
}
template <class T2>
bool _construct(std::true_type, T2&& t) {
_buffer.ctor(std::forward<T2>(t));
return true;
}
template <class T2>
bool _construct(std::false_type, T2&&) {
_buffer.ctor();
return false;
}
public:
const static struct _AsInitialized{} AsInitialized;
//! コンストラクタは呼ばないが初期化された物として扱う
/*! ユーザーが自分でコンストラクタを呼ばないとエラーになる */
Optional(_AsInitialized) noexcept:
_bInit(true)
{}
Optional(const Optional& opt):
_bInit(opt._bInit)
{
if(_bInit) {
_buffer.ctor(opt._buffer.get());
}
}
Optional(Optional&& opt) noexcept:
_bInit(opt._bInit)
{
if(_bInit) {
_buffer.ctor(std::move(opt).get());
opt._bInit = false;
}
}
template <class T2, ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))>
Optional(T2&& v) noexcept(noexcept(Buffer(std::forward<T2>(v)))):
_buffer(std::forward<T2>(v)),
_bInit(true)
{}
template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>
Optional(T2&& v) noexcept(noexcept(std::declval<Buffer>().ctor(std::forward<T2>(v).get()))):
_bInit(v._bInit)
{
if(_bInit) {
const bool bR = std::forward<T2>(v).isRvalue();
_buffer.ctor(std::forward<T2>(v).get());
if(bR)
v._bInit = false;
}
}
//! デフォルト初期化: 中身は無効
Optional() noexcept:
_bInit(false)
{}
//! none_tを渡して初期化するとデフォルトと同じ挙動
Optional(none_t) noexcept:
Optional()
{}
~Optional() {
_release();
}
decltype(auto) get() & noexcept {
return _buffer.get();
}
decltype(auto) get() const& noexcept {
return _buffer.get();
}
decltype(auto) get() && noexcept {
return std::move(_buffer.get());
}
decltype(auto) operator * () & noexcept {
return get();
}
decltype(auto) operator * () const& noexcept {
return get();
}
decltype(auto) operator * () && noexcept {
return std::move(get());
}
explicit operator bool () const noexcept {
return _bInit;
}
decltype(auto) operator -> () noexcept {
return _buffer.ptr();
}
decltype(auto) operator -> () const noexcept {
return _buffer.ptr();
}
bool operator == (const Optional& t) const noexcept {
const bool b = _bInit;
if(b == t._bInit) {
if(b)
return get() == t.get();
return true;
}
return false;
}
bool operator != (const Optional& t) const noexcept {
return !(this->operator == (t));
}
Optional& operator = (none_t) noexcept {
_release();
return *this;
}
template <
class T2,
ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))
>
Optional& operator = (T2&& t) {
if(!_bInit) {
_bInit = true;
using CanConstruct = std::is_constructible<value_t, decltype(std::forward<T2>(t))>;
if(_construct(CanConstruct{}, std::forward<T2>(t)))
return *this;
}
_buffer = std::forward<T2>(t);
return *this;
}
template <class... Ts>
Optional& operator = (ArgHolder<Ts...>&& ah) {
if(_bInit)
_release();
const auto fn = [&buff = _buffer](auto&&... ts) {
buff.ctor(std::forward<decltype(ts)>(ts)...);
};
ah.inorder(fn);
_bInit = true;
return *this;
}
template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>
Optional& operator = (T2&& t) noexcept(Is_RP) {
if(!t)
_release();
else {
_bInit = true;
_buffer = std::forward<T2>(t).get();
}
return *this;
}
template <class Ar, class T2>
friend void load(Ar&, Optional<T2>&);
template <class Ar, class T2>
friend void save(Ar&, const Optional<T2>&);
};
template <class T>
const typename Optional<T>::_AsInitialized Optional<T>::AsInitialized{};
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "stateseditorview.h"
#include "stateseditorwidget.h"
#include "stateseditormodel.h"
#include <customnotifications.h>
#include <rewritingexception.h>
#include <QPainter>
#include <QTimerEvent>
#include <QMessageBox>
#include <QDebug>
#include <math.h>
#include <nodemetainfo.h>
#include <variantproperty.h>
#include <nodelistproperty.h>
namespace QmlDesigner {
/**
We always have 'one' current state, where we get updates from (see sceneChanged()). In case
the current state is the base state, we render the base state + all other states.
*/
StatesEditorView::StatesEditorView(QObject *parent) :
QmlModelView(parent),
m_statesEditorModel(new StatesEditorModel(this)),
m_lastIndex(-1)
{
Q_ASSERT(m_statesEditorModel);
// base state
}
StatesEditorWidget *StatesEditorView::widget()
{
if (m_statesEditorWidget.isNull())
m_statesEditorWidget = new StatesEditorWidget(this, m_statesEditorModel.data());
return m_statesEditorWidget.data();
}
void StatesEditorView::removeState(int nodeId)
{
try {
if (nodeId > 0 && hasModelNodeForInternalId(nodeId)) {
ModelNode stateNode(modelNodeForInternalId(nodeId));
Q_ASSERT(stateNode.metaInfo().isSubclassOf("QtQuick/State", 4, 7));
NodeListProperty parentProperty = stateNode.parentProperty().toNodeListProperty();
if (parentProperty.count() <= 1) {
setCurrentState(baseState());
} else if (parentProperty.isValid()){
int index = parentProperty.indexOf(stateNode);
if (index == 0) {
setCurrentState(parentProperty.at(1));
} else {
setCurrentState(parentProperty.at(index - 1));
}
}
stateNode.destroy();
}
} catch (RewritingException &e) {
QMessageBox::warning(0, "Error", e.description());
}
}
void StatesEditorView::synchonizeCurrentStateFromWidget()
{
if (!model())
return;
int internalId = m_statesEditorWidget->currentStateInternalId();
if (internalId > 0 && hasModelNodeForInternalId(internalId)) {
ModelNode node = modelNodeForInternalId(internalId);
QmlModelState modelState(node);
if (modelState.isValid() && modelState != currentState())
setCurrentState(modelState);
} else {
setCurrentState(baseState());
}
}
void StatesEditorView::createNewState()
{
if (currentState().isBaseState()) {
addState();
} else {
duplicateCurrentState();
}
}
void StatesEditorView::addState()
{
// can happen when root node is e.g. a ListModel
if (!rootQmlItemNode().isValid())
return;
QStringList modelStateNames = rootStateGroup().names();
QString newStateName;
int index = 1;
while (true) {
newStateName = tr("State%1", "Default name for newly created states").arg(index++);
if (!modelStateNames.contains(newStateName))
break;
}
try {
if (rootStateGroup().allStates().count() < 1)
model()->addImport(Import::createLibraryImport("QtQuick", "1.0"));
ModelNode newState = rootStateGroup().addState(newStateName);
setCurrentState(newState);
} catch (RewritingException &e) {
QMessageBox::warning(0, "Error", e.description());
}
}
void StatesEditorView::resetModel()
{
if (m_statesEditorModel)
m_statesEditorModel->reset();
if (m_statesEditorWidget) {
if (currentState().isBaseState()) {
m_statesEditorWidget->setCurrentStateInternalId(currentState().modelNode().internalId());
} else {
m_statesEditorWidget->setCurrentStateInternalId(0);
}
}
}
void StatesEditorView::duplicateCurrentState()
{
QmlModelState state = currentState();
Q_ASSERT(!state.isBaseState());
QString newName = state.name();
// Strip out numbers at the end of the string
QRegExp regEx(QString("[0-9]+$"));
int numberIndex = newName.indexOf(regEx);
if ((numberIndex != -1) && (numberIndex+regEx.matchedLength()==newName.length()))
newName = newName.left(numberIndex);
int i = 1;
QStringList stateNames = rootStateGroup().names();
while (stateNames.contains(newName + QString::number(i)))
i++;
QmlModelState newState = state.duplicate(newName + QString::number(i));
setCurrentState(newState);
}
bool StatesEditorView::validStateName(const QString &name) const
{
if (name == tr("base state"))
return false;
QList<QmlModelState> modelStates = rootStateGroup().allStates();
foreach (const QmlModelState &state, modelStates) {
if (state.name() == name)
return false;
}
return true;
}
void StatesEditorView::renameState(int nodeId, const QString &newName)
{
if (hasModelNodeForInternalId(nodeId)) {
QmlModelState state(modelNodeForInternalId(nodeId));
try {
if (state.isValid() && state.name() != newName) {
// Jump to base state for the change
QmlModelState oldState = currentState();
setCurrentState(baseState());
state.setName(newName);
setCurrentState(oldState);
}
} catch (RewritingException &e) {
QMessageBox::warning(0, "Error", e.description());
}
}
}
void StatesEditorView::modelAttached(Model *model)
{
if (model == QmlModelView::model())
return;
Q_ASSERT(model);
QmlModelView::modelAttached(model);
if (m_statesEditorWidget)
m_statesEditorWidget->setNodeInstanceView(nodeInstanceView());
resetModel();
}
void StatesEditorView::modelAboutToBeDetached(Model *model)
{
QmlModelView::modelAboutToBeDetached(model);
resetModel();
}
void StatesEditorView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &propertyList)
{
foreach (const AbstractProperty &property, propertyList) {
if (property.name() == "states" && property.parentModelNode().isRootNode())
m_statesEditorModel->reset();
}
}
void StatesEditorView::variantPropertiesChanged(const QList<VariantProperty> &propertyList, PropertyChangeFlags /*propertyChange*/)
{
}
void StatesEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
if (removedNode.hasParentProperty()) {
const NodeAbstractProperty propertyParent = removedNode.parentProperty();
if (propertyParent.parentModelNode().isRootNode() && propertyParent.name() == "states") {
m_lastIndex = propertyParent.indexOf(removedNode);
}
}
}
void StatesEditorView::nodeRemoved(const ModelNode & /*removedNode*/, const NodeAbstractProperty &parentProperty, PropertyChangeFlags /*propertyChange*/)
{
if (parentProperty.isValid() && parentProperty.parentModelNode().isRootNode() && parentProperty.name() == "states") {
m_statesEditorModel->removeState(m_lastIndex);
m_lastIndex = -1;
}
}
void StatesEditorView::nodeAboutToBeReparented(const ModelNode &node, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags /*propertyChange*/)
{
if (oldPropertyParent.isValid() && oldPropertyParent.parentModelNode().isRootNode() && oldPropertyParent.name() == "states")
m_lastIndex = oldPropertyParent.indexOf(node);
}
void StatesEditorView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags /*propertyChange*/)
{
if (oldPropertyParent.isValid() && oldPropertyParent.parentModelNode().isRootNode() && oldPropertyParent.name() == "states")
m_statesEditorModel->removeState(m_lastIndex);
m_lastIndex = -1;
if (newPropertyParent.isValid() && newPropertyParent.parentModelNode().isRootNode() && newPropertyParent.name() == "states") {
int index = newPropertyParent.indexOf(node);
m_statesEditorModel->insertState(index);
}
}
void StatesEditorView::nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode & /*movedNode*/, int /*oldIndex*/)
{
if (listProperty.isValid() && listProperty.parentModelNode().isRootNode() && listProperty.name() == "states")
resetModel();
}
void StatesEditorView::nodeInstancePropertyChanged(const ModelNode &node, const QString &propertyName)
{
// sets currentState() used in sceneChanged
QmlModelView::nodeInstancePropertyChanged(node, propertyName);
}
void StatesEditorView::stateChanged(const QmlModelState &newQmlModelState, const QmlModelState &oldQmlModelState)
{
if (newQmlModelState.isBaseState()) {
m_statesEditorWidget->setCurrentStateInternalId(0);
} else {
m_statesEditorWidget->setCurrentStateInternalId(newQmlModelState.modelNode().internalId());
}
QmlModelView::stateChanged(newQmlModelState, oldQmlModelState);
}
void StatesEditorView::transformChanged(const QmlObjectNode &qmlObjectNode, const QString &propertyName)
{
QmlModelView::transformChanged(qmlObjectNode, propertyName);
}
void StatesEditorView::parentChanged(const QmlObjectNode &qmlObjectNode)
{
QmlModelView::parentChanged(qmlObjectNode);
}
void StatesEditorView::otherPropertyChanged(const QmlObjectNode &qmlObjectNode, const QString &propertyName)
{
QmlModelView::otherPropertyChanged(qmlObjectNode, propertyName);
}
void StatesEditorView::customNotification(const AbstractView * view, const QString & identifier, const QList<ModelNode> & nodeList, const QList<QVariant> &imageList)
{
if (identifier == "__instance preview image changed__") {
int minimumIndex = 10000;
int maximumIndex = -1;
foreach(const ModelNode &node, nodeList) {
if (node.isRootNode()) {
minimumIndex = qMin(minimumIndex, 0);
maximumIndex = qMax(maximumIndex, 0);
} else {
int index = rootStateGroup().allStates().indexOf(QmlModelState(node)) + 1;
if (index > 0) {
minimumIndex = qMin(minimumIndex, index);
maximumIndex = qMax(maximumIndex, index);
}
}
}
if (maximumIndex >= 0)
m_statesEditorModel->updateState(minimumIndex, maximumIndex);
} else {
QmlModelView::customNotification(view, identifier, nodeList, imageList);
}
}
void StatesEditorView::scriptFunctionsChanged(const ModelNode &node, const QStringList &scriptFunctionList)
{
QmlModelView::scriptFunctionsChanged(node, scriptFunctionList);
}
void StatesEditorView::nodeIdChanged(const ModelNode &/*node*/, const QString &/*newId*/, const QString &/*oldId*/)
{
}
void StatesEditorView::bindingPropertiesChanged(const QList<BindingProperty> &/*propertyList*/, PropertyChangeFlags /*propertyChange*/)
{
}
void StatesEditorView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/)
{
}
} // namespace QmlDesigner
<commit_msg>QmlDesigner: Fix warning<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "stateseditorview.h"
#include "stateseditorwidget.h"
#include "stateseditormodel.h"
#include <customnotifications.h>
#include <rewritingexception.h>
#include <QPainter>
#include <QTimerEvent>
#include <QMessageBox>
#include <QDebug>
#include <math.h>
#include <nodemetainfo.h>
#include <variantproperty.h>
#include <nodelistproperty.h>
namespace QmlDesigner {
/**
We always have 'one' current state, where we get updates from (see sceneChanged()). In case
the current state is the base state, we render the base state + all other states.
*/
StatesEditorView::StatesEditorView(QObject *parent) :
QmlModelView(parent),
m_statesEditorModel(new StatesEditorModel(this)),
m_lastIndex(-1)
{
Q_ASSERT(m_statesEditorModel);
// base state
}
StatesEditorWidget *StatesEditorView::widget()
{
if (m_statesEditorWidget.isNull())
m_statesEditorWidget = new StatesEditorWidget(this, m_statesEditorModel.data());
return m_statesEditorWidget.data();
}
void StatesEditorView::removeState(int nodeId)
{
try {
if (nodeId > 0 && hasModelNodeForInternalId(nodeId)) {
ModelNode stateNode(modelNodeForInternalId(nodeId));
Q_ASSERT(stateNode.metaInfo().isSubclassOf("QtQuick/State", 4, 7));
NodeListProperty parentProperty = stateNode.parentProperty().toNodeListProperty();
if (parentProperty.count() <= 1) {
setCurrentState(baseState());
} else if (parentProperty.isValid()){
int index = parentProperty.indexOf(stateNode);
if (index == 0) {
setCurrentState(parentProperty.at(1));
} else {
setCurrentState(parentProperty.at(index - 1));
}
}
stateNode.destroy();
}
} catch (RewritingException &e) {
QMessageBox::warning(0, "Error", e.description());
}
}
void StatesEditorView::synchonizeCurrentStateFromWidget()
{
if (!model())
return;
int internalId = m_statesEditorWidget->currentStateInternalId();
if (internalId > 0 && hasModelNodeForInternalId(internalId)) {
ModelNode node = modelNodeForInternalId(internalId);
QmlModelState modelState(node);
if (modelState.isValid() && modelState != currentState())
setCurrentState(modelState);
} else {
setCurrentState(baseState());
}
}
void StatesEditorView::createNewState()
{
if (currentState().isBaseState()) {
addState();
} else {
duplicateCurrentState();
}
}
void StatesEditorView::addState()
{
// can happen when root node is e.g. a ListModel
if (!rootQmlItemNode().isValid())
return;
QStringList modelStateNames = rootStateGroup().names();
QString newStateName;
int index = 1;
while (true) {
newStateName = tr("State%1", "Default name for newly created states").arg(index++);
if (!modelStateNames.contains(newStateName))
break;
}
try {
if (rootStateGroup().allStates().count() < 1)
model()->addImport(Import::createLibraryImport("QtQuick", "1.0"));
ModelNode newState = rootStateGroup().addState(newStateName);
setCurrentState(newState);
} catch (RewritingException &e) {
QMessageBox::warning(0, "Error", e.description());
}
}
void StatesEditorView::resetModel()
{
if (m_statesEditorModel)
m_statesEditorModel->reset();
if (m_statesEditorWidget) {
if (currentState().isBaseState()) {
m_statesEditorWidget->setCurrentStateInternalId(currentState().modelNode().internalId());
} else {
m_statesEditorWidget->setCurrentStateInternalId(0);
}
}
}
void StatesEditorView::duplicateCurrentState()
{
QmlModelState state = currentState();
Q_ASSERT(!state.isBaseState());
QString newName = state.name();
// Strip out numbers at the end of the string
QRegExp regEx(QString("[0-9]+$"));
int numberIndex = newName.indexOf(regEx);
if ((numberIndex != -1) && (numberIndex+regEx.matchedLength()==newName.length()))
newName = newName.left(numberIndex);
int i = 1;
QStringList stateNames = rootStateGroup().names();
while (stateNames.contains(newName + QString::number(i)))
i++;
QmlModelState newState = state.duplicate(newName + QString::number(i));
setCurrentState(newState);
}
bool StatesEditorView::validStateName(const QString &name) const
{
if (name == tr("base state"))
return false;
QList<QmlModelState> modelStates = rootStateGroup().allStates();
foreach (const QmlModelState &state, modelStates) {
if (state.name() == name)
return false;
}
return true;
}
void StatesEditorView::renameState(int nodeId, const QString &newName)
{
if (hasModelNodeForInternalId(nodeId)) {
QmlModelState state(modelNodeForInternalId(nodeId));
try {
if (state.isValid() && state.name() != newName) {
// Jump to base state for the change
QmlModelState oldState = currentState();
setCurrentState(baseState());
state.setName(newName);
setCurrentState(oldState);
}
} catch (RewritingException &e) {
QMessageBox::warning(0, "Error", e.description());
}
}
}
void StatesEditorView::modelAttached(Model *model)
{
if (model == QmlModelView::model())
return;
Q_ASSERT(model);
QmlModelView::modelAttached(model);
if (m_statesEditorWidget)
m_statesEditorWidget->setNodeInstanceView(nodeInstanceView());
resetModel();
}
void StatesEditorView::modelAboutToBeDetached(Model *model)
{
QmlModelView::modelAboutToBeDetached(model);
resetModel();
}
void StatesEditorView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &propertyList)
{
foreach (const AbstractProperty &property, propertyList) {
if (property.name() == "states" && property.parentModelNode().isRootNode())
m_statesEditorModel->reset();
}
}
void StatesEditorView::variantPropertiesChanged(const QList<VariantProperty> &/*propertyList*/, PropertyChangeFlags /*propertyChange*/)
{
}
void StatesEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
if (removedNode.hasParentProperty()) {
const NodeAbstractProperty propertyParent = removedNode.parentProperty();
if (propertyParent.parentModelNode().isRootNode() && propertyParent.name() == "states") {
m_lastIndex = propertyParent.indexOf(removedNode);
}
}
}
void StatesEditorView::nodeRemoved(const ModelNode & /*removedNode*/, const NodeAbstractProperty &parentProperty, PropertyChangeFlags /*propertyChange*/)
{
if (parentProperty.isValid() && parentProperty.parentModelNode().isRootNode() && parentProperty.name() == "states") {
m_statesEditorModel->removeState(m_lastIndex);
m_lastIndex = -1;
}
}
void StatesEditorView::nodeAboutToBeReparented(const ModelNode &node, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags /*propertyChange*/)
{
if (oldPropertyParent.isValid() && oldPropertyParent.parentModelNode().isRootNode() && oldPropertyParent.name() == "states")
m_lastIndex = oldPropertyParent.indexOf(node);
}
void StatesEditorView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags /*propertyChange*/)
{
if (oldPropertyParent.isValid() && oldPropertyParent.parentModelNode().isRootNode() && oldPropertyParent.name() == "states")
m_statesEditorModel->removeState(m_lastIndex);
m_lastIndex = -1;
if (newPropertyParent.isValid() && newPropertyParent.parentModelNode().isRootNode() && newPropertyParent.name() == "states") {
int index = newPropertyParent.indexOf(node);
m_statesEditorModel->insertState(index);
}
}
void StatesEditorView::nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode & /*movedNode*/, int /*oldIndex*/)
{
if (listProperty.isValid() && listProperty.parentModelNode().isRootNode() && listProperty.name() == "states")
resetModel();
}
void StatesEditorView::nodeInstancePropertyChanged(const ModelNode &node, const QString &propertyName)
{
// sets currentState() used in sceneChanged
QmlModelView::nodeInstancePropertyChanged(node, propertyName);
}
void StatesEditorView::stateChanged(const QmlModelState &newQmlModelState, const QmlModelState &oldQmlModelState)
{
if (newQmlModelState.isBaseState()) {
m_statesEditorWidget->setCurrentStateInternalId(0);
} else {
m_statesEditorWidget->setCurrentStateInternalId(newQmlModelState.modelNode().internalId());
}
QmlModelView::stateChanged(newQmlModelState, oldQmlModelState);
}
void StatesEditorView::transformChanged(const QmlObjectNode &qmlObjectNode, const QString &propertyName)
{
QmlModelView::transformChanged(qmlObjectNode, propertyName);
}
void StatesEditorView::parentChanged(const QmlObjectNode &qmlObjectNode)
{
QmlModelView::parentChanged(qmlObjectNode);
}
void StatesEditorView::otherPropertyChanged(const QmlObjectNode &qmlObjectNode, const QString &propertyName)
{
QmlModelView::otherPropertyChanged(qmlObjectNode, propertyName);
}
void StatesEditorView::customNotification(const AbstractView * view, const QString & identifier, const QList<ModelNode> & nodeList, const QList<QVariant> &imageList)
{
if (identifier == "__instance preview image changed__") {
int minimumIndex = 10000;
int maximumIndex = -1;
foreach(const ModelNode &node, nodeList) {
if (node.isRootNode()) {
minimumIndex = qMin(minimumIndex, 0);
maximumIndex = qMax(maximumIndex, 0);
} else {
int index = rootStateGroup().allStates().indexOf(QmlModelState(node)) + 1;
if (index > 0) {
minimumIndex = qMin(minimumIndex, index);
maximumIndex = qMax(maximumIndex, index);
}
}
}
if (maximumIndex >= 0)
m_statesEditorModel->updateState(minimumIndex, maximumIndex);
} else {
QmlModelView::customNotification(view, identifier, nodeList, imageList);
}
}
void StatesEditorView::scriptFunctionsChanged(const ModelNode &node, const QStringList &scriptFunctionList)
{
QmlModelView::scriptFunctionsChanged(node, scriptFunctionList);
}
void StatesEditorView::nodeIdChanged(const ModelNode &/*node*/, const QString &/*newId*/, const QString &/*oldId*/)
{
}
void StatesEditorView::bindingPropertiesChanged(const QList<BindingProperty> &/*propertyList*/, PropertyChangeFlags /*propertyChange*/)
{
}
void StatesEditorView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/)
{
}
} // namespace QmlDesigner
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Christian Loose <christian.loose@hamburg.de>
*
* 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 "discountmarkdownconverter.h"
extern "C" {
#ifdef Q_OS_WIN
#include <Windows.h>
#endif
#include <mkdio.h>
}
#include "markdowndocument.h"
#include "template/htmltemplate.h"
class DiscountMarkdownDocument : public MarkdownDocument
{
public:
explicit DiscountMarkdownDocument(MMIOT *document_) : discountDocument(document_) {}
~DiscountMarkdownDocument() { mkd_cleanup(discountDocument); }
MMIOT *document() const { return discountDocument; }
private:
MMIOT *discountDocument;
};
DiscountMarkdownConverter::DiscountMarkdownConverter()
{
}
MarkdownDocument *DiscountMarkdownConverter::createDocument(const QString &text, ConverterOptions options)
{
MMIOT *doc = 0;
if (text.length() > 0) {
QString markdownText(text);
// text has to always end with a line break,
// otherwise characters are missing in HTML
if (!markdownText.endsWith('\n')) {
markdownText.append('\n');
}
unsigned long converterOptions = translateConverterOptions(options);
QByteArray utf8Data = markdownText.toUtf8();
doc = mkd_string(utf8Data, utf8Data.length(), converterOptions);
mkd_compile(doc, converterOptions);
}
return new DiscountMarkdownDocument(doc);
}
QString DiscountMarkdownConverter::renderAsHtml(MarkdownDocument *document)
{
QString html;
if (document) {
DiscountMarkdownDocument *doc = dynamic_cast<DiscountMarkdownDocument*>(document);
if (doc && doc->document()) {
char *out;
mkd_document(doc->document(), &out);
html = QString::fromUtf8(out);
}
}
return html;
}
QString DiscountMarkdownConverter::renderAsTableOfContents(MarkdownDocument *document)
{
QString toc;
if (document) {
DiscountMarkdownDocument *doc = dynamic_cast<DiscountMarkdownDocument*>(document);
if (doc && doc->document()) {
// generate table of contents
char *out;
mkd_toc(doc->document(), &out);
toc = QString::fromUtf8(out);
}
}
return toc;
}
Template *DiscountMarkdownConverter::templateRenderer() const
{
static HtmlTemplate htmlTemplate;
return &htmlTemplate;
}
MarkdownConverter::ConverterOptions DiscountMarkdownConverter::supportedOptions() const
{
return MarkdownConverter::AutolinkOption |
MarkdownConverter::NoStrikethroughOption |
MarkdownConverter::NoAlphaListOption |
MarkdownConverter::NoDefinitionListOption |
MarkdownConverter::NoSmartypantsOption |
MarkdownConverter::ExtraFootnoteOption |
MarkdownConverter::NoSuperscriptOption;
}
unsigned long DiscountMarkdownConverter::translateConverterOptions(ConverterOptions options) const
{
unsigned long converterOptions = MKD_TOC | MKD_NOSTYLE;
// autolink
if (options.testFlag(MarkdownConverter::AutolinkOption)) {
converterOptions |= MKD_AUTOLINK;
}
// strikethrough
if (options.testFlag(MarkdownConverter::NoStrikethroughOption)) {
converterOptions |= MKD_NOSTRIKETHROUGH;
}
// alphabetic lists
if (options.testFlag(MarkdownConverter::NoAlphaListOption)) {
converterOptions |= MKD_NOALPHALIST;
}
// definition lists
if (options.testFlag(MarkdownConverter::NoDefinitionListOption)) {
converterOptions |= MKD_NODLIST;
}
// SmartyPants
if (options.testFlag(MarkdownConverter::NoSmartypantsOption)) {
converterOptions |= MKD_NOPANTS;
}
// Footnotes
if (options.testFlag(MarkdownConverter::ExtraFootnoteOption)) {
converterOptions |= MKD_EXTRA_FOOTNOTE;
}
// Superscript
if (options.testFlag(MarkdownConverter::NoSuperscriptOption)) {
converterOptions |= MKD_NOSUPERSCRIPT;
}
return converterOptions;
}
<commit_msg>allow compilation with old markdown<commit_after>/*
* Copyright 2013 Christian Loose <christian.loose@hamburg.de>
*
* 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 "discountmarkdownconverter.h"
extern "C" {
#ifdef Q_OS_WIN
#include <Windows.h>
#endif
#include <mkdio.h>
}
#include "markdowndocument.h"
#include "template/htmltemplate.h"
class DiscountMarkdownDocument : public MarkdownDocument
{
public:
explicit DiscountMarkdownDocument(MMIOT *document_) : discountDocument(document_) {}
~DiscountMarkdownDocument() { mkd_cleanup(discountDocument); }
MMIOT *document() const { return discountDocument; }
private:
MMIOT *discountDocument;
};
DiscountMarkdownConverter::DiscountMarkdownConverter()
{
}
MarkdownDocument *DiscountMarkdownConverter::createDocument(const QString &text, ConverterOptions options)
{
MMIOT *doc = 0;
if (text.length() > 0) {
QString markdownText(text);
// text has to always end with a line break,
// otherwise characters are missing in HTML
if (!markdownText.endsWith('\n')) {
markdownText.append('\n');
}
unsigned long converterOptions = translateConverterOptions(options);
QByteArray utf8Data = markdownText.toUtf8();
doc = mkd_string(utf8Data, utf8Data.length(), converterOptions);
mkd_compile(doc, converterOptions);
}
return new DiscountMarkdownDocument(doc);
}
QString DiscountMarkdownConverter::renderAsHtml(MarkdownDocument *document)
{
QString html;
if (document) {
DiscountMarkdownDocument *doc = dynamic_cast<DiscountMarkdownDocument*>(document);
if (doc && doc->document()) {
char *out;
mkd_document(doc->document(), &out);
html = QString::fromUtf8(out);
}
}
return html;
}
QString DiscountMarkdownConverter::renderAsTableOfContents(MarkdownDocument *document)
{
QString toc;
if (document) {
DiscountMarkdownDocument *doc = dynamic_cast<DiscountMarkdownDocument*>(document);
if (doc && doc->document()) {
// generate table of contents
char *out;
mkd_toc(doc->document(), &out);
toc = QString::fromUtf8(out);
}
}
return toc;
}
Template *DiscountMarkdownConverter::templateRenderer() const
{
static HtmlTemplate htmlTemplate;
return &htmlTemplate;
}
MarkdownConverter::ConverterOptions DiscountMarkdownConverter::supportedOptions() const
{
return MarkdownConverter::AutolinkOption |
MarkdownConverter::NoStrikethroughOption |
MarkdownConverter::NoAlphaListOption |
MarkdownConverter::NoDefinitionListOption |
MarkdownConverter::NoSmartypantsOption |
MarkdownConverter::ExtraFootnoteOption |
MarkdownConverter::NoSuperscriptOption;
}
unsigned long DiscountMarkdownConverter::translateConverterOptions(ConverterOptions options) const
{
unsigned long converterOptions = MKD_TOC;
#ifdef MKD_NOSTYLE
converterOptions |= MKD_NOSTYLE;
#endif
// autolink
if (options.testFlag(MarkdownConverter::AutolinkOption)) {
converterOptions |= MKD_AUTOLINK;
}
// strikethrough
if (options.testFlag(MarkdownConverter::NoStrikethroughOption)) {
converterOptions |= MKD_NOSTRIKETHROUGH;
}
// alphabetic lists
if (options.testFlag(MarkdownConverter::NoAlphaListOption)) {
converterOptions |= MKD_NOALPHALIST;
}
// definition lists
if (options.testFlag(MarkdownConverter::NoDefinitionListOption)) {
converterOptions |= MKD_NODLIST;
}
// SmartyPants
if (options.testFlag(MarkdownConverter::NoSmartypantsOption)) {
converterOptions |= MKD_NOPANTS;
}
// Footnotes
if (options.testFlag(MarkdownConverter::ExtraFootnoteOption)) {
converterOptions |= MKD_EXTRA_FOOTNOTE;
}
// Superscript
if (options.testFlag(MarkdownConverter::NoSuperscriptOption)) {
converterOptions |= MKD_NOSUPERSCRIPT;
}
return converterOptions;
}
<|endoftext|> |
<commit_before>#include <functional>
#include "extensions/quic_listeners/quiche/platform/flags_impl.h"
#include "test/test_common/logging.h"
#include "gtest/gtest.h"
#include "quiche/spdy/platform/api/spdy_arraysize.h"
#include "quiche/spdy/platform/api/spdy_bug_tracker.h"
#include "quiche/spdy/platform/api/spdy_containers.h"
#include "quiche/spdy/platform/api/spdy_endianness_util.h"
#include "quiche/spdy/platform/api/spdy_estimate_memory_usage.h"
#include "quiche/spdy/platform/api/spdy_flags.h"
#include "quiche/spdy/platform/api/spdy_logging.h"
#include "quiche/spdy/platform/api/spdy_ptr_util.h"
#include "quiche/spdy/platform/api/spdy_string.h"
#include "quiche/spdy/platform/api/spdy_string_piece.h"
#include "quiche/spdy/platform/api/spdy_test_helpers.h"
// Basic tests to validate functioning of the QUICHE spdy platform
// implementation. For platform APIs in which the implementation is a simple
// typedef/passthrough to a std:: or absl:: construct, the tests are kept
// minimal, and serve primarily to verify the APIs compile and link without
// issue.
namespace Envoy {
namespace Extensions {
namespace QuicListeners {
namespace Quiche {
namespace {
TEST(SpdyPlatformTest, SpdyArraysize) {
int array[] = {0, 1, 2, 3, 4};
EXPECT_EQ(5, SPDY_ARRAYSIZE(array));
}
TEST(SpdyPlatformTest, SpdyBugTracker) {
EXPECT_DEBUG_DEATH(SPDY_BUG << "Here is a bug,", " bug");
EXPECT_DEBUG_DEATH(SPDY_BUG_IF(true) << "There is a bug,", " bug");
EXPECT_LOG_NOT_CONTAINS("error", "", SPDY_BUG_IF(false) << "A feature is not a bug.");
EXPECT_EQ(true, FLAGS_spdy_always_log_bugs_for_tests);
}
TEST(SpdyPlatformTest, SpdyHashMap) {
spdy::SpdyHashMap<spdy::SpdyString, int> hmap;
hmap.insert({"foo", 2});
EXPECT_EQ(2, hmap["foo"]);
}
TEST(SpdyPlatformTest, SpdyHashSet) {
spdy::SpdyHashSet<spdy::SpdyString, spdy::SpdyHash<spdy::SpdyString>,
std::equal_to<spdy::SpdyString>>
hset({"foo", "bar"});
EXPECT_EQ(1, hset.count("bar"));
EXPECT_EQ(0, hset.count("qux"));
}
TEST(SpdyPlatformTest, SpdyEndianness) {
EXPECT_EQ(0x1234, spdy::SpdyNetToHost16(spdy::SpdyHostToNet16(0x1234)));
EXPECT_EQ(0x12345678, spdy::SpdyNetToHost32(spdy::SpdyHostToNet32(0x12345678)));
}
TEST(SpdyPlatformTest, SpdyEstimateMemoryUsage) {
spdy::SpdyString s = "foo";
// Stubbed out to always return 0.
EXPECT_EQ(0, spdy::SpdyEstimateMemoryUsage(s));
}
TEST(SpdyPlatformTest, SpdyLog) {
// SPDY_LOG macros are defined to QUIC_LOG macros, which is tested in
// QuicPlatformTest. Here we just make sure SPDY_LOG macros compile.
SPDY_LOG(INFO) << "INFO log may not show up by default.";
SPDY_LOG(ERROR) << "ERROR log should show up by default.";
// VLOG is only emitted if INFO is enabled and verbosity level is high enough.
SPDY_VLOG(1) << "VLOG(1)";
SPDY_DLOG(INFO) << "DLOG(INFO)";
SPDY_DLOG(ERROR) << "DLOG(ERROR)";
SPDY_DLOG_IF(ERROR, true) << "DLOG_IF(ERROR, true)";
SPDY_DLOG_IF(ERROR, false) << "DLOG_IF(ERROR, false)";
SPDY_DVLOG(2) << "DVLOG(2)";
SPDY_DVLOG_IF(3, true) << "DVLOG_IF(3, true)";
SPDY_DVLOG_IF(4, false) << "DVLOG_IF(4, false)";
}
TEST(SpdyPlatformTest, SpdyMakeUnique) {
auto p = spdy::SpdyMakeUnique<int>(4);
EXPECT_EQ(4, *p);
}
TEST(SpdyPlatformTest, SpdyWrapUnique) {
auto p = spdy::SpdyWrapUnique(new int(6));
EXPECT_EQ(6, *p);
}
TEST(SpdyPlatformTest, SpdyString) {
spdy::SpdyString s = "foo";
EXPECT_EQ('o', s[1]);
}
TEST(SpdyPlatformTest, SpdyStringPiece) {
spdy::SpdyString s = "bar";
spdy::SpdyStringPiece sp(s);
EXPECT_EQ('b', sp[0]);
}
TEST(SpdyPlatformTest, SpdyTestHelpers) {
auto bug = [](const char* error_message) { SPDY_BUG << error_message; };
EXPECT_SPDY_BUG(bug("bug one is expected"), "bug one");
EXPECT_SPDY_BUG(bug("bug two is expected"), "bug two");
}
TEST(SpdyPlatformTest, SpdyFlags) {
auto& flag_registry = quiche::FlagRegistry::GetInstance();
flag_registry.ResetFlags();
EXPECT_FALSE(GetSpdyReloadableFlag(spdy_testonly_default_false));
EXPECT_FALSE(GetSpdyRestartFlag(spdy_testonly_default_false));
flag_registry.FindFlag("spdy_reloadable_flag_spdy_testonly_default_false")
->SetValueFromString("true");
EXPECT_TRUE(GetSpdyReloadableFlag(spdy_testonly_default_false));
EXPECT_FALSE(GetSpdyRestartFlag(spdy_testonly_default_false));
flag_registry.ResetFlags();
flag_registry.FindFlag("spdy_restart_flag_spdy_testonly_default_false")
->SetValueFromString("yes");
EXPECT_FALSE(GetSpdyReloadableFlag(spdy_testonly_default_false));
EXPECT_TRUE(GetSpdyRestartFlag(spdy_testonly_default_false));
}
} // namespace
} // namespace Quiche
} // namespace QuicListeners
} // namespace Extensions
} // namespace Envoy
<commit_msg>Do not use SpdyString wrapper for std::string. (#7854)<commit_after>#include <functional>
#include <string>
#include "extensions/quic_listeners/quiche/platform/flags_impl.h"
#include "test/test_common/logging.h"
#include "gtest/gtest.h"
#include "quiche/spdy/platform/api/spdy_arraysize.h"
#include "quiche/spdy/platform/api/spdy_bug_tracker.h"
#include "quiche/spdy/platform/api/spdy_containers.h"
#include "quiche/spdy/platform/api/spdy_endianness_util.h"
#include "quiche/spdy/platform/api/spdy_estimate_memory_usage.h"
#include "quiche/spdy/platform/api/spdy_flags.h"
#include "quiche/spdy/platform/api/spdy_logging.h"
#include "quiche/spdy/platform/api/spdy_ptr_util.h"
#include "quiche/spdy/platform/api/spdy_string_piece.h"
#include "quiche/spdy/platform/api/spdy_test_helpers.h"
// Basic tests to validate functioning of the QUICHE spdy platform
// implementation. For platform APIs in which the implementation is a simple
// typedef/passthrough to a std:: or absl:: construct, the tests are kept
// minimal, and serve primarily to verify the APIs compile and link without
// issue.
namespace Envoy {
namespace Extensions {
namespace QuicListeners {
namespace Quiche {
namespace {
TEST(SpdyPlatformTest, SpdyArraysize) {
int array[] = {0, 1, 2, 3, 4};
EXPECT_EQ(5, SPDY_ARRAYSIZE(array));
}
TEST(SpdyPlatformTest, SpdyBugTracker) {
EXPECT_DEBUG_DEATH(SPDY_BUG << "Here is a bug,", " bug");
EXPECT_DEBUG_DEATH(SPDY_BUG_IF(true) << "There is a bug,", " bug");
EXPECT_LOG_NOT_CONTAINS("error", "", SPDY_BUG_IF(false) << "A feature is not a bug.");
EXPECT_EQ(true, FLAGS_spdy_always_log_bugs_for_tests);
}
TEST(SpdyPlatformTest, SpdyHashMap) {
spdy::SpdyHashMap<std::string, int> hmap;
hmap.insert({"foo", 2});
EXPECT_EQ(2, hmap["foo"]);
}
TEST(SpdyPlatformTest, SpdyHashSet) {
spdy::SpdyHashSet<std::string, spdy::SpdyHash<std::string>, std::equal_to<std::string>> hset(
{"foo", "bar"});
EXPECT_EQ(1, hset.count("bar"));
EXPECT_EQ(0, hset.count("qux"));
}
TEST(SpdyPlatformTest, SpdyEndianness) {
EXPECT_EQ(0x1234, spdy::SpdyNetToHost16(spdy::SpdyHostToNet16(0x1234)));
EXPECT_EQ(0x12345678, spdy::SpdyNetToHost32(spdy::SpdyHostToNet32(0x12345678)));
}
TEST(SpdyPlatformTest, SpdyEstimateMemoryUsage) {
std::string s = "foo";
// Stubbed out to always return 0.
EXPECT_EQ(0, spdy::SpdyEstimateMemoryUsage(s));
}
TEST(SpdyPlatformTest, SpdyLog) {
// SPDY_LOG macros are defined to QUIC_LOG macros, which is tested in
// QuicPlatformTest. Here we just make sure SPDY_LOG macros compile.
SPDY_LOG(INFO) << "INFO log may not show up by default.";
SPDY_LOG(ERROR) << "ERROR log should show up by default.";
// VLOG is only emitted if INFO is enabled and verbosity level is high enough.
SPDY_VLOG(1) << "VLOG(1)";
SPDY_DLOG(INFO) << "DLOG(INFO)";
SPDY_DLOG(ERROR) << "DLOG(ERROR)";
SPDY_DLOG_IF(ERROR, true) << "DLOG_IF(ERROR, true)";
SPDY_DLOG_IF(ERROR, false) << "DLOG_IF(ERROR, false)";
SPDY_DVLOG(2) << "DVLOG(2)";
SPDY_DVLOG_IF(3, true) << "DVLOG_IF(3, true)";
SPDY_DVLOG_IF(4, false) << "DVLOG_IF(4, false)";
}
TEST(SpdyPlatformTest, SpdyMakeUnique) {
auto p = spdy::SpdyMakeUnique<int>(4);
EXPECT_EQ(4, *p);
}
TEST(SpdyPlatformTest, SpdyWrapUnique) {
auto p = spdy::SpdyWrapUnique(new int(6));
EXPECT_EQ(6, *p);
}
TEST(SpdyPlatformTest, SpdyString) {
std::string s = "foo";
EXPECT_EQ('o', s[1]);
}
TEST(SpdyPlatformTest, SpdyStringPiece) {
std::string s = "bar";
spdy::SpdyStringPiece sp(s);
EXPECT_EQ('b', sp[0]);
}
TEST(SpdyPlatformTest, SpdyTestHelpers) {
auto bug = [](const char* error_message) { SPDY_BUG << error_message; };
EXPECT_SPDY_BUG(bug("bug one is expected"), "bug one");
EXPECT_SPDY_BUG(bug("bug two is expected"), "bug two");
}
TEST(SpdyPlatformTest, SpdyFlags) {
auto& flag_registry = quiche::FlagRegistry::GetInstance();
flag_registry.ResetFlags();
EXPECT_FALSE(GetSpdyReloadableFlag(spdy_testonly_default_false));
EXPECT_FALSE(GetSpdyRestartFlag(spdy_testonly_default_false));
flag_registry.FindFlag("spdy_reloadable_flag_spdy_testonly_default_false")
->SetValueFromString("true");
EXPECT_TRUE(GetSpdyReloadableFlag(spdy_testonly_default_false));
EXPECT_FALSE(GetSpdyRestartFlag(spdy_testonly_default_false));
flag_registry.ResetFlags();
flag_registry.FindFlag("spdy_restart_flag_spdy_testonly_default_false")
->SetValueFromString("yes");
EXPECT_FALSE(GetSpdyReloadableFlag(spdy_testonly_default_false));
EXPECT_TRUE(GetSpdyRestartFlag(spdy_testonly_default_false));
}
} // namespace
} // namespace Quiche
} // namespace QuicListeners
} // namespace Extensions
} // namespace Envoy
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QStandardPaths>
#include <QtQuick/QQuickView>
#include <QtQuick/QQuickItem>
#include <QDir>
#include <QMenu>
#include <QAction>
#include <QDesktopServices>
#include <QCloseEvent>
#include <QSystemTrayIcon>
#include <QMessageBox>
#include <QtQml/qqml.h>
#include "wqmlfile.h"
#include "wqmlsystem.h"
mainWindow::mainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::mainWindow){
ui->setupUi(this);
appConfig();
addTrayIcon();
addQmlApis();
addTreeRightClickMenu();
openWidgetsInFile();
}
mainWindow::~mainWindow()
{
delete ui;
}
void mainWindow::addQmlApis(){
qmlRegisterType<wqmlfile>("com.widgetci.file", 1, 0, "WFile");
qmlRegisterType<wqmlsystem>("com.widgetci.system", 1, 0, "WSystem");
}
void mainWindow::openWidgetsInFile(){
widgetsDataSettings = new QSettings(appDataDir + "/widgets.ini", QSettings::IniFormat);
int count = 0;
for(auto e : widgetsDataSettings->childGroups()){
widgetsDataSettings->beginGroup(e);
int wx = widgetsDataSettings->value("x", -1000).toInt();
int wy = widgetsDataSettings->value("y", -1000).toInt();
bool visible = widgetsDataSettings->value("visible", false).toBool();
widgetsDataSettings->endGroup();
if(visible){
toggleWidget(e, wx, wy);
count++;
}
}
if(count == 0) this->show(); // if no widgets visible, show the form.
}
// Toggle widgets
void mainWindow::toggleWidget(QTreeWidgetItem *item, int wx = -1000, int wy = -1000){
QString wid_filename = item->text(0);
// If widget not exists. Create one.
if(!map_widgetList.contains(wid_filename)){
// Load configs about the widget
QMap<QString, QVariant> widConf = getWidgetSettings(item->text(0));
//Check if has spesific coordinates
if(wx == -1000 || wy == -1000){
wx = widConf["x"].toInt();
wy = widConf["y"].toInt();
}
// Add the widget
WWidget *wid = new WWidget(QUrl::fromLocalFile(widgetsDir + "/" + wid_filename + "/main.qml"), wid_filename, wx, wy);
wid->toggleZPos(widConf["z-pos"].toInt());
wid->widgetSettings = widgetsDataSettings;
// Check for errors. (File not found etc...)
if( wid->status() == QQuickView::Error ){
QString errorString = "";
for (int i = 0; i < wid->errors().length(); ++i) {
errorString.append(wid->errors().at(i).toString());
}
errorString.append(tr("\n\nPlease try to fix the error and refresh the list"));
item->setBackground(0, QBrush(QColor(160,0,0,255)));
item->setTextColor(0, QColor(180, 180, 180, 255));
item->setSelected(false);
QMessageBox::warning(this, tr("An error occured"), errorString, QMessageBox::Ok);
return;
}else if(wid->status() == QQuickView::Ready){
item->setBackground(0, QBrush(QColor(0,0,0,0)));
}
map_widgetList.insert(wid->filename, wid);
item->setIcon(0, ico_toggleon);
item->setTextColor(0, colorOn);
// Delete the widget from list when destroyed
disconnect(wid, &QQuickWindow::destroyed, 0, 0);
connect(wid, &QQuickWindow::destroyed, [=]{
if(map_widgetList.contains(wid->filename)){
if(!CLOSING) saveWidgetSettings(wid->filename); // Save settings before closing the widgets.
map_widgetList.remove(wid->filename);
QList<QTreeWidgetItem *> item_lst = obj_widgetList->findItems(wid->filename, Qt::MatchExactly, 0);
if(item_lst.length() > 0){
item_lst[0]->setTextColor(0, colorOff);
item_lst[0]->setIcon(0, ico_toggleoff);
}
}
});
}else if(map_widgetList.contains(wid_filename)){
delete map_widgetList[wid_filename];
}
}
void mainWindow::toggleWidget(QString widgetName, int wx = -1000, int wy = -1000){
QList <QTreeWidgetItem *> items = obj_widgetList->findItems(widgetName, Qt::MatchExactly, 0);
if(items.length() > 0){
toggleWidget(items[0], wx, wy);
}
}
QMap<QString, QVariant> mainWindow::getWidgetSettings(QString widgetname){
QMap<QString, QVariant> mapTmp;
widgetsDataSettings->beginGroup(widgetname);
mapTmp["x"] = widgetsDataSettings->value("x", -1000);
mapTmp["y"] = widgetsDataSettings->value("y", -1000);
mapTmp["visible"] = widgetsDataSettings->value("visible", false);
mapTmp["z-pos"] = widgetsDataSettings->value("z-pos", 0);
mapTmp["lock"] = widgetsDataSettings->value("lock", false);
widgetsDataSettings->endGroup();
return mapTmp;
}
void mainWindow::saveWidgetSettings(QString widgetname){
widgetsDataSettings->beginGroup(widgetname);
widgetsDataSettings->setValue("x", map_widgetList[widgetname]->x());
widgetsDataSettings->setValue("y", map_widgetList[widgetname]->y());
widgetsDataSettings->setValue("visible", map_widgetList[widgetname]->isVisible());
widgetsDataSettings->setValue("z-pos", map_widgetList[widgetname]->z_pos);
widgetsDataSettings->endGroup();
widgetsDataSettings->sync();
}
void mainWindow::updateWidgetList(QTreeWidget* widgetList_obj){
QMap<QString, WWidget *> tmpWidgetsMap(map_widgetList);
widgetList_obj->clear();
QDir dir(widgetsDir);
QStringList folderList = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
// Close all widgets (to open just available ones later)
for(QString e : map_widgetList.keys()){
delete map_widgetList.value(e);
}
// Add folders one by one
for(int i=0; i<folderList.length(); i++){
QString folder = folderList.at(i);
QTreeWidgetItem* item = new QTreeWidgetItem(widgetList_obj);
item->setText(0, folder);
item->setIcon(0, ico_toggleoff);
if(tmpWidgetsMap.contains(folder)){
toggleWidget(folder);
//item->setIcon(0, ico_toggleon);
}
}
// Enable|Disable widgets by double clicking on themauto
disconnect(widgetList_obj, &QTreeWidget::itemActivated, 0, 0); // prevent multiple connections & runs
connect(widgetList_obj, &QTreeWidget::itemActivated, [=](QTreeWidgetItem* item) {
toggleWidget(item);
});
}
void mainWindow::addTreeRightClickMenu(){
// Initialize the variables
ico_toggleoff = QIcon(":/img/toggleoff.png");
ico_toggleon = QIcon(":/img/toggleon.png");
colorOn = QColor(0, 230, 0, 255);
colorOff = QColor(255, 255, 255, 255);
// QTreeWidget list object from ui:
obj_widgetList = ui->obj_widgetList;
// Update & Refresh the widgets
updateWidgetList(obj_widgetList);
// Right Click Menu
obj_widgetList->setContextMenuPolicy(Qt::CustomContextMenu);
menu_wlRightClick = new QMenu(this);
// Right Click Menu Actions
QAction* act_wlrc_ShowHide = new QAction(tr("Show"), this);
connect(act_wlrc_ShowHide, &QAction::triggered, [=]{
// Show/Hide Action
toggleWidget(obj_widgetList->currentItem());
});
QAction* act_wlrc_Edit = new QAction(tr("Edit"), this);
connect(act_wlrc_Edit, &QAction::triggered, [=]{
// Edit the widget file with default editor
QDesktopServices::openUrl(QUrl::fromLocalFile(widgetsDir + "/" + obj_widgetList->currentItem()->text(0) + "/main.qml"));
});
QAction* act_wlrc_Reload = new QAction(tr("Reload"), this);
connect(act_wlrc_Reload, &QAction::triggered, [=]{
// Reload the widget
if(map_widgetList.contains(obj_widgetList->currentItem()->text(0)))
map_widgetList.value(obj_widgetList->currentItem()->text(0))->reload();
});
QAction* act_wlrc_RefreshTheList = new QAction(tr("Refresh the list"), this);
connect(act_wlrc_RefreshTheList, &QAction::triggered, [=]{
// Refresh all the list.
updateWidgetList(obj_widgetList);
});
QAction* act_wlrc_Delete = new QAction(tr("Remove"), this);
connect(act_wlrc_Delete, &QAction::triggered, [=]{
if(map_widgetList.contains(obj_widgetList->currentItem()->text(0)))
toggleWidget(obj_widgetList->currentItem()->text(0));
delete obj_widgetList->currentItem();
obj_widgetList->clearSelection();
});
QAction* act_wlrc_DeleteDisk = new QAction(tr("Delete From Disk..."), this);
connect(act_wlrc_DeleteDisk, &QAction::triggered, [=]{
int answer = QMessageBox::warning(this, tr("Warning"), tr("The '%1' folder will be deleted from disk.\n\nAre you sure?").arg(obj_widgetList->currentItem()->text(0)), QMessageBox::Cancel | QMessageBox::Ok);
if(answer == QMessageBox::Ok){
QDir folder(widgetsDir + "/" + obj_widgetList->currentItem()->text(0));
if(folder.removeRecursively()){
QMessageBox::information(this, tr("Information"), tr("The folder has been deleted successfully."), QMessageBox::Ok);
if(map_widgetList.contains(obj_widgetList->currentItem()->text(0))){
toggleWidget(obj_widgetList->currentItem()->text(0));
updateWidgetList(obj_widgetList);
}
}else{
QMessageBox::critical(this, tr("Information"), tr("The folder couldn't be removed.\nCheck the folder and the files may be using by another program."), QMessageBox::Ok);
}
}
});
// Add Actions to the QTreeWidget's Right Click Menu
menu_wlRightClick->addAction(act_wlrc_ShowHide);
menu_wlRightClick->addSeparator();
menu_wlRightClick->addAction(act_wlrc_Reload);
menu_wlRightClick->addAction(act_wlrc_Edit);
menu_wlRightClick->addAction(act_wlrc_RefreshTheList);
menu_wlRightClick->addSeparator();
menu_wlRightClick->addAction(act_wlrc_Delete);
menu_wlRightClick->addAction(act_wlrc_DeleteDisk);
connect(obj_widgetList, &QTreeWidget::customContextMenuRequested, [=](const QPoint & pos) {
QPoint pt(pos);
pt.setX(pt.x()+2);
pt.setY(pt.y()+22);
QTreeWidgetItem *item = obj_widgetList->currentItem();
QString wid_filename = item->text(0);
if(!map_widgetList.contains(wid_filename)){
act_wlrc_ShowHide->setText(tr("Show"));
act_wlrc_Reload->setEnabled(false);
}else if(map_widgetList.contains(wid_filename)){
act_wlrc_ShowHide->setText(tr("Hide"));
act_wlrc_Reload->setEnabled(true);
}
menu_wlRightClick->exec( obj_widgetList->mapToGlobal(pt) );
});
}
void mainWindow::addActionsToTray(){
// Create Menu & Items
trayMenu = new QMenu(this);
QAction* openManager = new QAction(tr("Open Manager..."), this);
QAction* reloadAll = new QAction(tr("Reload All"), this);
QAction* quit = new QAction(tr("Quit"), this);
trayMenu->addAction(openManager);
trayMenu->addAction(reloadAll);
trayMenu->addSeparator();
trayMenu->addAction(quit);
// Connect
connect(openManager, &QAction::triggered, [=]{
this->setVisible(true);
this->raise();
QApplication::setActiveWindow(this);
});
connect(reloadAll, &QAction::triggered, [=]{
for(auto e : map_widgetList.keys()){
map_widgetList.value(e)->reload();
}
});
connect(quit, &QAction::triggered, [=]{
onAppQuit();
});
}
void mainWindow::addTrayIcon(){
// Add actions
addActionsToTray();
// Set the app icon
appIcon = new QIcon(":/img/icon.png");
setWindowIcon(*appIcon);
// Set the tray
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayMenu);
trayIcon->setIcon(*appIcon);
trayIcon->show();
connect(trayIcon, &QSystemTrayIcon::activated, [=](QSystemTrayIcon::ActivationReason reason){
if(reason == QSystemTrayIcon::DoubleClick){
this->setVisible(true);
this->raise();
QApplication::setActiveWindow(this);
}
});
}
void mainWindow::appConfig(){
// Set directory variables.
appDataDir = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)[0];
widgetsDir = appDataDir + "/widgets";
// Create the directory if not exists.
QDir dir(widgetsDir);
if(!dir.exists()){
QDir localdir(":/widgets/defaultwidgets/");
QStringList folderList = localdir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
// Copy the local folders one by one
QFile file;
for(int i=0; i<folderList.length(); i++){
QString folder = folderList.at(i);
//qDebug() << localdir.path() + folder << widgetsDir + "/" + folder;
dir.mkpath(widgetsDir + "/" + folder);
// Copy the files inside folder
QDir filedir(localdir.path() + "/" + folder);
QStringList filelist = filedir.entryList(QDir::Files | QDir::NoDotAndDotDot);
for (int a = 0; a < filelist.length(); ++a) {
file.copy(localdir.path() + "/" + folder + "/" + filelist.at(a), widgetsDir + "/" + folder + "/" + filelist.at(a));
}
}
}
}
void mainWindow::on_obj_showFolderBtn_clicked(){
QDesktopServices::openUrl(widgetsDir);
}
void mainWindow::on_obj_refreshWidgetListBtn_clicked(){
updateWidgetList(ui->obj_widgetList);
}
// Before the app quit
void mainWindow::onAppQuit(){
CLOSING = true;
// Close the widgets too.
for(auto e : map_widgetList.keys()){
// Save widget configs.
saveWidgetSettings(e);
// Destroy them.
delete map_widgetList.value(e);
}
QApplication::quit();
}
// Window Close Event
void mainWindow::closeEvent(QCloseEvent *event){
event->ignore();
this->setVisible(false);
}
<commit_msg>[FIXED] ReadOnly copied widget files at first opening. Now they are writeable.<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QStandardPaths>
#include <QtQuick/QQuickView>
#include <QtQuick/QQuickItem>
#include <QDir>
#include <QMenu>
#include <QAction>
#include <QDesktopServices>
#include <QCloseEvent>
#include <QSystemTrayIcon>
#include <QMessageBox>
#include <QtQml/qqml.h>
#include "wqmlfile.h"
#include "wqmlsystem.h"
mainWindow::mainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::mainWindow){
ui->setupUi(this);
appConfig();
addTrayIcon();
addQmlApis();
addTreeRightClickMenu();
openWidgetsInFile();
}
mainWindow::~mainWindow()
{
delete ui;
}
void mainWindow::addQmlApis(){
qmlRegisterType<wqmlfile>("com.widgetci.file", 1, 0, "WFile");
qmlRegisterType<wqmlsystem>("com.widgetci.system", 1, 0, "WSystem");
}
void mainWindow::openWidgetsInFile(){
widgetsDataSettings = new QSettings(appDataDir + "/widgets.ini", QSettings::IniFormat);
int count = 0;
for(auto e : widgetsDataSettings->childGroups()){
widgetsDataSettings->beginGroup(e);
int wx = widgetsDataSettings->value("x", -1000).toInt();
int wy = widgetsDataSettings->value("y", -1000).toInt();
bool visible = widgetsDataSettings->value("visible", false).toBool();
widgetsDataSettings->endGroup();
if(visible){
toggleWidget(e, wx, wy);
count++;
}
}
if(count == 0) this->show(); // if no widgets visible, show the form.
}
// Toggle widgets
void mainWindow::toggleWidget(QTreeWidgetItem *item, int wx = -1000, int wy = -1000){
QString wid_filename = item->text(0);
// If widget not exists. Create one.
if(!map_widgetList.contains(wid_filename)){
// Load configs about the widget
QMap<QString, QVariant> widConf = getWidgetSettings(item->text(0));
//Check if has spesific coordinates
if(wx == -1000 || wy == -1000){
wx = widConf["x"].toInt();
wy = widConf["y"].toInt();
}
// Add the widget
WWidget *wid = new WWidget(QUrl::fromLocalFile(widgetsDir + "/" + wid_filename + "/main.qml"), wid_filename, wx, wy);
wid->toggleZPos(widConf["z-pos"].toInt());
wid->widgetSettings = widgetsDataSettings;
// Check for errors. (File not found etc...)
if( wid->status() == QQuickView::Error ){
QString errorString = "";
for (int i = 0; i < wid->errors().length(); ++i) {
errorString.append(wid->errors().at(i).toString());
}
errorString.append(tr("\n\nPlease try to fix the error and refresh the list"));
item->setBackground(0, QBrush(QColor(160,0,0,255)));
item->setTextColor(0, QColor(180, 180, 180, 255));
item->setSelected(false);
QMessageBox::warning(this, tr("An error occured"), errorString, QMessageBox::Ok);
return;
}else if(wid->status() == QQuickView::Ready){
item->setBackground(0, QBrush(QColor(0,0,0,0)));
}
map_widgetList.insert(wid->filename, wid);
item->setIcon(0, ico_toggleon);
item->setTextColor(0, colorOn);
// Delete the widget from list when destroyed
disconnect(wid, &QQuickWindow::destroyed, 0, 0);
connect(wid, &QQuickWindow::destroyed, [=]{
if(map_widgetList.contains(wid->filename)){
if(!CLOSING) saveWidgetSettings(wid->filename); // Save settings before closing the widgets.
map_widgetList.remove(wid->filename);
QList<QTreeWidgetItem *> item_lst = obj_widgetList->findItems(wid->filename, Qt::MatchExactly, 0);
if(item_lst.length() > 0){
item_lst[0]->setTextColor(0, colorOff);
item_lst[0]->setIcon(0, ico_toggleoff);
}
}
});
}else if(map_widgetList.contains(wid_filename)){
delete map_widgetList[wid_filename];
}
}
void mainWindow::toggleWidget(QString widgetName, int wx = -1000, int wy = -1000){
QList <QTreeWidgetItem *> items = obj_widgetList->findItems(widgetName, Qt::MatchExactly, 0);
if(items.length() > 0){
toggleWidget(items[0], wx, wy);
}
}
QMap<QString, QVariant> mainWindow::getWidgetSettings(QString widgetname){
QMap<QString, QVariant> mapTmp;
widgetsDataSettings->beginGroup(widgetname);
mapTmp["x"] = widgetsDataSettings->value("x", -1000);
mapTmp["y"] = widgetsDataSettings->value("y", -1000);
mapTmp["visible"] = widgetsDataSettings->value("visible", false);
mapTmp["z-pos"] = widgetsDataSettings->value("z-pos", 0);
mapTmp["lock"] = widgetsDataSettings->value("lock", false);
widgetsDataSettings->endGroup();
return mapTmp;
}
void mainWindow::saveWidgetSettings(QString widgetname){
widgetsDataSettings->beginGroup(widgetname);
widgetsDataSettings->setValue("x", map_widgetList[widgetname]->x());
widgetsDataSettings->setValue("y", map_widgetList[widgetname]->y());
widgetsDataSettings->setValue("visible", map_widgetList[widgetname]->isVisible());
widgetsDataSettings->setValue("z-pos", map_widgetList[widgetname]->z_pos);
widgetsDataSettings->endGroup();
widgetsDataSettings->sync();
}
void mainWindow::updateWidgetList(QTreeWidget* widgetList_obj){
QMap<QString, WWidget *> tmpWidgetsMap(map_widgetList);
widgetList_obj->clear();
QDir dir(widgetsDir);
QStringList folderList = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
// Close all widgets (to open just available ones later)
for(QString e : map_widgetList.keys()){
delete map_widgetList.value(e);
}
// Add folders one by one
for(int i=0; i<folderList.length(); i++){
QString folder = folderList.at(i);
QTreeWidgetItem* item = new QTreeWidgetItem(widgetList_obj);
item->setText(0, folder);
item->setIcon(0, ico_toggleoff);
if(tmpWidgetsMap.contains(folder)){
toggleWidget(folder);
//item->setIcon(0, ico_toggleon);
}
}
// Enable|Disable widgets by double clicking on themauto
disconnect(widgetList_obj, &QTreeWidget::itemActivated, 0, 0); // prevent multiple connections & runs
connect(widgetList_obj, &QTreeWidget::itemActivated, [=](QTreeWidgetItem* item) {
toggleWidget(item);
});
}
void mainWindow::addTreeRightClickMenu(){
// Initialize the variables
ico_toggleoff = QIcon(":/img/toggleoff.png");
ico_toggleon = QIcon(":/img/toggleon.png");
colorOn = QColor(0, 230, 0, 255);
colorOff = QColor(255, 255, 255, 255);
// QTreeWidget list object from ui:
obj_widgetList = ui->obj_widgetList;
// Update & Refresh the widgets
updateWidgetList(obj_widgetList);
// Right Click Menu
obj_widgetList->setContextMenuPolicy(Qt::CustomContextMenu);
menu_wlRightClick = new QMenu(this);
// Right Click Menu Actions
QAction* act_wlrc_ShowHide = new QAction(tr("Show"), this);
connect(act_wlrc_ShowHide, &QAction::triggered, [=]{
// Show/Hide Action
toggleWidget(obj_widgetList->currentItem());
});
QAction* act_wlrc_Edit = new QAction(tr("Edit"), this);
connect(act_wlrc_Edit, &QAction::triggered, [=]{
// Edit the widget file with default editor
QDesktopServices::openUrl(QUrl::fromLocalFile(widgetsDir + "/" + obj_widgetList->currentItem()->text(0) + "/main.qml"));
});
QAction* act_wlrc_Reload = new QAction(tr("Reload"), this);
connect(act_wlrc_Reload, &QAction::triggered, [=]{
// Reload the widget
if(map_widgetList.contains(obj_widgetList->currentItem()->text(0)))
map_widgetList.value(obj_widgetList->currentItem()->text(0))->reload();
});
QAction* act_wlrc_RefreshTheList = new QAction(tr("Refresh the list"), this);
connect(act_wlrc_RefreshTheList, &QAction::triggered, [=]{
// Refresh all the list.
updateWidgetList(obj_widgetList);
});
QAction* act_wlrc_Delete = new QAction(tr("Remove"), this);
connect(act_wlrc_Delete, &QAction::triggered, [=]{
if(map_widgetList.contains(obj_widgetList->currentItem()->text(0)))
toggleWidget(obj_widgetList->currentItem()->text(0));
delete obj_widgetList->currentItem();
obj_widgetList->clearSelection();
});
QAction* act_wlrc_DeleteDisk = new QAction(tr("Delete From Disk..."), this);
connect(act_wlrc_DeleteDisk, &QAction::triggered, [=]{
int answer = QMessageBox::warning(this, tr("Warning"), tr("The '%1' folder will be deleted from disk.\n\nAre you sure?").arg(obj_widgetList->currentItem()->text(0)), QMessageBox::Cancel | QMessageBox::Ok);
if(answer == QMessageBox::Ok){
QDir folder(widgetsDir + "/" + obj_widgetList->currentItem()->text(0));
if(folder.removeRecursively()){
QMessageBox::information(this, tr("Information"), tr("The folder has been deleted successfully."), QMessageBox::Ok);
if(map_widgetList.contains(obj_widgetList->currentItem()->text(0))){
toggleWidget(obj_widgetList->currentItem()->text(0));
updateWidgetList(obj_widgetList);
}
}else{
QMessageBox::critical(this, tr("Information"), tr("The folder couldn't be removed.\nCheck the folder and the files may be using by another program."), QMessageBox::Ok);
}
}
});
// Add Actions to the QTreeWidget's Right Click Menu
menu_wlRightClick->addAction(act_wlrc_ShowHide);
menu_wlRightClick->addSeparator();
menu_wlRightClick->addAction(act_wlrc_Reload);
menu_wlRightClick->addAction(act_wlrc_Edit);
menu_wlRightClick->addAction(act_wlrc_RefreshTheList);
menu_wlRightClick->addSeparator();
menu_wlRightClick->addAction(act_wlrc_Delete);
menu_wlRightClick->addAction(act_wlrc_DeleteDisk);
connect(obj_widgetList, &QTreeWidget::customContextMenuRequested, [=](const QPoint & pos) {
QPoint pt(pos);
pt.setX(pt.x()+2);
pt.setY(pt.y()+22);
QTreeWidgetItem *item = obj_widgetList->currentItem();
QString wid_filename = item->text(0);
if(!map_widgetList.contains(wid_filename)){
act_wlrc_ShowHide->setText(tr("Show"));
act_wlrc_Reload->setEnabled(false);
}else if(map_widgetList.contains(wid_filename)){
act_wlrc_ShowHide->setText(tr("Hide"));
act_wlrc_Reload->setEnabled(true);
}
menu_wlRightClick->exec( obj_widgetList->mapToGlobal(pt) );
});
}
void mainWindow::addActionsToTray(){
// Create Menu & Items
trayMenu = new QMenu(this);
QAction* openManager = new QAction(tr("Open Manager..."), this);
QAction* reloadAll = new QAction(tr("Reload All"), this);
QAction* quit = new QAction(tr("Quit"), this);
trayMenu->addAction(openManager);
trayMenu->addAction(reloadAll);
trayMenu->addSeparator();
trayMenu->addAction(quit);
// Connect
connect(openManager, &QAction::triggered, [=]{
this->setVisible(true);
this->raise();
QApplication::setActiveWindow(this);
});
connect(reloadAll, &QAction::triggered, [=]{
for(auto e : map_widgetList.keys()){
map_widgetList.value(e)->reload();
}
});
connect(quit, &QAction::triggered, [=]{
onAppQuit();
});
}
void mainWindow::addTrayIcon(){
// Add actions
addActionsToTray();
// Set the app icon
appIcon = new QIcon(":/img/icon.png");
setWindowIcon(*appIcon);
// Set the tray
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayMenu);
trayIcon->setIcon(*appIcon);
trayIcon->show();
connect(trayIcon, &QSystemTrayIcon::activated, [=](QSystemTrayIcon::ActivationReason reason){
if(reason == QSystemTrayIcon::DoubleClick){
this->setVisible(true);
this->raise();
QApplication::setActiveWindow(this);
}
});
}
void mainWindow::appConfig(){
// Set directory variables.
appDataDir = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)[0];
widgetsDir = appDataDir + "/widgets";
// Create the directory if not exists.
QDir dir(widgetsDir);
if(!dir.exists()){
QDir localdir(":/widgets/defaultwidgets/");
QStringList folderList = localdir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
// Copy the local folders one by one
QFile file;
for(int i=0; i<folderList.length(); i++){
QString folder = folderList.at(i);
//qDebug() << localdir.path() + folder << widgetsDir + "/" + folder;
dir.mkpath(widgetsDir + "/" + folder);
// Copy the files inside folder
QDir filedir(localdir.path() + "/" + folder);
QStringList filelist = filedir.entryList(QDir::Files | QDir::NoDotAndDotDot);
for (int a = 0; a < filelist.length(); ++a) {
QString fileSrc = localdir.path() + "/" + folder + "/" + filelist.at(a);
QString fileTarget = widgetsDir + "/" + folder + "/" + filelist.at(a);
// Copy the file
file.copy( fileSrc , fileTarget );
// Set permissions Readable and Writeable.
file.setPermissions(fileTarget, QFileDevice::ReadOther | QFileDevice::WriteOther | QFileDevice::ExeGroup);
}
}
}
}
void mainWindow::on_obj_showFolderBtn_clicked(){
QDesktopServices::openUrl(widgetsDir);
}
void mainWindow::on_obj_refreshWidgetListBtn_clicked(){
updateWidgetList(ui->obj_widgetList);
}
// Before the app quit
void mainWindow::onAppQuit(){
CLOSING = true;
// Close the widgets too.
for(auto e : map_widgetList.keys()){
// Save widget configs.
saveWidgetSettings(e);
// Destroy them.
delete map_widgetList.value(e);
}
QApplication::quit();
}
// Window Close Event
void mainWindow::closeEvent(QCloseEvent *event){
event->ignore();
this->setVisible(false);
}
<|endoftext|> |
<commit_before>// wingtrack.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "FlyCapture2.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/background_segm.hpp>
#include <opencv2/gpu/gpu.hpp>
using namespace FlyCapture2;
using namespace cv;
using namespace cv::gpu;
#define USEGPU 1
void PrintBuildInfo()
{
FC2Version fc2Version;
Utilities::GetLibraryVersion(&fc2Version);
char version[128];
sprintf_s(
version,
"FlyCapture2 library version: %d.%d.%d.%d\n",
fc2Version.major, fc2Version.minor, fc2Version.type, fc2Version.build);
printf("%s", version);
char timeStamp[512];
sprintf_s(timeStamp, "Application build date: %s %s\n\n", __DATE__, __TIME__);
printf("%s", timeStamp);
}
void PrintCameraInfo(CameraInfo* pCamInfo)
{
printf(
"\n*** CAMERA INFORMATION ***\n"
"Serial number - %u\n"
"Camera model - %s\n"
"Camera vendor - %s\n"
"Sensor - %s\n"
"Resolution - %s\n"
"Firmware version - %s\n"
"Firmware build time - %s\n\n",
pCamInfo->serialNumber,
pCamInfo->modelName,
pCamInfo->vendorName,
pCamInfo->sensorInfo,
pCamInfo->sensorResolution,
pCamInfo->firmwareVersion,
pCamInfo->firmwareBuildTime);
}
void PrintFormat7Capabilities(Format7Info fmt7Info)
{
printf(
"Max image pixels: (%u, %u)\n"
"Image Unit size: (%u, %u)\n"
"Offset Unit size: (%u, %u)\n"
"Pixel format bitfield: 0x%08x\n",
fmt7Info.maxWidth,
fmt7Info.maxHeight,
fmt7Info.imageHStepSize,
fmt7Info.imageVStepSize,
fmt7Info.offsetHStepSize,
fmt7Info.offsetVStepSize,
fmt7Info.pixelFormatBitField);
}
void PrintError(Error error)
{
error.PrintErrorTrace();
}
int _tmain(int argc, _TCHAR* argv[])
{
const Mode k_fmt7Mode = MODE_0;
const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW8;
Error error;
BusManager busMgr;
unsigned int numCameras;
error = busMgr.GetNumOfCameras(&numCameras);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
printf("Number of cameras detected: %u\n", numCameras);
if (numCameras < 1)
{
printf("Insufficient number of cameras... exiting\n");
return -1;
}
PGRGuid guid;
error = busMgr.GetCameraFromIndex(0, &guid);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
Camera cam;
// Connect to a camera
error = cam.Connect(&guid);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
// Get the camera information
CameraInfo camInfo;
error = cam.GetCameraInfo(&camInfo);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
PrintCameraInfo(&camInfo);
// Query for available Format 7 modes
Format7Info fmt7Info;
bool supported;
fmt7Info.mode = k_fmt7Mode;
error = cam.GetFormat7Info(&fmt7Info, &supported);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
PrintFormat7Capabilities(fmt7Info);
if ((k_fmt7PixFmt & fmt7Info.pixelFormatBitField) == 0)
{
// Pixel format not supported!
printf("Pixel format is not supported\n");
return -1;
}
Format7ImageSettings fmt7ImageSettings;
fmt7ImageSettings.mode = k_fmt7Mode;
fmt7ImageSettings.offsetX = 0;
fmt7ImageSettings.offsetY = 0;
fmt7ImageSettings.width = fmt7Info.maxWidth;
fmt7ImageSettings.height = fmt7Info.maxHeight;
fmt7ImageSettings.pixelFormat = k_fmt7PixFmt;
bool valid;
Format7PacketInfo fmt7PacketInfo;
// Validate the settings to make sure that they are valid
error = cam.ValidateFormat7Settings(
&fmt7ImageSettings,
&valid,
&fmt7PacketInfo);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
if (!valid)
{
// Settings are not valid
printf("Format7 settings are not valid\n");
return -1;
}
// Set the settings to the camera
error = cam.SetFormat7Configuration(
&fmt7ImageSettings,
fmt7PacketInfo.recommendedBytesPerPacket);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
// Start capturing images
error = cam.StartCapture();
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
// Retrieve frame rate property
Property frmRate;
frmRate.type = FRAME_RATE;
error = cam.GetProperty(&frmRate);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
printf("Frame rate is %3.2f fps\n", frmRate.absValue);
Image rawImage;
BackgroundSubtractorMOG mog_cpu;
MOG_GPU mog_gpu;
Mat fgmask; //fg mask generated by MOG method
GpuMat d_frame, d_fgmask;
for (int imageCount = 0; ; imageCount++)
{
// Retrieve an image
error = cam.RetrieveBuffer(&rawImage);
if (error != PGRERROR_OK)
{
PrintError(error);
continue;
}
// Create a converted image
Image convertedImage;
// Convert the raw image
error = rawImage.Convert(PIXEL_FORMAT_MONO8, &convertedImage);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
// convert to OpenCV Mat
unsigned int rowBytes = (double)convertedImage.GetReceivedDataSize() / (double)convertedImage.GetRows();
Mat frame = Mat(convertedImage.GetRows(), convertedImage.GetCols(), CV_8UC1, convertedImage.GetData(), rowBytes);
if (USEGPU)
{
d_frame.upload(frame);
mog_gpu(d_frame, d_fgmask, 0.01f);
d_fgmask.download(fgmask);
}
else
mog_cpu(frame, fgmask, 0.01);
imshow("raw image", frame);
imshow("FG mask", fgmask);
char key = waitKey(1);
if (key == 27)
break;
}
// Stop capturing images
error = cam.StopCapture();
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
// Disconnect the camera
error = cam.Disconnect();
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
printf("Done! Press Enter to exit...\n");
getchar();
return 0;
}
<commit_msg>Added reading fmf files, debugging required<commit_after>// wingtrack.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "FlyCapture2.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/background_segm.hpp>
#include <opencv2/gpu/gpu.hpp>
using namespace FlyCapture2;
using namespace cv;
using namespace cv::gpu;
#define USEGPU 1
FILE *FMF_In;
unsigned __int32 fmfVersion, SizeY, SizeX, nframes;
unsigned __int64 bytesPerChunk;
long maxFramesInFile;
char *buf;
Camera cam;
BackgroundSubtractorMOG mog_cpu;
MOG_GPU mog_gpu;
Mat frame, fgmask;
GpuMat d_frame, d_fgmask;
Error error;
void PrintBuildInfo()
{
FC2Version fc2Version;
Utilities::GetLibraryVersion(&fc2Version);
char version[128];
sprintf_s(
version,
"FlyCapture2 library version: %d.%d.%d.%d\n",
fc2Version.major, fc2Version.minor, fc2Version.type, fc2Version.build);
printf("%s", version);
char timeStamp[512];
sprintf_s(timeStamp, "Application build date: %s %s\n\n", __DATE__, __TIME__);
printf("%s", timeStamp);
}
void PrintCameraInfo(CameraInfo* pCamInfo)
{
printf(
"\n*** CAMERA INFORMATION ***\n"
"Serial number - %u\n"
"Camera model - %s\n"
"Camera vendor - %s\n"
"Sensor - %s\n"
"Resolution - %s\n"
"Firmware version - %s\n"
"Firmware build time - %s\n\n",
pCamInfo->serialNumber,
pCamInfo->modelName,
pCamInfo->vendorName,
pCamInfo->sensorInfo,
pCamInfo->sensorResolution,
pCamInfo->firmwareVersion,
pCamInfo->firmwareBuildTime);
}
void PrintFormat7Capabilities(Format7Info fmt7Info)
{
printf(
"Max image pixels: (%u, %u)\n"
"Image Unit size: (%u, %u)\n"
"Offset Unit size: (%u, %u)\n"
"Pixel format bitfield: 0x%08x\n",
fmt7Info.maxWidth,
fmt7Info.maxHeight,
fmt7Info.imageHStepSize,
fmt7Info.imageVStepSize,
fmt7Info.offsetHStepSize,
fmt7Info.offsetVStepSize,
fmt7Info.pixelFormatBitField);
}
void PrintError(Error error)
{
error.PrintErrorTrace();
}
void ReadFMFHeader()
{
fread(&fmfVersion, sizeof(unsigned __int32), 1, FMF_In);
fread(&SizeY, sizeof(unsigned __int32), 1, FMF_In);
fread(&SizeX, sizeof(unsigned __int32), 1, FMF_In);
fread(&bytesPerChunk, sizeof(unsigned __int64), 1, FMF_In);
fread(&nframes, sizeof(unsigned __int64), 1, FMF_In);
buf = new char[bytesPerChunk];
maxFramesInFile = (unsigned long int)nframes;
}
int ReadFMFFrame(unsigned long frameIndex)
{
//IplImage *temp = cvCreateImage(cvSize(SizeX, SizeY), IPL_DEPTH_8U, 1);
if((long)frameIndex>=0L && (long)frameIndex < maxFramesInFile)
fseek (FMF_In, frameIndex*bytesPerChunk + 28 , SEEK_SET );
else
return -1; // Cannot grab .. illegal frame number
fread(buf, sizeof(double), 1, FMF_In);
fread(buf, bytesPerChunk-sizeof(double), 1, FMF_In);
//memmove(temp->imageData, buf, bytesPerChunk);
return 1;
}
void CloseFMF()
{
fclose(FMF_In);
}
int _tmain(int argc, _TCHAR* argv[])
{
bool isVideo = false;
bool isCam = false;
if (argc == 2)
{
FMF_In = fopen(argv[1], "rb");
if(FMF_In == NULL) // Cannot open File
{
printf("Cannot open input video file\n");
return -1;
}
ReadFMFHeader();
isVideo = true;
}
else
{
const Mode k_fmt7Mode = MODE_0;
const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW8;
BusManager busMgr;
unsigned int numCameras;
error = busMgr.GetNumOfCameras(&numCameras);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
printf("Number of cameras detected: %u\n", numCameras);
if (numCameras < 1)
{
printf("Insufficient number of cameras... exiting\n");
return -1;
}
PGRGuid guid;
error = busMgr.GetCameraFromIndex(0, &guid);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
// Connect to a camera
error = cam.Connect(&guid);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
// Get the camera information
CameraInfo camInfo;
error = cam.GetCameraInfo(&camInfo);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
PrintCameraInfo(&camInfo);
// Query for available Format 7 modes
Format7Info fmt7Info;
bool supported;
fmt7Info.mode = k_fmt7Mode;
error = cam.GetFormat7Info(&fmt7Info, &supported);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
PrintFormat7Capabilities(fmt7Info);
if ((k_fmt7PixFmt & fmt7Info.pixelFormatBitField) == 0)
{
// Pixel format not supported!
printf("Pixel format is not supported\n");
return -1;
}
Format7ImageSettings fmt7ImageSettings;
fmt7ImageSettings.mode = k_fmt7Mode;
fmt7ImageSettings.offsetX = 0;
fmt7ImageSettings.offsetY = 0;
fmt7ImageSettings.width = fmt7Info.maxWidth;
fmt7ImageSettings.height = fmt7Info.maxHeight;
fmt7ImageSettings.pixelFormat = k_fmt7PixFmt;
bool valid;
Format7PacketInfo fmt7PacketInfo;
// Validate the settings to make sure that they are valid
error = cam.ValidateFormat7Settings(
&fmt7ImageSettings,
&valid,
&fmt7PacketInfo);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
if (!valid)
{
// Settings are not valid
printf("Format7 settings are not valid\n");
return -1;
}
// Set the settings to the camera
error = cam.SetFormat7Configuration(
&fmt7ImageSettings,
fmt7PacketInfo.recommendedBytesPerPacket);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
// Start capturing images
error = cam.StartCapture();
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
// Retrieve frame rate property
Property frmRate;
frmRate.type = FRAME_RATE;
error = cam.GetProperty(&frmRate);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
printf("Frame rate is %3.2f fps\n", frmRate.absValue);
isCam = true;
}
for (int imageCount = 0; ; imageCount++)
{
if (isCam)
{
Image rawImage, convertedImage;
// Retrieve an image
error = cam.RetrieveBuffer(&rawImage);
if (error != PGRERROR_OK)
{
PrintError(error);
continue;
}
// Convert the raw image
error = rawImage.Convert(PIXEL_FORMAT_MONO8, &convertedImage);
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
// convert to OpenCV Mat
unsigned int rowBytes = (double)convertedImage.GetReceivedDataSize() / (double)convertedImage.GetRows();
Mat tFrame = Mat(convertedImage.GetRows(), convertedImage.GetCols(), CV_8UC1, convertedImage.GetData(), rowBytes);
frame = tFrame;
}
else if (isVideo)
{
int success = ReadFMFFrame(imageCount);
if (success){
Mat tFrame = Mat(SizeY, SizeX, CV_8UC1, buf, bytesPerChunk);
frame = tFrame;
}
else
break;
}
if (USEGPU)
{
d_frame.upload(frame);
mog_gpu(d_frame, d_fgmask, 0.01f);
d_fgmask.download(fgmask);
}
else
mog_cpu(frame, fgmask, 0.01);
imshow("raw image", frame);
imshow("FG mask", fgmask);
char key = waitKey(1);
if (key == 27)
break;
}
if (isCam)
{
// Stop capturing images
error = cam.StopCapture();
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
// Disconnect the camera
error = cam.Disconnect();
if (error != PGRERROR_OK)
{
PrintError(error);
return -1;
}
}
else
CloseFMF();
printf("Done! Press Enter to exit...\n");
getchar();
return 0;
}
<|endoftext|> |
<commit_before>/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "kolabwizard.h"
#include "kolabconfig.h"
#include <libkcal/resourcecalendar.h>
#include <kabc/resource.h>
#include "kresources/imap/kcal/resourceimap.h"
#include "kresources/imap/kabc/resourceimap.h"
#include "kresources/imap/knotes/resourceimap.h"
#include <klineedit.h>
#include <klocale.h>
#include <qlayout.h>
#include <qcheckbox.h>
#include <qlabel.h>
class CreateCalenderImapResource : public KConfigPropagator::Change
{
public:
CreateCalenderImapResource()
: KConfigPropagator::Change( i18n("Create Calender IMAP Resource") )
{
}
void apply()
{
kdDebug() << "Creating Calender IMAP Resource" << endl;
KCal::CalendarResourceManager m( "calendar" );
m.readConfig();
QString server = KolabConfig::self()->server();
KCal::ResourceIMAP *r = new KCal::ResourceIMAP( server );
r->setResourceName( i18n("Kolab Server") );
m.add( r );
m.writeConfig();
}
};
class CreateContactImapResource : public KConfigPropagator::Change
{
public:
CreateContactImapResource()
: KConfigPropagator::Change( i18n("Create Contact IMAP Resource") )
{
}
void apply()
{
KRES::Manager<KABC::Resource> m( "contact" );
m.readConfig();
KABC::ResourceIMAP *r = new KABC::ResourceIMAP( 0 );
r->setResourceName( i18n("Kolab Server") );
m.add( r );
m.writeConfig();
}
};
class CreateNotesImapResource : public KConfigPropagator::Change
{
public:
CreateNotesImapResource()
: KConfigPropagator::Change( i18n("Create Notes IMAP Resource") )
{
}
void apply()
{
KRES::Manager<ResourceNotes> m( "notes" );
m.readConfig();
KNotesIMAP::ResourceIMAP *r = new KNotesIMAP::ResourceIMAP( 0 );
r->setResourceName( i18n("Kolab Server") );
m.add( r );
m.writeConfig();
}
};
class KolabPropagator : public KConfigPropagator
{
public:
KolabPropagator()
: KConfigPropagator( KolabConfig::self(), "kolab.kcfg" )
{
}
protected:
void addCustomChanges( Change::List &changes )
{
QString freeBusyBaseUrl = "webdavs://" + KolabConfig::self()->server() +
"/freebusy/";
ChangeConfig *c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "FreeBusy";
c->name = "FreeBusyPublishUrl";
c->label = "";
QString user = KolabConfig::self()->user();
int pos = user.find( "@" );
if ( pos > 0 ) user = user.left( pos );
c->value = freeBusyBaseUrl + user + ".ifb";
changes.append( c );
c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "FreeBusy";
c->name = "FreeBusyRetrieveUrl";
c->value = freeBusyBaseUrl;
changes.append( c );
KCal::CalendarResourceManager m( "calendar" );
m.readConfig();
KCal::CalendarResourceManager::Iterator it;
for ( it = m.begin(); it != m.end(); ++it ) {
if ( (*it)->type() == "imap" ) break;
}
if ( it == m.end() ) {
changes.append( new CreateCalenderImapResource );
changes.append( new CreateContactImapResource );
changes.append( new CreateNotesImapResource );
}
}
};
KolabWizard::KolabWizard() : KConfigWizard( new KolabPropagator )
{
QFrame *page = createWizardPage( i18n("Kolab Server") );
QGridLayout *topLayout = new QGridLayout( page );
topLayout->setSpacing( spacingHint() );
QLabel *label = new QLabel( i18n("Server name:"), page );
topLayout->addWidget( label, 0, 0 );
mServerEdit = new KLineEdit( page );
topLayout->addWidget( mServerEdit, 0, 1 );
label = new QLabel( i18n("User name:"), page );
topLayout->addWidget( label, 1, 0 );
mUserEdit = new KLineEdit( page );
topLayout->addWidget( mUserEdit, 1, 1 );
label = new QLabel( i18n("Password:"), page );
topLayout->addWidget( label, 2, 0 );
mPasswordEdit = new KLineEdit( page );
mPasswordEdit->setEchoMode( KLineEdit::Password );
topLayout->addWidget( mPasswordEdit, 2, 1 );
mSavePasswordCheck = new QCheckBox( i18n("Save password"), page );
topLayout->addMultiCellWidget( mSavePasswordCheck, 3, 3, 0, 1 );
topLayout->setRowStretch( 4, 1 );
setupRulesPage();
setupChangesPage();
resize( 400, 300 );
}
KolabWizard::~KolabWizard()
{
}
void KolabWizard::usrReadConfig()
{
mServerEdit->setText( KolabConfig::self()->server() );
mUserEdit->setText( KolabConfig::self()->user() );
mPasswordEdit->setText( KolabConfig::self()->password() );
mSavePasswordCheck->setChecked( KolabConfig::self()->savePassword() );
}
void KolabWizard::usrWriteConfig()
{
KolabConfig::self()->setServer( mServerEdit->text() );
KolabConfig::self()->setUser( mUserEdit->text() );
KolabConfig::self()->setPassword( mPasswordEdit->text() );
KolabConfig::self()->setSavePassword( mSavePasswordCheck->isChecked() );
}
<commit_msg>- add new ldap entry - turn on groupware functionality in kmail<commit_after>/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>
Copyright (c) 2004 Daniel Molkentin <molkentin@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "kolabwizard.h"
#include "kolabconfig.h"
#include "kmailchanges.h"
#include <libkcal/resourcecalendar.h>
#include <kabc/resource.h>
#include "kresources/imap/kcal/resourceimap.h"
#include "kresources/imap/kabc/resourceimap.h"
#include "kresources/imap/knotes/resourceimap.h"
#include <klineedit.h>
#include <klocale.h>
#include <qlayout.h>
#include <qcheckbox.h>
#include <qlabel.h>
class SetupLDAPSearchAccount : public KConfigPropagator::Change
{
public:
SetupLDAPSearchAccount()
: KConfigPropagator::Change( i18n("Setup LDAP Search Account") )
{
}
void apply()
{
QString host = KolabConfig::self()->server();
QString basedn = host;
basedn.replace(".",",dc=");
basedn.prepend("dc=");
KConfig c( "kabldaprc" );
c.setGroup( "LDAP" );
uint selHosts = c.readNumEntry("NumSelectedHosts", 0);
c.writeEntry( "NumSelectedHosts", selHosts + 1 );
c.writeEntry( QString("SelectedHost%1").arg(selHosts), host);
c.writeEntry( QString("SelectedBase%1").arg(selHosts), basedn);
c.writeEntry( QString("SelectedPort%1").arg(selHosts), "389");
}
};
class CreateCalenderImapResource : public KConfigPropagator::Change
{
public:
CreateCalenderImapResource()
: KConfigPropagator::Change( i18n("Create Calender IMAP Resource") )
{
}
void apply()
{
KCal::CalendarResourceManager m( "calendar" );
m.readConfig();
QString server = KolabConfig::self()->server();
KCal::ResourceIMAP *r = new KCal::ResourceIMAP( server );
r->setResourceName( i18n("Kolab Server") );
m.add( r );
m.writeConfig();
}
};
class CreateContactImapResource : public KConfigPropagator::Change
{
public:
CreateContactImapResource()
: KConfigPropagator::Change( i18n("Create Contact IMAP Resource") )
{
}
void apply()
{
KRES::Manager<KABC::Resource> m( "contact" );
m.readConfig();
KABC::ResourceIMAP *r = new KABC::ResourceIMAP( 0 );
r->setResourceName( i18n("Kolab Server") );
m.add( r );
m.writeConfig();
}
};
class CreateNotesImapResource : public KConfigPropagator::Change
{
public:
CreateNotesImapResource()
: KConfigPropagator::Change( i18n("Create Notes IMAP Resource") )
{
}
void apply()
{
KRES::Manager<ResourceNotes> m( "notes" );
m.readConfig();
KNotesIMAP::ResourceIMAP *r = new KNotesIMAP::ResourceIMAP( 0 );
r->setResourceName( i18n("Kolab Server") );
m.add( r );
m.writeConfig();
}
};
class KolabPropagator : public KConfigPropagator
{
public:
KolabPropagator()
: KConfigPropagator( KolabConfig::self(), "kolab.kcfg" )
{
}
protected:
void addCustomChanges( Change::List &changes )
{
QString freeBusyBaseUrl = "webdavs://" + KolabConfig::self()->server() +
"/freebusy/";
ChangeConfig *c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "FreeBusy";
c->name = "FreeBusyPublishUrl";
c->label = "";
QString user = KolabConfig::self()->user();
int pos = user.find( "@" );
if ( pos > 0 ) user = user.left( pos );
c->value = freeBusyBaseUrl + user + ".ifb";
changes.append( c );
c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "FreeBusy";
c->name = "FreeBusyRetrieveUrl";
c->value = freeBusyBaseUrl;
// KMail cruft has been outsourced
createKMailChanges( changes );
changes.append( c );
changes.append( new SetupLDAPSearchAccount );
KCal::CalendarResourceManager m( "calendar" );
m.readConfig();
KCal::CalendarResourceManager::Iterator it;
for ( it = m.begin(); it != m.end(); ++it ) {
if ( (*it)->type() == "imap" ) break;
}
if ( it == m.end() ) {
changes.append( new CreateCalenderImapResource );
changes.append( new CreateContactImapResource );
changes.append( new CreateNotesImapResource );
}
}
};
KolabWizard::KolabWizard() : KConfigWizard( new KolabPropagator )
{
QFrame *page = createWizardPage( i18n("Kolab Server") );
QGridLayout *topLayout = new QGridLayout( page );
topLayout->setSpacing( spacingHint() );
QLabel *label = new QLabel( i18n("Server name:"), page );
topLayout->addWidget( label, 0, 0 );
mServerEdit = new KLineEdit( page );
topLayout->addWidget( mServerEdit, 0, 1 );
label = new QLabel( i18n("User name:"), page );
topLayout->addWidget( label, 1, 0 );
mUserEdit = new KLineEdit( page );
topLayout->addWidget( mUserEdit, 1, 1 );
label = new QLabel( i18n("Password:"), page );
topLayout->addWidget( label, 2, 0 );
mPasswordEdit = new KLineEdit( page );
mPasswordEdit->setEchoMode( KLineEdit::Password );
topLayout->addWidget( mPasswordEdit, 2, 1 );
mSavePasswordCheck = new QCheckBox( i18n("Save password"), page );
topLayout->addMultiCellWidget( mSavePasswordCheck, 3, 3, 0, 1 );
topLayout->setRowStretch( 4, 1 );
setupRulesPage();
setupChangesPage();
resize( 400, 300 );
}
KolabWizard::~KolabWizard()
{
}
void KolabWizard::usrReadConfig()
{
mServerEdit->setText( KolabConfig::self()->server() );
mUserEdit->setText( KolabConfig::self()->user() );
mPasswordEdit->setText( KolabConfig::self()->password() );
mSavePasswordCheck->setChecked( KolabConfig::self()->savePassword() );
}
void KolabWizard::usrWriteConfig()
{
KolabConfig::self()->setServer( mServerEdit->text() );
KolabConfig::self()->setUser( mUserEdit->text() );
KolabConfig::self()->setPassword( mPasswordEdit->text() );
KolabConfig::self()->setSavePassword( mSavePasswordCheck->isChecked() );
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/gfx/rect.h"
#if defined(OS_WIN)
#include <windows.h>
#elif defined(OS_MACOSX)
#include <CoreGraphics/CGGeometry.h>
#elif defined(OS_LINUX)
#include <gdk/gdk.h>
#endif
#include "base/logging.h"
namespace {
void AdjustAlongAxis(int dst_origin, int dst_size, int* origin, int* size) {
if (*origin < dst_origin) {
*origin = dst_origin;
*size = std::min(dst_size, *size);
} else {
*size = std::min(dst_size, *size);
*origin = std::min(dst_origin + dst_size, *origin + *size) - *size;
}
}
} // namespace
namespace gfx {
Rect::Rect() {
}
Rect::Rect(int width, int height) {
set_width(width);
set_height(height);
}
Rect::Rect(int x, int y, int width, int height)
: origin_(x, y) {
set_width(width);
set_height(height);
}
#if defined(OS_WIN)
Rect::Rect(const RECT& r)
: origin_(r.left, r.top) {
set_width(r.right - r.left);
set_height(r.bottom - r.top);
}
Rect& Rect::operator=(const RECT& r) {
origin_.SetPoint(r.left, r.top);
set_width(r.right - r.left);
set_height(r.bottom - r.top);
return *this;
}
#elif defined(OS_MACOSX)
Rect::Rect(const CGRect& r)
: origin_(r.origin.x, r.origin.y) {
set_width(r.size.width);
set_height(r.size.height);
}
Rect& Rect::operator=(const CGRect& r) {
origin_.SetPoint(r.origin.x, r.origin.y);
set_width(r.size.width);
set_height(r.size.height);
return *this;
}
#elif defined(OS_LINUX)
Rect::Rect(const GdkRectangle& r)
: origin_(r.x, r.y) {
set_width(r.width);
set_height(r.height);
}
Rect& Rect::operator=(const GdkRectangle& r) {
origin_.SetPoint(r.x, r.y);
set_width(r.width);
set_height(r.height);
return *this;
}
#endif
void Rect::set_width(int width) {
if (width < 0) {
NOTREACHED();
width = 0;
}
size_.set_width(width);
}
void Rect::set_height(int height) {
if (height < 0) {
NOTREACHED();
height = 0;
}
size_.set_height(height);
}
void Rect::SetRect(int x, int y, int width, int height) {
origin_.SetPoint(x, y);
set_width(width);
set_height(height);
}
void Rect::Inset(int horizontal, int vertical) {
set_x(x() + horizontal);
set_y(y() + vertical);
set_width(std::max(width() - (horizontal * 2), 0));
set_height(std::max(height() - (vertical * 2), 0));
}
void Rect::Inset(int left, int top, int right, int bottom) {
set_width(std::max(width() - left - right, 0));
set_height(std::max(height() - top - bottom, 0));
set_x(left);
set_y(top);
}
void Rect::Offset(int horizontal, int vertical) {
set_x(x() + horizontal);
set_y(y() + vertical);
}
bool Rect::IsEmpty() const {
return width() == 0 || height() == 0;
}
bool Rect::operator==(const Rect& other) const {
return origin_ == other.origin_ && size_ == other.size_;
}
#if defined(OS_WIN)
RECT Rect::ToRECT() const {
RECT r;
r.left = x();
r.right = right();
r.top = y();
r.bottom = bottom();
return r;
}
#elif defined(OS_MACOSX)
CGRect Rect::ToCGRect() const {
return CGRectMake(x(), y(), width(), height());
}
#endif
bool Rect::Contains(int point_x, int point_y) const {
return (point_x >= x()) && (point_x < right()) &&
(point_y >= y()) && (point_y < bottom());
}
bool Rect::Contains(const Rect& rect) const {
return (rect.x() >= x() && rect.right() <= right() &&
rect.y() >= y() && rect.bottom() <= bottom());
}
bool Rect::Intersects(const Rect& rect) const {
return !(rect.x() >= right() || rect.right() <= x() ||
rect.y() >= bottom() || rect.bottom() <= y());
}
Rect Rect::Intersect(const Rect& rect) const {
int rx = std::max(x(), rect.x());
int ry = std::max(y(), rect.y());
int rr = std::min(right(), rect.right());
int rb = std::min(bottom(), rect.bottom());
if (rx >= rr || ry >= rb)
rx = ry = rr = rb = 0; // non-intersecting
return Rect(rx, ry, rr - rx, rb - ry);
}
Rect Rect::Union(const Rect& rect) const {
// special case empty rects...
if (IsEmpty())
return rect;
if (rect.IsEmpty())
return *this;
int rx = std::min(x(), rect.x());
int ry = std::min(y(), rect.y());
int rr = std::max(right(), rect.right());
int rb = std::max(bottom(), rect.bottom());
return Rect(rx, ry, rr - rx, rb - ry);
}
Rect Rect::Subtract(const Rect& rect) const {
// boundary cases:
if (!Intersects(rect))
return *this;
if (rect.Contains(*this))
return Rect();
int rx = x();
int ry = y();
int rr = right();
int rb = bottom();
if (rect.y() <= y() && rect.bottom() >= bottom()) {
// complete intersection in the y-direction
if (rect.x() <= x()) {
rx = rect.right();
} else {
rr = rect.x();
}
} else if (rect.x() <= x() && rect.right() >= right()) {
// complete intersection in the x-direction
if (rect.y() <= y()) {
ry = rect.bottom();
} else {
rb = rect.y();
}
}
return Rect(rx, ry, rr - rx, rb - ry);
}
Rect Rect::AdjustToFit(const Rect& rect) const {
int new_x = x();
int new_y = y();
int new_width = width();
int new_height = height();
AdjustAlongAxis(rect.x(), rect.width(), &new_x, &new_width);
AdjustAlongAxis(rect.y(), rect.height(), &new_y, &new_height);
return Rect(new_x, new_y, new_width, new_height);
}
Point Rect::CenterPoint() const {
return Point(x() + (width() + 1) / 2, y() + (height() + 1) / 2);
}
} // namespace gfx
<commit_msg>Fix tree breakage.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/gfx/rect.h"
#if defined(OS_WIN)
#include <windows.h>
#elif defined(OS_MACOSX)
#include <CoreGraphics/CGGeometry.h>
#elif defined(OS_LINUX)
#include <gdk/gdk.h>
#endif
#include "base/logging.h"
namespace {
void AdjustAlongAxis(int dst_origin, int dst_size, int* origin, int* size) {
if (*origin < dst_origin) {
*origin = dst_origin;
*size = std::min(dst_size, *size);
} else {
*size = std::min(dst_size, *size);
*origin = std::min(dst_origin + dst_size, *origin + *size) - *size;
}
}
} // namespace
namespace gfx {
Rect::Rect() {
}
Rect::Rect(int width, int height) {
set_width(width);
set_height(height);
}
Rect::Rect(int x, int y, int width, int height)
: origin_(x, y) {
set_width(width);
set_height(height);
}
Rect::Rect(const gfx::Point& origin, const gfx::Size& size)
: origin_(origin), size_(size) {
}
#if defined(OS_WIN)
Rect::Rect(const RECT& r)
: origin_(r.left, r.top) {
set_width(r.right - r.left);
set_height(r.bottom - r.top);
}
Rect& Rect::operator=(const RECT& r) {
origin_.SetPoint(r.left, r.top);
set_width(r.right - r.left);
set_height(r.bottom - r.top);
return *this;
}
#elif defined(OS_MACOSX)
Rect::Rect(const CGRect& r)
: origin_(r.origin.x, r.origin.y) {
set_width(r.size.width);
set_height(r.size.height);
}
Rect& Rect::operator=(const CGRect& r) {
origin_.SetPoint(r.origin.x, r.origin.y);
set_width(r.size.width);
set_height(r.size.height);
return *this;
}
#elif defined(OS_LINUX)
Rect::Rect(const GdkRectangle& r)
: origin_(r.x, r.y) {
set_width(r.width);
set_height(r.height);
}
Rect& Rect::operator=(const GdkRectangle& r) {
origin_.SetPoint(r.x, r.y);
set_width(r.width);
set_height(r.height);
return *this;
}
#endif
void Rect::set_width(int width) {
if (width < 0) {
NOTREACHED();
width = 0;
}
size_.set_width(width);
}
void Rect::set_height(int height) {
if (height < 0) {
NOTREACHED();
height = 0;
}
size_.set_height(height);
}
void Rect::SetRect(int x, int y, int width, int height) {
origin_.SetPoint(x, y);
set_width(width);
set_height(height);
}
void Rect::Inset(int horizontal, int vertical) {
set_x(x() + horizontal);
set_y(y() + vertical);
set_width(std::max(width() - (horizontal * 2), 0));
set_height(std::max(height() - (vertical * 2), 0));
}
void Rect::Inset(int left, int top, int right, int bottom) {
set_width(std::max(width() - left - right, 0));
set_height(std::max(height() - top - bottom, 0));
set_x(left);
set_y(top);
}
void Rect::Offset(int horizontal, int vertical) {
set_x(x() + horizontal);
set_y(y() + vertical);
}
bool Rect::IsEmpty() const {
return width() == 0 || height() == 0;
}
bool Rect::operator==(const Rect& other) const {
return origin_ == other.origin_ && size_ == other.size_;
}
#if defined(OS_WIN)
RECT Rect::ToRECT() const {
RECT r;
r.left = x();
r.right = right();
r.top = y();
r.bottom = bottom();
return r;
}
#elif defined(OS_MACOSX)
CGRect Rect::ToCGRect() const {
return CGRectMake(x(), y(), width(), height());
}
#endif
bool Rect::Contains(int point_x, int point_y) const {
return (point_x >= x()) && (point_x < right()) &&
(point_y >= y()) && (point_y < bottom());
}
bool Rect::Contains(const Rect& rect) const {
return (rect.x() >= x() && rect.right() <= right() &&
rect.y() >= y() && rect.bottom() <= bottom());
}
bool Rect::Intersects(const Rect& rect) const {
return !(rect.x() >= right() || rect.right() <= x() ||
rect.y() >= bottom() || rect.bottom() <= y());
}
Rect Rect::Intersect(const Rect& rect) const {
int rx = std::max(x(), rect.x());
int ry = std::max(y(), rect.y());
int rr = std::min(right(), rect.right());
int rb = std::min(bottom(), rect.bottom());
if (rx >= rr || ry >= rb)
rx = ry = rr = rb = 0; // non-intersecting
return Rect(rx, ry, rr - rx, rb - ry);
}
Rect Rect::Union(const Rect& rect) const {
// special case empty rects...
if (IsEmpty())
return rect;
if (rect.IsEmpty())
return *this;
int rx = std::min(x(), rect.x());
int ry = std::min(y(), rect.y());
int rr = std::max(right(), rect.right());
int rb = std::max(bottom(), rect.bottom());
return Rect(rx, ry, rr - rx, rb - ry);
}
Rect Rect::Subtract(const Rect& rect) const {
// boundary cases:
if (!Intersects(rect))
return *this;
if (rect.Contains(*this))
return Rect();
int rx = x();
int ry = y();
int rr = right();
int rb = bottom();
if (rect.y() <= y() && rect.bottom() >= bottom()) {
// complete intersection in the y-direction
if (rect.x() <= x()) {
rx = rect.right();
} else {
rr = rect.x();
}
} else if (rect.x() <= x() && rect.right() >= right()) {
// complete intersection in the x-direction
if (rect.y() <= y()) {
ry = rect.bottom();
} else {
rb = rect.y();
}
}
return Rect(rx, ry, rr - rx, rb - ry);
}
Rect Rect::AdjustToFit(const Rect& rect) const {
int new_x = x();
int new_y = y();
int new_width = width();
int new_height = height();
AdjustAlongAxis(rect.x(), rect.width(), &new_x, &new_width);
AdjustAlongAxis(rect.y(), rect.height(), &new_y, &new_height);
return Rect(new_x, new_y, new_width, new_height);
}
Point Rect::CenterPoint() const {
return Point(x() + (width() + 1) / 2, y() + (height() + 1) / 2);
}
} // namespace gfx
<|endoftext|> |
<commit_before>#include <thread>
#include <iostream>
#include "processor.h"
#ifdef WINDOWS
#include <windows.h>
#else
#include <unistd.h>
#endif
const uint MILLIS_IN_MICRO = 1000;
void sleep_for_millis(uint period) {
#ifdef WINDOWS
Sleep(period);
#else
usleep(period * MILLIS_IN_MICRO);
#endif
}
void Processor::run() {
int popped = 0;
while (true) {
while (buffer_.pop()) {
++popped;
}
if (popped > 200) {
if (!handler_.updateSigprofInterval()) {
break;
}
popped = 0;
}
if (!isRunning_.load()) {
break;
}
sleep_for_millis(interval_);
}
handler_.stopSigprof();
}
void callbackToRunProcessor(jvmtiEnv *jvmti_env, JNIEnv *jni_env, void *arg) {
IMPLICITLY_USE(jvmti_env);
IMPLICITLY_USE(jni_env);
//Avoid having the processor thread also receive the PROF signals
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGPROF);
if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
logError("ERROR: failed to set processor thread signal mask\n");
}
Processor *processor = (Processor *) arg;
processor->run();
}
void Processor::start(JNIEnv *jniEnv) {
jvmtiError result;
std::cout << "Starting sampling\n";
jthread thread = newThread(jniEnv, "Honest Profiler Processing Thread");
jvmtiStartFunction callback = callbackToRunProcessor;
result = jvmti_->RunAgentThread(thread, callback, this, JVMTI_THREAD_NORM_PRIORITY);
if (result != JVMTI_ERROR_NONE) {
logError("ERROR: Running agent thread failed with: %d\n", result);
}
}
void Processor::stop() {
isRunning_.store(false);
std::cout << "Stopping sampling\n";
}
bool Processor::isRunning() const {
return isRunning_.load();
}
<commit_msg>Set processor running to true on start<commit_after>#include <thread>
#include <iostream>
#include "processor.h"
#ifdef WINDOWS
#include <windows.h>
#else
#include <unistd.h>
#endif
const uint MILLIS_IN_MICRO = 1000;
void sleep_for_millis(uint period) {
#ifdef WINDOWS
Sleep(period);
#else
usleep(period * MILLIS_IN_MICRO);
#endif
}
void Processor::run() {
int popped = 0;
while (true) {
while (buffer_.pop()) {
++popped;
}
if (popped > 200) {
if (!handler_.updateSigprofInterval()) {
break;
}
popped = 0;
}
if (!isRunning_.load()) {
break;
}
sleep_for_millis(interval_);
}
handler_.stopSigprof();
}
void callbackToRunProcessor(jvmtiEnv *jvmti_env, JNIEnv *jni_env, void *arg) {
IMPLICITLY_USE(jvmti_env);
IMPLICITLY_USE(jni_env);
//Avoid having the processor thread also receive the PROF signals
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGPROF);
if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
logError("ERROR: failed to set processor thread signal mask\n");
}
Processor *processor = (Processor *) arg;
processor->run();
}
void Processor::start(JNIEnv *jniEnv) {
jvmtiError result;
std::cout << "Starting sampling\n";
isRunning_.store(true);
jthread thread = newThread(jniEnv, "Honest Profiler Processing Thread");
jvmtiStartFunction callback = callbackToRunProcessor;
result = jvmti_->RunAgentThread(thread, callback, this, JVMTI_THREAD_NORM_PRIORITY);
if (result != JVMTI_ERROR_NONE) {
logError("ERROR: Running agent thread failed with: %d\n", result);
}
}
void Processor::stop() {
isRunning_.store(false);
std::cout << "Stopping sampling\n";
}
bool Processor::isRunning() const {
return isRunning_.load();
}
<|endoftext|> |
<commit_before>#include "middling_player.hpp"
#include <ctime>
#include <boost/random/discrete_distribution.hpp>
#include "logger.hpp"
#include "walk_move.hpp"
#include "wall_move.hpp"
#include "exception.hpp"
static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
static int kLookForward = 2;
static int kMinimaxNodes = 0;
namespace Quoridor {
MiddlingPlayer::MiddlingPlayer(std::shared_ptr<Game> game,
std::shared_ptr<Pawn> pawn)
: game_(game), pawn_(pawn), goal_nodes_()
{
lg.add_attribute("Tag", blattrs::constant<std::string>("middling player"));
goal_nodes_ = game_->pawn_data(pawn_).goal_nodes;
BOOST_LOG_DEBUG(lg) << "created new MiddlingPlayer (" << pawn_->color() << ")";
for (auto node : goal_nodes_) {
BOOST_LOG_DEBUG(lg) << "goal node: " << node.row() << ":" << node.col();
}
}
MiddlingPlayer::~MiddlingPlayer()
{
}
IMove *MiddlingPlayer::get_move()
{
IMove *move = NULL;
kMinimaxNodes = 0;
double v = get_max_move(*game_, 0, -100, 100, &move);
BOOST_LOG_DEBUG(lg) << "got k " << v << " (analyzed " << kMinimaxNodes
<< " nodes)";
if (WalkMove *m = dynamic_cast<WalkMove*>(move)) {
BOOST_LOG_DEBUG(lg) << "best move is " << m->node().row() << ":"
<< m->node().col();
}
else if (WallMove *m = dynamic_cast<WallMove*>(move)) {
BOOST_LOG_DEBUG(lg) << "best move is " << m->wall();
}
return move;
}
double MiddlingPlayer::get_max_move(const Game &game, int depth,
double a, double b, IMove **best_move)
{
++kMinimaxNodes;
std::vector<IMove*> moves;
game.possible_moves(pawn_, &moves);
for (auto move : moves) {
Game game_cp = game;
if (WalkMove *m = dynamic_cast<WalkMove*>(move)) {
game_cp.move_pawn(m->node());
if (game_cp.is_finished()) {
if (best_move != NULL) {
*best_move = new WalkMove(*m);
}
a = 1.0f;
return a;
}
}
else if (WallMove *m = dynamic_cast<WallMove*>(move)) {
if (game_cp.add_wall(m->wall()) < 0) {
continue;
}
}
if (depth < kLookForward) {
game_cp.switch_pawn();
double val = get_min_move(game_cp, depth + 1, a, b);
if (val > a) {
a = val;
if (best_move != NULL) {
if (WalkMove *m = dynamic_cast<WalkMove*>(move)) {
*best_move = new WalkMove(*m);
}
else if (WallMove *m = dynamic_cast<WallMove*>(move)) {
*best_move = new WallMove(*m);
}
}
}
if (b <= a) {
return a;
}
}
else {
return evaluate(game_cp);
}
}
return a;
}
double MiddlingPlayer::get_min_move(const Game &game, int depth,
double a, double b)
{
++kMinimaxNodes;
std::vector<IMove*> moves;
game.possible_moves(pawn_, &moves);
for (auto move : moves) {
Game game_cp = game;
if (WalkMove *m = dynamic_cast<WalkMove*>(move)) {
game_cp.move_pawn(m->node());
if (game_cp.is_finished()) {
b = -1.0f;
return b;
}
}
else if (WallMove *m = dynamic_cast<WallMove*>(move)) {
if (game_cp.add_wall(m->wall()) < 0) {
continue;
}
}
if (depth < kLookForward) {
game_cp.switch_pawn();
b = std::min(b, get_max_move(game_cp, depth + 1, a, b, NULL));
if (b <= a) {
return b;
}
}
else {
return evaluate(game_cp);
}
}
return b;
}
double MiddlingPlayer::evaluate(const Game &game) const
{
double max_k = 0;
for (auto goal_node : goal_nodes_) {
std::list<Node> path;
if (game.get_path(pawn_, goal_node, &path)) {
double k = 1 / static_cast<double>(path.size());
max_k = std::max(k, max_k);
}
}
double rival_max_k = 0;
for (auto pawn_data : game.pawn_data_list()) {
if (pawn_data.pawn == pawn_) {
continue;
}
for (auto goal_node : pawn_data.goal_nodes) {
std::list<Node> path;
if (game.get_path(pawn_data.pawn, goal_node, &path)) {
double k = 1 / static_cast<double>(path.size());
rival_max_k = std::max(k, rival_max_k);
}
}
}
return max_k - rival_max_k;
}
} /* namespace Quoridor */
<commit_msg>Use shortest_path in MiddlingPlayer::evaluate<commit_after>#include "middling_player.hpp"
#include <ctime>
#include <boost/random/discrete_distribution.hpp>
#include "logger.hpp"
#include "walk_move.hpp"
#include "wall_move.hpp"
#include "exception.hpp"
static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
static int kLookForward = 2;
static int kMinimaxNodes = 0;
namespace Quoridor {
MiddlingPlayer::MiddlingPlayer(std::shared_ptr<Game> game,
std::shared_ptr<Pawn> pawn)
: game_(game), pawn_(pawn), goal_nodes_()
{
lg.add_attribute("Tag", blattrs::constant<std::string>("middling player"));
goal_nodes_ = game_->pawn_data(pawn_).goal_nodes;
BOOST_LOG_DEBUG(lg) << "created new MiddlingPlayer (" << pawn_->color() << ")";
for (auto node : goal_nodes_) {
BOOST_LOG_DEBUG(lg) << "goal node: " << node.row() << ":" << node.col();
}
}
MiddlingPlayer::~MiddlingPlayer()
{
}
IMove *MiddlingPlayer::get_move()
{
IMove *move = NULL;
kMinimaxNodes = 0;
double v = get_max_move(*game_, 0, -100, 100, &move);
BOOST_LOG_DEBUG(lg) << "got k " << v << " (analyzed " << kMinimaxNodes
<< " nodes)";
if (WalkMove *m = dynamic_cast<WalkMove*>(move)) {
BOOST_LOG_DEBUG(lg) << "best move is " << m->node().row() << ":"
<< m->node().col();
}
else if (WallMove *m = dynamic_cast<WallMove*>(move)) {
BOOST_LOG_DEBUG(lg) << "best move is " << m->wall();
}
return move;
}
double MiddlingPlayer::get_max_move(const Game &game, int depth,
double a, double b, IMove **best_move)
{
++kMinimaxNodes;
std::vector<IMove*> moves;
game.possible_moves(pawn_, &moves);
for (auto move : moves) {
Game game_cp = game;
if (WalkMove *m = dynamic_cast<WalkMove*>(move)) {
game_cp.move_pawn(m->node());
if (game_cp.is_finished()) {
if (best_move != NULL) {
*best_move = new WalkMove(*m);
}
a = 1.0f;
return a;
}
}
else if (WallMove *m = dynamic_cast<WallMove*>(move)) {
if (game_cp.add_wall(m->wall()) < 0) {
continue;
}
}
if (depth < kLookForward) {
game_cp.switch_pawn();
double val = get_min_move(game_cp, depth + 1, a, b);
if (val > a) {
a = val;
if (best_move != NULL) {
if (WalkMove *m = dynamic_cast<WalkMove*>(move)) {
*best_move = new WalkMove(*m);
}
else if (WallMove *m = dynamic_cast<WallMove*>(move)) {
*best_move = new WallMove(*m);
}
}
}
if (b <= a) {
return a;
}
}
else {
return evaluate(game_cp);
}
}
return a;
}
double MiddlingPlayer::get_min_move(const Game &game, int depth,
double a, double b)
{
++kMinimaxNodes;
std::vector<IMove*> moves;
game.possible_moves(pawn_, &moves);
for (auto move : moves) {
Game game_cp = game;
if (WalkMove *m = dynamic_cast<WalkMove*>(move)) {
game_cp.move_pawn(m->node());
if (game_cp.is_finished()) {
b = -1.0f;
return b;
}
}
else if (WallMove *m = dynamic_cast<WallMove*>(move)) {
if (game_cp.add_wall(m->wall()) < 0) {
continue;
}
}
if (depth < kLookForward) {
game_cp.switch_pawn();
b = std::min(b, get_max_move(game_cp, depth + 1, a, b, NULL));
if (b <= a) {
return b;
}
}
else {
return evaluate(game_cp);
}
}
return b;
}
double MiddlingPlayer::evaluate(const Game &game) const
{
double max_k = 0;
std::list<Node> path;
game.shortest_path(game_->pawn_data(pawn_).node, goal_nodes_, &path);
double k = 1 / static_cast<double>(path.size());
max_k = std::max(k, max_k);
double rival_max_k = 0;
for (auto pawn_data : game.pawn_data_list()) {
if (pawn_data.pawn == pawn_) {
continue;
}
std::list<Node> path;
game.shortest_path(pawn_data.node, pawn_data.goal_nodes, &path);
double k = 1 / static_cast<double>(path.size());
rival_max_k = std::max(k, rival_max_k);
}
return max_k - rival_max_k;
}
} /* namespace Quoridor */
<|endoftext|> |
<commit_before>#include<bits/stdc++.h>
#include<random>
#include<chrono>
#define ui unsigned int
using namespace std;
int main()
{
ui n=1000,d=5,m,l,s;
double epsi;
cout<<"Enter the number of Nodes (n) where n > 49 : "<<endl;
cin>>n;
assert(n>49);
cout<<"Enter the degree of each node (d) where d > 3 : "<<endl;
cin>>d;
assert(d > 3);
cout<<"Enter the value of epsilon (epsi) where 0 < epsi < 1 : "<<endl;
cin>>epsi;
assert(epsi>0 && epsi<1);
cout<<"Enter the value to repeat the loop (s) where s>=48/epsi : "<<endl;
cin>>s;
assert(s>=48/epsi);
cout<<"Enter the no of random walks (m) where m>=s*12*sqrt(n)/(epsi^2) : "<<endl;
cin>>m;
assert(m>=(s*12*sqrt(n)/pow(epsi,2)));
cout<<"Enter the length of random walk (l) where l>=16*(d^2)*ln(n/epsi) : "<<endl;
cin>>l;
assert(l>=(16*pow(d,2)*log(n/epsi)));
/**************************************************************/
/* Generating Random Graph */
/* */
/**************************************************************/
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator (seed);
std::uniform_int_distribution<ui> distribution(1,n);
vector<list <ui> > G(n+1);
for(ui i=1;i<=n;++i)
{
ui n1=0,n2=0,n3=0,n4=0,n5=0;
while(n1==n2)
{
while(n2==n3)
{
while(n3==n4)
{
while(n4==n5)
{
while(n5==i || n5==0)
{
n5=distribution(generator);
}
n4=distribution(generator);
}
n3=distribution(generator);
}
n2=distribution(generator);
}
n1=distribution(generator);
}
G[i].unique();
G[n5].unique();
G[n4].unique();
G[n3].unique();
G[n2].unique();
G[n1].unique();
if(G[i].size()<10 && G[n5].size()<10)
{
G[i].push_back(n5);
G[n5].push_back(i);
}
G[i].unique();
G[n5].unique();
if(G[i].size()<10 && G[n4].size()<10)
{
G[i].push_back(n4);
G[n4].push_back(i);
}
G[i].unique();
G[n4].unique();
if(G[i].size()<10 && G[n3].size()<10)
{
G[i].push_back(n3);
G[n3].push_back(i);
}
G[i].unique();
G[n3].unique();
if(G[i].size()<10 && G[n2].size()<10)
{
G[i].push_back(n2);
G[n2].push_back(i);
}
G[i].unique();
G[n2].unique();
if(G[i].size()<10 && G[n1].size()<10)
{
G[i].push_back(n1);
G[n1].push_back(i);
}
G[i].unique();
G[n1].unique();
if(G[i].size()<5)
i--;
}
for(ui i=1;i<=n;++i)
{
cout<<"Node "<<i<<": " ;
for(auto it = G[i].begin(); it != G[i].end();++it)
{
cout<<" "<<*it;
}
cout<<endl;
}
/**************************************************************/
/* Random Walks & Expansion Tester */
/* */
/**************************************************************/
distribution.reset();
while(s--)
{
ui v;
v = distribution(generator);
vector< ui> pairs1;
for(ui m=1; m<=(sqrt(n)); ++m)
{
ui w=v;
std::uniform_int_distribution<ui> dVertex (1,G[w].size());
for(ui l=1; l<= log2(n);++l)
{
auto it=G[w].begin();
w = dVertex(generator);
advance(it,w-1);
w=*it;
}
pairs1.push_back(w);
}
sort(pairs1.begin(),pairs1.end());
ui collision= pairs1.size();
vector<ui>::iterator it;
it = unique (pairs1.begin(), pairs1.end());
pairs1.resize(distance(pairs1.begin(),it) );
collision = collision- pairs1.size();
if(collision < (((sqrt(n))*((sqrt(n))-1))/(2*n)))
{cout<<"Reject"<<endl;return 0;}
}
cout<<"Accept"<<endl;
return 0;
}
<commit_msg>Update TestingExpansion.cpp<commit_after>#include <bits/stdc++.h>
#include<chrono>
#include<random>
#define ui unsigned int
using namespace std;
int main()
{
/**************************************************************/
/* Generating Random Graph */
/* */
/**************************************************************/
ui n=10000;
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator (seed);
std::uniform_int_distribution<ui> distribution(1,n);
vector<list <ui> > G(n+1);
for(ui i=1;i<=n;++i)
{
ui n1=0,n2=0,n3=0,n4=0,n5=0;
while(n1==n2)
{
while(n2==n3)
{
while(n3==n4)
{
while(n4==n5)
{
while(n5==i || n5==0)
{
n5=distribution(generator);
}
n4=distribution(generator);
}
n3=distribution(generator);
}
n2=distribution(generator);
}
n1=distribution(generator);
}
G[i].unique();
G[n5].unique();
G[n4].unique();
G[n3].unique();
G[n2].unique();
G[n1].unique();
if(G[i].size()<10 && G[n5].size()<10)
{
G[i].push_back(n5);
G[n5].push_back(i);
}
G[i].unique();
G[n5].unique();
if(G[i].size()<10 && G[n4].size()<10)
{
G[i].push_back(n4);
G[n4].push_back(i);
}
G[i].unique();
G[n4].unique();
if(G[i].size()<10 && G[n3].size()<10)
{
G[i].push_back(n3);
G[n3].push_back(i);
}
G[i].unique();
G[n3].unique();
if(G[i].size()<10 && G[n2].size()<10)
{
G[i].push_back(n2);
G[n2].push_back(i);
}
G[i].unique();
G[n2].unique();
if(G[i].size()<10 && G[n1].size()<10)
{
G[i].push_back(n1);
G[n1].push_back(i);
}
G[i].unique();
G[n1].unique();
if(G[i].size()<5)
i--;
}
for(ui i=1;i<=n;++i)
{
cout<<"Node "<<i<<": " ;
for(auto it = G[i].begin(); it != G[i].end();++it)
{
cout<<" "<<*it;
}
cout<<endl;
}
distribution.reset();
ui s=50;
/**************************************************************/
/* Testing Expander Graph */
/* */
/**************************************************************/
while(s--)
{
ui v;
v = distribution(generator);
vector< ui> pairs1;
for(ui m=1; m<=(sqrt(n)); ++m)
{
ui w=v;
std::uniform_int_distribution<ui> dVertex (1,10);
for(ui l=1; l<= log2(n);++l)
{
ui temp=w;
list<ui>::iterator it=G[temp].begin();
w = dVertex(generator);
if(w<G[temp].size())
{
while(w--)
it++;
w=*it;
}
else
w=temp;
}
pairs1.push_back(w);
}
sort(pairs1.begin(),pairs1.end());
ui collision= pairs1.size();
vector<ui>::iterator it;
it = unique (pairs1.begin(), pairs1.end());
pairs1.resize(distance(pairs1.begin(),it) );
collision = collision- pairs1.size();
if(collision < (((sqrt(n))*((sqrt(n))-1))/(2*n)))
{cout<<"Reject"<<endl;return 0;}
}
cout<<"Accept"<<endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "DarcyWater.h"
#include "SteamTables.h"
template<>
Parameters valid_params<DarcyWater>()
{
Parameters params;
params.set<Real>("permeability")=1.0E-12; //intrinsic permeability, "k", in (m^2)
params.set<Real>("porosity")=0.10; //dimensionless but variable
params.set<Real>("rho_w")=1000.0; //water density, variable, in (kg/m^3)
params.set<Real>("mu_w")=0.001; //water dynamic viscosity, variable, in (Pa s)
params.set<Real>("c_f")=1.0;//"consolodation factor", use for modifing porosity from
// geomechanics
params.set<Real>("thermal_conductivity") = 1.0; //thermal thermal_conductivity, in (m^2/s)
params.set<Real>("time_coefficient") = 1.0; //leftover from example, carry it along for now
params.set<Real>("gravity") = 9.80665; //gravity acceleration, in (m/s^2)
params.set<Real>("water_specific_heat") = 4186.0; //units of (J/(kg K))
params.set<Real>("rock_specific_heat") = 1.00e3; //units of (J/(kg K))
params.set<Real>("rho_r") = 2.50e3; //rock density, in (kg/m^3)
params.set<Real>("gx")= 0.0; //x component of the gravity pressure vector
params.set<Real>("gy")= 0.0; //y component of the gravity pressure vector
params.set<Real>("gz")= 1.0; //z component of the gravity pressure vector
// params.set<RealGradient>("darcy_velocity")=0.0;
return params;
}
DarcyWater::DarcyWater(std::string name,
Parameters parameters,
unsigned int block_id,
std::vector<std::string> coupled_to,
std::vector<std::string> coupled_as)
:Material(name,parameters,block_id,coupled_to,coupled_as),
_input_permeability(parameters.get<Real>("permeability")),
_input_porosity(parameters.get<Real>("porosity")),
_input_rho_w(parameters.get<Real>("rho_w")),
_input_mu_w(parameters.get<Real>("mu_w")),
_input_c_f(parameters.get<Real>("c_f")),
_input_thermal_conductivity(parameters.get<Real>("thermal_conductivity")),
_input_time_coefficient(parameters.get<Real>("time_coefficient")),
_input_water_specif_heat(parameters.get<Real>("water_specific_heat")),
_input_rock_specific_heat(parameters.get<Real>("rock_specific_heat")),
_input_rho_r(parameters.get<Real>("rho_r")),
_input_gravity(parameters.get<Real>("gravity")),
_gx(parameters.get<Real>("gx")),
_gy(parameters.get<Real>("gy")),
_gz(parameters.get<Real>("gz")),
_permeability(declareRealProperty("permeability")),
_porosity(declareRealProperty("porosity")),
_rho_w(declareRealProperty("rho_w")),
_mu_w(declareRealProperty("mu_w")),
_c_f(declareRealProperty("c_f")),
_thermal_conductivity(declareRealProperty("thermal_conductivity")),
_time_coefficient(declareRealProperty("time_coefficient")),
_gravity(declareRealProperty("gravity")),
_water_specific_heat(declareRealProperty("water_specific_heat")),
_rock_specific_heat(declareRealProperty("rock_specific_heat")),
_rho_r(declareRealProperty("rho_r")),
_darcy_params(declareRealProperty("darcy_params")),
_darcy_flux(declareGradientProperty("darcy_pressure")),
_darcy_velocity(declareGradientProperty("darcy_velocity")),
_gravity_vector(declareRealVectorValueProperty("gravity_vector")),
_grad_p(coupledGrad("pressure")),
_pressure(coupledVal("pressure")),
_temperature(coupledVal("temperature")),
_grad_T(coupledGrad("temperature"))
{}
void
DarcyWater::computeProperties()
{
for(unsigned int qp=0; qp<_qrule->n_points(); qp++)
{
_gravity_vector[qp](1) = _gy;
_gravity_vector[qp](2) = _gz;
_permeability[qp] = _input_permeability;
_porosity[qp] = _input_porosity;
_rho_w[qp] = _input_rho_w;
_mu_w[qp] = _input_mu_w;
_thermal_conductivity[qp] = _input_thermal_conductivity;
_time_coefficient[qp] = _input_time_coefficient;
_gravity[qp] = _input_gravity;
SteamTables::steam_call_(_pressure[qp], _temperature[qp], _rho_w[qp], _mu_w[qp]);
_darcy_params[qp] = ((_permeability[qp] * _rho_w[qp]) / _mu_w[qp]);
_darcy_flux[qp] = -((_permeability)[qp] / (_mu_w)[qp]) * ((_grad_p[qp])+((_rho_w)[qp]*(_gravity)[qp]*(_gravity_vector)[qp]));
_darcy_velocity[qp] = (_darcy_flux[qp]) / _porosity[qp];
/*
std::cerr << "Pressure = " <<(_pressure)[qp]<<" Temp = "<<(_temperature)[qp]<<"\n";
//std::cerr << (_mu_w)[qp] <<" * "<< (_rho_w)[qp] <<" * "<< (_permeability)[qp] <<" = "<< (_darcy_params)[qp]<<"\n";
//std::cerr << "Darcy Flux Vector = " << (_darcy_flux)[qp];//<<"\n";
//std::cerr << "gravity Vector = " << (_gravity_vector)[qp];//<<"\n";
std::cerr << "Darcy Velocity = " <<(_darcy_velocity)[qp];//<<"\n";
// std::cerr << "Pressure = " <<(_pressure)[qp]<<" Temp = "<<(_temperature)[qp]<<"\n";
std::cerr << "grad Pressure = " <<(_grad_p)[qp];
std::cerr << "grad Temp = " <<(_grad_T)[qp];
std::cerr << "density = " <<(_rho_w)[qp]<< " viscosity = " <<(_mu_w)[qp]<<"\n";
//std::cerr << "viscosity = " <<(_mu_w)[qp]<<"\n";
std::cerr <<"\n";
*/
}
}
<commit_msg>Revised kernels<commit_after>#include "DarcyWater.h"
#include "SteamTables.h"
template<>
Parameters valid_params<DarcyWater>()
{
Parameters params;
params.set<Real>("permeability")=1.0E-12; //intrinsic permeability, "k", in (m^2)
params.set<Real>("porosity")=0.10; //dimensionless but variable
params.set<Real>("rho_w")=1000.0; //water density, variable, in (kg/m^3)
params.set<Real>("mu_w")=0.001; //water dynamic viscosity, variable, in (Pa s)
params.set<Real>("c_f")=1.0;//"consolodation factor", use for modifing porosity from
// geomechanics
params.set<Real>("thermal_conductivity") = 1.0; //thermal thermal_conductivity, in (m^2/s)
params.set<Real>("time_coefficient") = 1.0; //leftover from example, carry it along for now
params.set<Real>("gravity") = 9.80665; //gravity acceleration, in (m/s^2)
params.set<Real>("water_specific_heat") = 4186.0; //units of (J/(kg K))
params.set<Real>("rock_specific_heat") = 1.00e3; //units of (J/(kg K))
params.set<Real>("rho_r") = 2.50e3; //rock density, in (kg/m^3)
params.set<Real>("gx")= 0.0; //x component of the gravity pressure vector
params.set<Real>("gy")= 0.0; //y component of the gravity pressure vector
params.set<Real>("gz")= 1.0; //z component of the gravity pressure vector
// params.set<RealGradient>("darcy_velocity")=0.0;
return params;
}
DarcyWater::DarcyWater(std::string name,
Parameters parameters,
unsigned int block_id,
std::vector<std::string> coupled_to,
std::vector<std::string> coupled_as)
:Material(name,parameters,block_id,coupled_to,coupled_as),
_input_permeability(parameters.get<Real>("permeability")),
_input_porosity(parameters.get<Real>("porosity")),
_input_rho_w(parameters.get<Real>("rho_w")),
_input_mu_w(parameters.get<Real>("mu_w")),
_input_c_f(parameters.get<Real>("c_f")),
_input_thermal_conductivity(parameters.get<Real>("thermal_conductivity")),
_input_time_coefficient(parameters.get<Real>("time_coefficient")),
_input_water_specif_heat(parameters.get<Real>("water_specific_heat")),
_input_rock_specific_heat(parameters.get<Real>("rock_specific_heat")),
_input_rho_r(parameters.get<Real>("rho_r")),
_input_gravity(parameters.get<Real>("gravity")),
_gx(parameters.get<Real>("gx")),
_gy(parameters.get<Real>("gy")),
_gz(parameters.get<Real>("gz")),
_permeability(declareRealProperty("permeability")),
_porosity(declareRealProperty("porosity")),
_rho_w(declareRealProperty("rho_w")),
_mu_w(declareRealProperty("mu_w")),
_c_f(declareRealProperty("c_f")),
_thermal_conductivity(declareRealProperty("thermal_conductivity")),
_time_coefficient(declareRealProperty("time_coefficient")),
_gravity(declareRealProperty("gravity")),
_water_specific_heat(declareRealProperty("water_specific_heat")),
_rock_specific_heat(declareRealProperty("rock_specific_heat")),
_rho_r(declareRealProperty("rho_r")),
_darcy_params(declareRealProperty("darcy_params")),
_darcy_flux(declareGradientProperty("darcy_pressure")),
_darcy_velocity(declareGradientProperty("darcy_velocity")),
_gravity_vector(declareRealVectorValueProperty("gravity_vector")),
_grad_p(coupledGrad("pressure")),
_pressure(coupledVal("pressure")),
_temperature(coupledVal("temperature")),
_grad_T(coupledGrad("temperature"))
{}
void
DarcyWater::computeProperties()
{
for(unsigned int qp=0; qp<_qrule->n_points(); qp++)
{
_gravity_vector[qp](0) = _gx;
_gravity_vector[qp](1) = _gy;
_gravity_vector[qp](2) = _gz;
_permeability[qp] = _input_permeability;
_porosity[qp] = _input_porosity;
_rho_w[qp] = _input_rho_w;
_mu_w[qp] = _input_mu_w;
_thermal_conductivity[qp] = _input_thermal_conductivity;
_time_coefficient[qp] = _input_time_coefficient;
_gravity[qp] = _input_gravity;
SteamTables::steam_call_(_pressure[qp], _temperature[qp], _rho_w[qp], _mu_w[qp]);
_darcy_params[qp] = ((_permeability[qp] * _rho_w[qp]) / _mu_w[qp]);
_darcy_flux[qp] = -((_permeability)[qp] / (_mu_w)[qp]) * ((_grad_p[qp])+((_rho_w)[qp]*(_gravity)[qp]*(_gravity_vector)[qp]));
_darcy_velocity[qp] = (_darcy_flux[qp]) / _porosity[qp];
/*
std::cerr << "Pressure = " <<(_pressure)[qp]<<" Temp = "<<(_temperature)[qp]<<"\n";
//std::cerr << (_mu_w)[qp] <<" * "<< (_rho_w)[qp] <<" * "<< (_permeability)[qp] <<" = "<< (_darcy_params)[qp]<<"\n";
//std::cerr << "Darcy Flux Vector = " << (_darcy_flux)[qp];//<<"\n";
//std::cerr << "gravity Vector = " << (_gravity_vector)[qp];//<<"\n";
std::cerr << "Darcy Velocity = " <<(_darcy_velocity)[qp];//<<"\n";
// std::cerr << "Pressure = " <<(_pressure)[qp]<<" Temp = "<<(_temperature)[qp]<<"\n";
std::cerr << "grad Pressure = " <<(_grad_p)[qp];
std::cerr << "grad Temp = " <<(_grad_T)[qp];
std::cerr << "density = " <<(_rho_w)[qp]<< " viscosity = " <<(_mu_w)[qp]<<"\n";
//std::cerr << "viscosity = " <<(_mu_w)[qp]<<"\n";
std::cerr <<"\n";
*/
}
}
<|endoftext|> |
<commit_before>#ifndef MEMCACHED_PROTOCOL_HPP_
#define MEMCACHED_PROTOCOL_HPP_
#include <vector>
#include "errors.hpp"
#include <boost/variant.hpp>
#include "btree/backfill.hpp"
#include "btree/parallel_traversal.hpp" // TODO: sigh
#include "buffer_cache/mirrored/config.hpp"
#include "buffer_cache/types.hpp"
#include "containers/archive/boost_types.hpp"
#include "containers/archive/stl_types.hpp"
#include "memcached/queries.hpp"
#include "memcached/region.hpp"
#include "protocol_api.hpp"
#include "rpc/serialize_macros.hpp"
#include "timestamps.hpp"
#include "perfmon_types.hpp"
#include "repli_timestamp.hpp"
class real_superblock_t;
write_message_t &operator<<(write_message_t &msg, const intrusive_ptr_t<data_buffer_t> &buf);
archive_result_t deserialize(read_stream_t *s, intrusive_ptr_t<data_buffer_t> *buf);
write_message_t &operator<<(write_message_t &msg, const rget_result_t &iter);
archive_result_t deserialize(read_stream_t *s, rget_result_t *iter);
RDB_DECLARE_SERIALIZABLE(get_query_t);
RDB_DECLARE_SERIALIZABLE(rget_query_t);
RDB_DECLARE_SERIALIZABLE(distribution_get_query_t);
RDB_DECLARE_SERIALIZABLE(get_result_t);
RDB_DECLARE_SERIALIZABLE(key_with_data_buffer_t);
RDB_DECLARE_SERIALIZABLE(rget_result_t);
RDB_DECLARE_SERIALIZABLE(distribution_result_t);
RDB_DECLARE_SERIALIZABLE(get_cas_mutation_t);
RDB_DECLARE_SERIALIZABLE(sarc_mutation_t);
RDB_DECLARE_SERIALIZABLE(delete_mutation_t);
RDB_DECLARE_SERIALIZABLE(incr_decr_mutation_t);
RDB_DECLARE_SERIALIZABLE(incr_decr_result_t);
RDB_DECLARE_SERIALIZABLE(append_prepend_mutation_t);
RDB_DECLARE_SERIALIZABLE(backfill_atom_t);
/* `memcached_protocol_t` is a container struct. It's never actually
instantiated; it just exists to pass around all the memcached-related types and
functions that the query-routing logic needs to know about. */
class memcached_protocol_t {
public:
typedef key_range_t region_t;
struct temporary_cache_t { };
struct read_response_t {
typedef boost::variant<get_result_t, rget_result_t, distribution_result_t> result_t;
read_response_t() { }
read_response_t(const read_response_t& r) : result(r.result) { }
explicit read_response_t(const result_t& r) : result(r) { }
result_t result;
RDB_MAKE_ME_SERIALIZABLE_1(result);
};
struct read_t {
typedef boost::variant<get_query_t, rget_query_t, distribution_get_query_t> query_t;
key_range_t get_region() const THROWS_NOTHING;
read_t shard(const key_range_t ®ion) const THROWS_NOTHING;
read_response_t unshard(std::vector<read_response_t> responses, temporary_cache_t *cache) const THROWS_NOTHING;
read_t() { }
read_t(const read_t& r) : query(r.query), effective_time(r.effective_time) { }
read_t(const query_t& q, exptime_t et) : query(q), effective_time(et) { }
query_t query;
exptime_t effective_time;
RDB_MAKE_ME_SERIALIZABLE_1(query);
};
struct write_response_t {
typedef boost::variant<get_result_t, set_result_t, delete_result_t, incr_decr_result_t, append_prepend_result_t> result_t;
write_response_t() { }
write_response_t(const write_response_t& w) : result(w.result) { }
explicit write_response_t(const result_t& rv) : result(rv) { }
result_t result;
RDB_MAKE_ME_SERIALIZABLE_1(result);
};
struct write_t {
typedef boost::variant<get_cas_mutation_t, sarc_mutation_t, delete_mutation_t, incr_decr_mutation_t, append_prepend_mutation_t> query_t;
key_range_t get_region() const THROWS_NOTHING;
write_t shard(key_range_t region) const THROWS_NOTHING;
write_response_t unshard(std::vector<write_response_t> responses, temporary_cache_t *cache) const THROWS_NOTHING;
write_t() { }
write_t(const write_t& w) : mutation(w.mutation), proposed_cas(w.proposed_cas), effective_time(w.effective_time) { }
write_t(const query_t& m, cas_t pc, exptime_t et) : mutation(m), proposed_cas(pc), effective_time(et) { }
query_t mutation;
cas_t proposed_cas;
exptime_t effective_time; /* so operations are deterministic even with expiration */
RDB_MAKE_ME_SERIALIZABLE_2(mutation, proposed_cas);
};
struct backfill_chunk_t {
struct delete_key_t {
store_key_t key;
repli_timestamp_t recency;
delete_key_t() { }
delete_key_t(const store_key_t& key_, const repli_timestamp_t& recency_) : key(key_), recency(recency_) { }
RDB_MAKE_ME_SERIALIZABLE_1(key);
};
struct delete_range_t {
key_range_t range;
delete_range_t() { }
explicit delete_range_t(const key_range_t& _range) : range(_range) { }
RDB_MAKE_ME_SERIALIZABLE_1(range);
};
struct key_value_pair_t {
backfill_atom_t backfill_atom;
key_value_pair_t() { }
explicit key_value_pair_t(const backfill_atom_t& backfill_atom_) : backfill_atom(backfill_atom_) { }
RDB_MAKE_ME_SERIALIZABLE_1(backfill_atom);
};
backfill_chunk_t() { }
explicit backfill_chunk_t(boost::variant<delete_range_t, delete_key_t, key_value_pair_t> val_) : val(val_) { }
boost::variant<delete_range_t, delete_key_t, key_value_pair_t> val;
static backfill_chunk_t delete_range(const key_range_t& range) {
return backfill_chunk_t(delete_range_t(range));
}
static backfill_chunk_t delete_key(const store_key_t& key, const repli_timestamp_t& recency) {
return backfill_chunk_t(delete_key_t(key, recency));
}
static backfill_chunk_t set_key(const backfill_atom_t& key) {
return backfill_chunk_t(key_value_pair_t(key));
}
RDB_MAKE_ME_SERIALIZABLE_1(val);
};
typedef traversal_progress_combiner_t backfill_progress_t;
class store_t : public store_view_t<memcached_protocol_t> {
typedef region_map_t<memcached_protocol_t, binary_blob_t> metainfo_t;
boost::scoped_ptr<standard_serializer_t> serializer;
mirrored_cache_config_t cache_dynamic_config;
boost::scoped_ptr<cache_t> cache;
boost::scoped_ptr<btree_slice_t> btree;
order_source_t order_source;
fifo_enforcer_source_t token_source;
fifo_enforcer_sink_t token_sink;
public:
store_t(const std::string& filename, bool create, perfmon_collection_t *collection = NULL);
~store_t();
void new_read_token(boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token_out);
void new_write_token(boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token_out);
metainfo_t get_metainfo(
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void set_metainfo(
const metainfo_t &new_metainfo,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
memcached_protocol_t::read_response_t read(
DEBUG_ONLY(const metainfo_t& expected_metainfo, )
const memcached_protocol_t::read_t &read,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
memcached_protocol_t::write_response_t write(
DEBUG_ONLY(const metainfo_t& expected_metainfo, )
const metainfo_t& new_metainfo,
const memcached_protocol_t::write_t &write,
transition_timestamp_t timestamp,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
bool send_backfill(
const region_map_t<memcached_protocol_t, state_timestamp_t> &start_point,
const boost::function<bool(const metainfo_t&)> &should_backfill,
const boost::function<void(memcached_protocol_t::backfill_chunk_t)> &chunk_fun,
backfill_progress_t *progress_out,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void receive_backfill(
const memcached_protocol_t::backfill_chunk_t &chunk,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void reset_data(
memcached_protocol_t::region_t subregion,
const metainfo_t &new_metainfo,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
private:
region_map_t<memcached_protocol_t, binary_blob_t> get_metainfo_internal(transaction_t* txn, buf_lock_t* sb_buf) const THROWS_NOTHING;
void acquire_superblock_for_read(
access_t access,
bool snapshot,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token,
boost::scoped_ptr<transaction_t> &txn_out,
boost::scoped_ptr<real_superblock_t> &sb_out,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void acquire_superblock_for_backfill(
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token,
boost::scoped_ptr<transaction_t> &txn_out,
boost::scoped_ptr<real_superblock_t> &sb_out,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void acquire_superblock_for_write(
access_t access,
int expected_change_count,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token,
boost::scoped_ptr<transaction_t> &txn_out,
boost::scoped_ptr<real_superblock_t> &sb_out,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void check_and_update_metainfo(
DEBUG_ONLY(const metainfo_t& expected_metainfo, )
const metainfo_t &new_metainfo,
transaction_t *txn,
real_superblock_t *superbloc) const
THROWS_NOTHING;
metainfo_t check_metainfo(
DEBUG_ONLY(const metainfo_t& expected_metainfo, )
transaction_t *txn,
real_superblock_t *superbloc) const
THROWS_NOTHING;
void update_metainfo(const metainfo_t &old_metainfo, const metainfo_t &new_metainfo, transaction_t *txn, real_superblock_t *superbloc) const THROWS_NOTHING;
perfmon_collection_t *perfmon_collection;
};
};
#endif /* MEMCACHED_PROTOCOL_HPP_ */
<commit_msg>fixing expiration, effective_time in memcached read and write operations was not being serialized<commit_after>#ifndef MEMCACHED_PROTOCOL_HPP_
#define MEMCACHED_PROTOCOL_HPP_
#include <vector>
#include "errors.hpp"
#include <boost/variant.hpp>
#include "btree/backfill.hpp"
#include "btree/parallel_traversal.hpp" // TODO: sigh
#include "buffer_cache/mirrored/config.hpp"
#include "buffer_cache/types.hpp"
#include "containers/archive/boost_types.hpp"
#include "containers/archive/stl_types.hpp"
#include "memcached/queries.hpp"
#include "memcached/region.hpp"
#include "protocol_api.hpp"
#include "rpc/serialize_macros.hpp"
#include "timestamps.hpp"
#include "perfmon_types.hpp"
#include "repli_timestamp.hpp"
class real_superblock_t;
write_message_t &operator<<(write_message_t &msg, const intrusive_ptr_t<data_buffer_t> &buf);
archive_result_t deserialize(read_stream_t *s, intrusive_ptr_t<data_buffer_t> *buf);
write_message_t &operator<<(write_message_t &msg, const rget_result_t &iter);
archive_result_t deserialize(read_stream_t *s, rget_result_t *iter);
RDB_DECLARE_SERIALIZABLE(get_query_t);
RDB_DECLARE_SERIALIZABLE(rget_query_t);
RDB_DECLARE_SERIALIZABLE(distribution_get_query_t);
RDB_DECLARE_SERIALIZABLE(get_result_t);
RDB_DECLARE_SERIALIZABLE(key_with_data_buffer_t);
RDB_DECLARE_SERIALIZABLE(rget_result_t);
RDB_DECLARE_SERIALIZABLE(distribution_result_t);
RDB_DECLARE_SERIALIZABLE(get_cas_mutation_t);
RDB_DECLARE_SERIALIZABLE(sarc_mutation_t);
RDB_DECLARE_SERIALIZABLE(delete_mutation_t);
RDB_DECLARE_SERIALIZABLE(incr_decr_mutation_t);
RDB_DECLARE_SERIALIZABLE(incr_decr_result_t);
RDB_DECLARE_SERIALIZABLE(append_prepend_mutation_t);
RDB_DECLARE_SERIALIZABLE(backfill_atom_t);
/* `memcached_protocol_t` is a container struct. It's never actually
instantiated; it just exists to pass around all the memcached-related types and
functions that the query-routing logic needs to know about. */
class memcached_protocol_t {
public:
typedef key_range_t region_t;
struct temporary_cache_t { };
struct read_response_t {
typedef boost::variant<get_result_t, rget_result_t, distribution_result_t> result_t;
read_response_t() { }
read_response_t(const read_response_t& r) : result(r.result) { }
explicit read_response_t(const result_t& r) : result(r) { }
result_t result;
RDB_MAKE_ME_SERIALIZABLE_1(result);
};
struct read_t {
typedef boost::variant<get_query_t, rget_query_t, distribution_get_query_t> query_t;
key_range_t get_region() const THROWS_NOTHING;
read_t shard(const key_range_t ®ion) const THROWS_NOTHING;
read_response_t unshard(std::vector<read_response_t> responses, temporary_cache_t *cache) const THROWS_NOTHING;
read_t() { }
read_t(const read_t& r) : query(r.query), effective_time(r.effective_time) { }
read_t(const query_t& q, exptime_t et) : query(q), effective_time(et) { }
query_t query;
exptime_t effective_time;
RDB_MAKE_ME_SERIALIZABLE_2(query, effective_time);
};
struct write_response_t {
typedef boost::variant<get_result_t, set_result_t, delete_result_t, incr_decr_result_t, append_prepend_result_t> result_t;
write_response_t() { }
write_response_t(const write_response_t& w) : result(w.result) { }
explicit write_response_t(const result_t& rv) : result(rv) { }
result_t result;
RDB_MAKE_ME_SERIALIZABLE_1(result);
};
struct write_t {
typedef boost::variant<get_cas_mutation_t, sarc_mutation_t, delete_mutation_t, incr_decr_mutation_t, append_prepend_mutation_t> query_t;
key_range_t get_region() const THROWS_NOTHING;
write_t shard(key_range_t region) const THROWS_NOTHING;
write_response_t unshard(std::vector<write_response_t> responses, temporary_cache_t *cache) const THROWS_NOTHING;
write_t() { }
write_t(const write_t& w) : mutation(w.mutation), proposed_cas(w.proposed_cas), effective_time(w.effective_time) { }
write_t(const query_t& m, cas_t pc, exptime_t et) : mutation(m), proposed_cas(pc), effective_time(et) { }
query_t mutation;
cas_t proposed_cas;
exptime_t effective_time; /* so operations are deterministic even with expiration */
RDB_MAKE_ME_SERIALIZABLE_3(mutation, proposed_cas, effective_time);
};
struct backfill_chunk_t {
struct delete_key_t {
store_key_t key;
repli_timestamp_t recency;
delete_key_t() { }
delete_key_t(const store_key_t& key_, const repli_timestamp_t& recency_) : key(key_), recency(recency_) { }
RDB_MAKE_ME_SERIALIZABLE_1(key);
};
struct delete_range_t {
key_range_t range;
delete_range_t() { }
explicit delete_range_t(const key_range_t& _range) : range(_range) { }
RDB_MAKE_ME_SERIALIZABLE_1(range);
};
struct key_value_pair_t {
backfill_atom_t backfill_atom;
key_value_pair_t() { }
explicit key_value_pair_t(const backfill_atom_t& backfill_atom_) : backfill_atom(backfill_atom_) { }
RDB_MAKE_ME_SERIALIZABLE_1(backfill_atom);
};
backfill_chunk_t() { }
explicit backfill_chunk_t(boost::variant<delete_range_t, delete_key_t, key_value_pair_t> val_) : val(val_) { }
boost::variant<delete_range_t, delete_key_t, key_value_pair_t> val;
static backfill_chunk_t delete_range(const key_range_t& range) {
return backfill_chunk_t(delete_range_t(range));
}
static backfill_chunk_t delete_key(const store_key_t& key, const repli_timestamp_t& recency) {
return backfill_chunk_t(delete_key_t(key, recency));
}
static backfill_chunk_t set_key(const backfill_atom_t& key) {
return backfill_chunk_t(key_value_pair_t(key));
}
RDB_MAKE_ME_SERIALIZABLE_1(val);
};
typedef traversal_progress_combiner_t backfill_progress_t;
class store_t : public store_view_t<memcached_protocol_t> {
typedef region_map_t<memcached_protocol_t, binary_blob_t> metainfo_t;
boost::scoped_ptr<standard_serializer_t> serializer;
mirrored_cache_config_t cache_dynamic_config;
boost::scoped_ptr<cache_t> cache;
boost::scoped_ptr<btree_slice_t> btree;
order_source_t order_source;
fifo_enforcer_source_t token_source;
fifo_enforcer_sink_t token_sink;
public:
store_t(const std::string& filename, bool create, perfmon_collection_t *collection = NULL);
~store_t();
void new_read_token(boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token_out);
void new_write_token(boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token_out);
metainfo_t get_metainfo(
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void set_metainfo(
const metainfo_t &new_metainfo,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
memcached_protocol_t::read_response_t read(
DEBUG_ONLY(const metainfo_t& expected_metainfo, )
const memcached_protocol_t::read_t &read,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
memcached_protocol_t::write_response_t write(
DEBUG_ONLY(const metainfo_t& expected_metainfo, )
const metainfo_t& new_metainfo,
const memcached_protocol_t::write_t &write,
transition_timestamp_t timestamp,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
bool send_backfill(
const region_map_t<memcached_protocol_t, state_timestamp_t> &start_point,
const boost::function<bool(const metainfo_t&)> &should_backfill,
const boost::function<void(memcached_protocol_t::backfill_chunk_t)> &chunk_fun,
backfill_progress_t *progress_out,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void receive_backfill(
const memcached_protocol_t::backfill_chunk_t &chunk,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void reset_data(
memcached_protocol_t::region_t subregion,
const metainfo_t &new_metainfo,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
private:
region_map_t<memcached_protocol_t, binary_blob_t> get_metainfo_internal(transaction_t* txn, buf_lock_t* sb_buf) const THROWS_NOTHING;
void acquire_superblock_for_read(
access_t access,
bool snapshot,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token,
boost::scoped_ptr<transaction_t> &txn_out,
boost::scoped_ptr<real_superblock_t> &sb_out,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void acquire_superblock_for_backfill(
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> &token,
boost::scoped_ptr<transaction_t> &txn_out,
boost::scoped_ptr<real_superblock_t> &sb_out,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void acquire_superblock_for_write(
access_t access,
int expected_change_count,
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> &token,
boost::scoped_ptr<transaction_t> &txn_out,
boost::scoped_ptr<real_superblock_t> &sb_out,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
void check_and_update_metainfo(
DEBUG_ONLY(const metainfo_t& expected_metainfo, )
const metainfo_t &new_metainfo,
transaction_t *txn,
real_superblock_t *superbloc) const
THROWS_NOTHING;
metainfo_t check_metainfo(
DEBUG_ONLY(const metainfo_t& expected_metainfo, )
transaction_t *txn,
real_superblock_t *superbloc) const
THROWS_NOTHING;
void update_metainfo(const metainfo_t &old_metainfo, const metainfo_t &new_metainfo, transaction_t *txn, real_superblock_t *superbloc) const THROWS_NOTHING;
perfmon_collection_t *perfmon_collection;
};
};
#endif /* MEMCACHED_PROTOCOL_HPP_ */
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "pwfile.h"
#include <platform/cbassert.h>
#include <cstring>
#include <mutex>
#include <stdio.h>
#include <stdlib.h>
#include <stdexcept>
#include <string>
#include <unordered_map>
static std::mutex uhash_lock;
// Map of username -> password.
typedef std::unordered_map<std::string, std::string> user_hashtable_t;
static user_hashtable_t user_ht;
static void kill_whitey(char *s)
{
for (size_t i = strlen(s) - 1; i > 0 && isspace(s[i]); i--) {
s[i] = '\0';
}
}
static const char *get_isasl_filename(void)
{
return getenv("ISASL_PWFILE");
}
void free_user_ht(void)
{
user_ht.clear();
}
static void store_pw(user_hashtable_t& ht,
const char *username,
const char *password)
{
ht.emplace(std::make_pair(username, password));
}
bool find_pw(const std::string& user, std::string& password) {
std::lock_guard<std::mutex> guard(uhash_lock);
auto it = user_ht.find(user);
if (it != user_ht.end()) {
password = it->second;
return true;
} else {
return false;
}
}
cbsasl_error_t load_user_db(void)
{
FILE *sfile;
char up[128];
const char *filename = get_isasl_filename();
if (!filename) {
return CBSASL_OK;
}
sfile = fopen(filename, "r");
if (!sfile) {
return CBSASL_FAIL;
}
try {
user_hashtable_t new_ut;
/* File has lines that are newline terminated. */
/* File may have comment lines that must being with '#'. */
/* Lines should look like... */
/* <NAME><whitespace><PASSWORD><whitespace><CONFIG><optional_whitespace> */
/* */
while (fgets(up, sizeof(up), sfile)) {
if (up[0] != '#') {
char *uname = up, *p = up, *cfg = NULL;
kill_whitey(up);
while (*p && !isspace(p[0])) {
p++;
}
/* If p is pointing at a NUL, there's nothing after the username. */
if (p[0] != '\0') {
p[0] = '\0';
p++;
}
/* p now points to the first character after the (now) */
/* null-terminated username. */
while (*p && isspace(*p)) {
p++;
}
/* p now points to the first non-whitespace character */
/* after the above */
cfg = p;
if (cfg[0] != '\0') {
/* move cfg past the password */
while (*cfg && !isspace(cfg[0])) {
cfg++;
}
if (cfg[0] != '\0') {
cfg[0] = '\0';
cfg++;
/* Skip whitespace */
while (*cfg && isspace(cfg[0])) {
cfg++;
}
}
}
/* Note: cfg currently unused and hence not stored in hash. */
store_pw(new_ut, uname, p);
}
}
fclose(sfile);
/* Replace the current configuration with the new one */
{
std::lock_guard<std::mutex> guard(uhash_lock);
free_user_ht();
user_ht = new_ut;
}
} catch (std::bad_alloc&) {
fclose(sfile);
return CBSASL_NOMEM;
}
return CBSASL_OK;
}
<commit_msg>Refactor: Use STL functions to parse isasl.pw<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "pwfile.h"
#include <cstring>
#include <iterator>
#include <mutex>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
// Map of username -> password.
typedef std::unordered_map<std::string, std::string> user_hashtable_t;
// The mutex protecting access to the user/password map
static std::mutex uhash_lock;
// The map containing the user/password mappings
static user_hashtable_t user_ht;
void free_user_ht(void) {
user_ht.clear();
}
bool find_pw(const std::string& user, std::string& password) {
std::lock_guard<std::mutex> guard(uhash_lock);
auto it = user_ht.find(user);
if (it != user_ht.end()) {
password = it->second;
return true;
} else {
return false;
}
}
cbsasl_error_t load_user_db(void) {
const char* filename = getenv("ISASL_PWFILE");
if (!filename) {
return CBSASL_OK;
}
FILE* sfile = fopen(filename, "r");
if (sfile == nullptr) {
return CBSASL_FAIL;
}
try {
user_hashtable_t new_ut;
/* File has lines that are newline terminated.
* File may have comment lines that must being with '#'.
* Lines should look like...
* <NAME><whitespace><PASSWORD><whitespace><CONFIG><optional_whitespace>
*/
char up[128];
while (fgets(up, sizeof(up), sfile)) {
if (up[0] != '#') {
using std::istream_iterator;
using std::vector;
using std::string;
std::istringstream iss(up);
vector<string> tokens{istream_iterator<string>{iss},
istream_iterator<string>{}};
if (tokens.empty()) {
// empty line
continue;
}
std::string passwd;
if (tokens.size() > 1) {
passwd = tokens[1];
}
new_ut.emplace(std::make_pair(tokens[0], passwd));
}
}
fclose(sfile);
/* Replace the current configuration with the new one */
{
std::lock_guard<std::mutex> guard(uhash_lock);
free_user_ht();
user_ht = new_ut;
}
} catch (std::bad_alloc&) {
fclose(sfile);
return CBSASL_NOMEM;
}
return CBSASL_OK;
}
<|endoftext|> |
<commit_before>#pragma once
#include <exception>
#include <regex>
// ----------------------------------------------------------------------
namespace virus_name
{
namespace _internal
{
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#endif
const std::regex cdc{"^([A-Z][A-Z][A-Z]?) "};
// [1] - type+subtype, [2] - host, [3] - location, [4] - isolation-number (omitting leading zeros), [5] - century, [6] - year (2 last digit), [7] - reassortant and passage
const std::regex international{"^([AB][^/]*)/(?:([^/]+)/)?([^/]+)/0*([^/]+)/(19|20)?(\\d\\d)(?:(?:\\s+|__)(.+))?$"};
inline std::string make_year(const std::smatch& m)
{
std::string year;
if (m[5].length())
year = m[5].str() + m[6].str();
else if (m[6].str()[0] > '2')
year = "19" + m[6].str();
else
year = "20" + m[6].str();
return year;
}
#pragma GCC diagnostic pop
}
// ----------------------------------------------------------------------
class Unrecognized : public std::exception {};
// ----------------------------------------------------------------------
std::string normalize(std::string name);
// ----------------------------------------------------------------------
std::string normalize(std::string name);
// returned cdc abbreviation starts with #
inline std::string location(std::string name)
{
using namespace _internal;
std::string location;
std::smatch m;
if (std::regex_search(name, m, cdc))
location = "#" + m[1].str();
else if (std::regex_match(name, m, international))
location = m[3].str();
else
throw Unrecognized{};
return location;
}
// ----------------------------------------------------------------------
inline std::string virus_type(std::string name)
{
using namespace _internal;
std::string virus_type;
std::smatch m;
if (std::regex_match(name, m, international))
virus_type = m[1].str();
else
throw Unrecognized{};
return virus_type;
} // AntigenSerum::virus_type
// ----------------------------------------------------------------------
inline std::string year(std::string name)
{
using namespace _internal;
std::string year;
std::smatch m;
if (std::regex_match(name, m, international))
year = make_year(m);
else
throw Unrecognized{};
return year;
} // AntigenSerum::year
// ----------------------------------------------------------------------
inline void split(std::string name, std::string& virus_type, std::string& host, std::string& location, std::string& isolation, std::string& year, std::string& passage)
{
using namespace _internal;
std::smatch m;
if (std::regex_match(name, m, international)) {
virus_type = m[1].str();
host = m[2].str();
location = m[3].str();
isolation = m[4].str();
year = make_year(m);
passage = m[7].str();
}
else
throw Unrecognized{};
}
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>better error reporting when virus name parsing failed<commit_after>#pragma once
#include <exception>
#include <regex>
// ----------------------------------------------------------------------
namespace virus_name
{
namespace _internal
{
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#endif
const std::regex cdc{"^([A-Z][A-Z][A-Z]?) "};
// [1] - type+subtype, [2] - host, [3] - location, [4] - isolation-number (omitting leading zeros), [5] - century, [6] - year (2 last digit), [7] - reassortant and passage
const std::regex international{"^([AB][^/]*)/(?:([^/]+)/)?([^/]+)/0*([^/]+)/(19|20)?(\\d\\d)(?:(?:\\s+|__)(.+))?$"};
inline std::string make_year(const std::smatch& m)
{
std::string year;
if (m[5].length())
year = m[5].str() + m[6].str();
else if (m[6].str()[0] > '2')
year = "19" + m[6].str();
else
year = "20" + m[6].str();
return year;
}
#pragma GCC diagnostic pop
}
// ----------------------------------------------------------------------
class Unrecognized : public std::runtime_error { public: using std::runtime_error::runtime_error; };
// ----------------------------------------------------------------------
std::string normalize(std::string name);
// ----------------------------------------------------------------------
std::string normalize(std::string name);
// returned cdc abbreviation starts with #
inline std::string location(std::string name)
{
using namespace _internal;
std::string location;
std::smatch m;
if (std::regex_search(name, m, cdc))
location = "#" + m[1].str();
else if (std::regex_match(name, m, international))
location = m[3].str();
else
throw Unrecognized{"No location in " + name};
return location;
}
// ----------------------------------------------------------------------
inline std::string virus_type(std::string name)
{
using namespace _internal;
std::string virus_type;
std::smatch m;
if (std::regex_match(name, m, international))
virus_type = m[1].str();
else
throw Unrecognized{"No virus_type in " + name};
return virus_type;
} // AntigenSerum::virus_type
// ----------------------------------------------------------------------
inline std::string year(std::string name)
{
using namespace _internal;
std::string year;
std::smatch m;
if (std::regex_match(name, m, international))
year = make_year(m);
else
throw Unrecognized{"No year in " + name};
return year;
} // AntigenSerum::year
// ----------------------------------------------------------------------
inline void split(std::string name, std::string& virus_type, std::string& host, std::string& location, std::string& isolation, std::string& year, std::string& passage)
{
using namespace _internal;
std::smatch m;
if (std::regex_match(name, m, international)) {
virus_type = m[1].str();
host = m[2].str();
location = m[3].str();
isolation = m[4].str();
year = make_year(m);
passage = m[7].str();
}
else
throw Unrecognized{"Cannot split " + name};
}
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2021 Intel Corporation. All Rights Reserved.
#include <easylogging++.h>
#ifdef BUILD_SHARED_LIBS
// With static linkage, ELPP is initialized by librealsense, so doing it here will
// create errors. When we're using the shared .so/.dll, the two are separate and we have
// to initialize ours if we want to use the APIs!
INITIALIZE_EASYLOGGINGPP
#endif
// Let Catch define its own main() function
#define CATCH_CONFIG_MAIN
#include "../../catch.h"
#include <librealsense2/rs.hpp>
#include <librealsense2/rsutil.h>
using namespace rs2;
// structure of a matrix 4 X 4, representing rotation and translation as following:
// pos_and_rot[i][j] is
// _ _
// | | |
// | rotation | translation |
// | (3x3) | (3x1) |
// | _________ |____________ |
// | 0 | 1 |
// |_ (1x3) | (1x1) _|
//
struct position_and_rotation {
double pos_and_rot[4][4];
// rotation tolerance - units are in cosinus of radians
const double rotation_tolerance = 0.000001;
// translation tolerance - units are in meters
const double translation_tolerance = 0.000001; // 0.001mm
position_and_rotation operator* (const position_and_rotation& other)
{
position_and_rotation product;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
product.pos_and_rot[i][j] = 0;
for (int k = 0; k < 4; k++)
product.pos_and_rot[i][j] += pos_and_rot[i][k] * other.pos_and_rot[k][j];
}
}
return product;
}
bool equals(const position_and_rotation& other)
{
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
{
double tolerance = rotation_tolerance;
if (j == 3) tolerance = translation_tolerance;
if (fabs(pos_and_rot[i][j] - other.pos_and_rot[i][j]) > tolerance)
{
std::cout << "i,j = " << i << "," << j << ", pos_and_rot[i][j] = " << (double)pos_and_rot[i][j] << ", tolerance = " << tolerance << std::endl;
return false;
}
}
return true;
}
bool is_identity()
{
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
{
double target = 0.0;
if (i == j) target = 1.0;
double tolerance = rotation_tolerance;
if (j == 3) tolerance = translation_tolerance;
if (fabs(pos_and_rot[i][j] - target) > tolerance)
{
std::cout << "i,j = " << i << "," << j << ", pos_and_rot[i][j] = " << (double)pos_and_rot[i][j] << ", target = " << (double)target << ", tolerance = " << tolerance << std::endl;
return false;
}
}
return true;
}
};
// This method takes in consideration that the totation array is given in the order of a column major 3x3 matrix
position_and_rotation matrix_4_by_4_from_translation_and_rotation(const float* position, const float* rotation)
{
position_and_rotation pos_rot;
pos_rot.pos_and_rot[0][0] = static_cast<double>(rotation[0]);
pos_rot.pos_and_rot[1][0] = static_cast<double>(rotation[1]);
pos_rot.pos_and_rot[2][0] = static_cast<double>(rotation[2]);
pos_rot.pos_and_rot[0][1] = static_cast<double>(rotation[3]);
pos_rot.pos_and_rot[1][1] = static_cast<double>(rotation[4]);
pos_rot.pos_and_rot[2][1] = static_cast<double>(rotation[5]);
pos_rot.pos_and_rot[0][2] = static_cast<double>(rotation[6]);
pos_rot.pos_and_rot[1][2] = static_cast<double>(rotation[7]);
pos_rot.pos_and_rot[2][2] = static_cast<double>(rotation[8]);
pos_rot.pos_and_rot[3][0] = 0.0;
pos_rot.pos_and_rot[3][1] = 0.0;
pos_rot.pos_and_rot[3][2] = 0.0;
pos_rot.pos_and_rot[0][3] = static_cast<double>(position[0]);
pos_rot.pos_and_rot[1][3] = static_cast<double>(position[1]);
pos_rot.pos_and_rot[2][3] = static_cast<double>(position[2]);
pos_rot.pos_and_rot[3][3] = 1.0;
return pos_rot;
}
// checking the extrinsics graph
// steps are:
// 1. get all the profiles
// 2. for each pair of these profiles:
// check that:
// point P(x,y,z,head,pitch,roll) in profile A transformed to profile B coordinates, and then transformed back to profile A coordinates == same point P
TEST_CASE("Extrinsics graph - matrices 4x4", "[live]")
{
rs2::context ctx;
auto list = ctx.query_devices();
for (auto&& device : list)
{
std::cout << "device: " << device.get_info(RS2_CAMERA_INFO_NAME) << std::endl;
auto sensors = device.query_sensors();
// getting stream profiles from all sensors
std::vector<rs2::stream_profile> profiles;
for (auto&& sensor : sensors)
{
std::vector<rs2::stream_profile> stream_profiles = sensor.get_stream_profiles();
for (auto&& profile : stream_profiles)
{
profiles.push_back(profile);
}
}
float start_point[3] = { 1.f, 2.f, 3.f };
for (int i = 0; i < profiles.size() - 2; ++i)
{
for (int j = i + 1; j < profiles.size() - 1; ++j)
{
rs2_extrinsics extr_i_to_j = profiles[i].get_extrinsics_to(profiles[j]);
rs2_extrinsics extr_j_to_i = profiles[j].get_extrinsics_to(profiles[i]);
position_and_rotation pr_i_to_j = matrix_4_by_4_from_translation_and_rotation(extr_i_to_j.translation, extr_i_to_j.rotation);
position_and_rotation pr_j_to_i = matrix_4_by_4_from_translation_and_rotation(extr_j_to_i.translation, extr_j_to_i.rotation);
position_and_rotation product = pr_i_to_j * pr_j_to_i;
// checking that product of extrinsics from i to j with extrinsiscs from j to i is identity matrix
REQUIRE(product.is_identity());
// checking with API rs2_transform_point_to_point
float transformed_point[3];
rs2_transform_point_to_point(transformed_point, &extr_i_to_j, start_point);
float end_point[3];
rs2_transform_point_to_point(end_point, &extr_j_to_i, transformed_point);
bool res = true;
for (int t = 0; t < 3; ++t)
{
if (fabs(start_point[t] - end_point[t]) > 0.001f)
res = false;
}
// checking that transforming a point with extrinsiscs from i to j and the from j to i
// gets back to the initial point
REQUIRE(res);
// checking that a point and orientation, represented by a 4x4 matrix
// is equal to the result of transforming it by the extrinsics
// from profile A to B, and then from profile B to A
position_and_rotation point_and_orientation;
// rotation part with 30 degrees rotation on each axis
point_and_orientation.pos_and_rot[0][0] = 0.75f;
point_and_orientation.pos_and_rot[0][1] = -0.4330127f;
point_and_orientation.pos_and_rot[0][2] = 0.5f;
point_and_orientation.pos_and_rot[1][0] = 0.649519f;
point_and_orientation.pos_and_rot[1][1] = 0.625f;
point_and_orientation.pos_and_rot[1][2] = -0.4330127f;
point_and_orientation.pos_and_rot[2][0] = -0.125f;
point_and_orientation.pos_and_rot[2][1] = 0.649519f;
point_and_orientation.pos_and_rot[2][2] = 0.75f;
point_and_orientation.pos_and_rot[3][0] = 0.f;
point_and_orientation.pos_and_rot[3][1] = 0.f;
point_and_orientation.pos_and_rot[3][2] = 0.f;
// translation part
point_and_orientation.pos_and_rot[0][3] = 1.f;
point_and_orientation.pos_and_rot[1][3] = 2.f;
point_and_orientation.pos_and_rot[2][3] = 3.f;
point_and_orientation.pos_and_rot[3][3] = 1.f;
// applying extrinsics from i to j on point with orientation
position_and_rotation retransformed_temp = pr_j_to_i * point_and_orientation;
// applying extrinsics from j to i
position_and_rotation retransformed = pr_i_to_j * retransformed_temp;
// checking that the point and orientation are the same as before the transformations
REQUIRE(retransformed.equals(point_and_orientation));
}
}
}
}
<commit_msg>semantic changes<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2021 Intel Corporation. All Rights Reserved.
#include <easylogging++.h>
#ifdef BUILD_SHARED_LIBS
// With static linkage, ELPP is initialized by librealsense, so doing it here will
// create errors. When we're using the shared .so/.dll, the two are separate and we have
// to initialize ours if we want to use the APIs!
INITIALIZE_EASYLOGGINGPP
#endif
// Let Catch define its own main() function
#define CATCH_CONFIG_MAIN
#include "../../catch.h"
#include <librealsense2/rs.hpp>
#include <librealsense2/rsutil.h>
using namespace rs2;
// structure of a matrix 4 X 4, representing rotation and translation as following:
// pos_and_rot[i][j] is
// _ _
// | | |
// | rotation | translation |
// | (3x3) | (3x1) |
// | _________ |____________ |
// | 0 | 1 |
// |_ (1x3) | (1x1) _|
//
struct position_and_rotation {
double pos_and_rot[4][4];
// rotation tolerance - units are in cosinus of radians
const double rotation_tolerance = 0.000001;
// translation tolerance - units are in meters
const double translation_tolerance = 0.000001; // 0.001mm
position_and_rotation operator* (const position_and_rotation& other)
{
position_and_rotation product;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
product.pos_and_rot[i][j] = 0;
for (int k = 0; k < 4; k++)
product.pos_and_rot[i][j] += pos_and_rot[i][k] * other.pos_and_rot[k][j];
}
}
return product;
}
bool equals(const position_and_rotation& other)
{
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
{
double tolerance = rotation_tolerance;
if (j == 3) tolerance = translation_tolerance;
if (fabs(pos_and_rot[i][j] - other.pos_and_rot[i][j]) > tolerance)
{
std::cout << "i,j = " << i << "," << j << ", pos_and_rot[i][j] = " << pos_and_rot[i][j] << ", tolerance = " << tolerance << std::endl;
return false;
}
}
return true;
}
bool is_identity()
{
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
{
double target = 0.0;
if (i == j) target = 1.0;
double tolerance = rotation_tolerance;
if (j == 3) tolerance = translation_tolerance;
if (fabs(pos_and_rot[i][j] - target) > tolerance)
{
std::cout << "i,j = " << i << "," << j << ", pos_and_rot[i][j] = " << pos_and_rot[i][j] << ", target = " << target << ", tolerance = " << tolerance << std::endl;
return false;
}
}
return true;
}
};
// This method takes in consideration that the totation array is given in the order of a column major 3x3 matrix
position_and_rotation matrix_4_by_4_from_translation_and_rotation(const float* position, const float* rotation)
{
position_and_rotation pos_rot;
pos_rot.pos_and_rot[0][0] = static_cast<double>(rotation[0]);
pos_rot.pos_and_rot[1][0] = static_cast<double>(rotation[1]);
pos_rot.pos_and_rot[2][0] = static_cast<double>(rotation[2]);
pos_rot.pos_and_rot[0][1] = static_cast<double>(rotation[3]);
pos_rot.pos_and_rot[1][1] = static_cast<double>(rotation[4]);
pos_rot.pos_and_rot[2][1] = static_cast<double>(rotation[5]);
pos_rot.pos_and_rot[0][2] = static_cast<double>(rotation[6]);
pos_rot.pos_and_rot[1][2] = static_cast<double>(rotation[7]);
pos_rot.pos_and_rot[2][2] = static_cast<double>(rotation[8]);
pos_rot.pos_and_rot[3][0] = 0.0;
pos_rot.pos_and_rot[3][1] = 0.0;
pos_rot.pos_and_rot[3][2] = 0.0;
pos_rot.pos_and_rot[0][3] = static_cast<double>(position[0]);
pos_rot.pos_and_rot[1][3] = static_cast<double>(position[1]);
pos_rot.pos_and_rot[2][3] = static_cast<double>(position[2]);
pos_rot.pos_and_rot[3][3] = 1.0;
return pos_rot;
}
// checking the extrinsics graph
// steps are:
// 1. get all the profiles
// 2. for each pair of these profiles:
// check that:
// point P(x,y,z,head,pitch,roll) in profile A transformed to profile B coordinates, and then transformed back to profile A coordinates == same point P
TEST_CASE("Extrinsics graph - matrices 4x4", "[live]")
{
rs2::context ctx;
auto list = ctx.query_devices();
for (auto&& device : list)
{
std::cout << "device: " << device.get_info(RS2_CAMERA_INFO_NAME) << std::endl;
auto sensors = device.query_sensors();
// getting stream profiles from all sensors
std::vector<rs2::stream_profile> profiles;
for (auto&& sensor : sensors)
{
std::vector<rs2::stream_profile> stream_profiles = sensor.get_stream_profiles();
for (auto&& profile : stream_profiles)
{
profiles.push_back(profile);
}
}
float start_point[3] = { 1.f, 2.f, 3.f };
for (int i = 0; i < profiles.size() - 2; ++i)
{
for (int j = i + 1; j < profiles.size() - 1; ++j)
{
rs2_extrinsics extr_i_to_j = profiles[i].get_extrinsics_to(profiles[j]);
rs2_extrinsics extr_j_to_i = profiles[j].get_extrinsics_to(profiles[i]);
position_and_rotation pr_i_to_j = matrix_4_by_4_from_translation_and_rotation(extr_i_to_j.translation, extr_i_to_j.rotation);
position_and_rotation pr_j_to_i = matrix_4_by_4_from_translation_and_rotation(extr_j_to_i.translation, extr_j_to_i.rotation);
position_and_rotation product = pr_i_to_j * pr_j_to_i;
// checking that product of extrinsics from i to j with extrinsiscs from j to i is identity matrix
REQUIRE(product.is_identity());
// checking with API rs2_transform_point_to_point
float transformed_point[3];
rs2_transform_point_to_point(transformed_point, &extr_i_to_j, start_point);
float end_point[3];
rs2_transform_point_to_point(end_point, &extr_j_to_i, transformed_point);
bool res = true;
for (int t = 0; t < 3; ++t)
{
if (fabs(start_point[t] - end_point[t]) > 0.001f)
res = false;
}
// checking that transforming a point with extrinsiscs from i to j and the from j to i
// gets back to the initial point
REQUIRE(res);
// checking that a point and orientation, represented by a 4x4 matrix
// is equal to the result of transforming it by the extrinsics
// from profile A to B, and then from profile B to A
position_and_rotation point_and_orientation;
// rotation part with 30 degrees rotation on each axis
point_and_orientation.pos_and_rot[0][0] = 0.75f;
point_and_orientation.pos_and_rot[0][1] = -0.4330127f;
point_and_orientation.pos_and_rot[0][2] = 0.5f;
point_and_orientation.pos_and_rot[1][0] = 0.649519f;
point_and_orientation.pos_and_rot[1][1] = 0.625f;
point_and_orientation.pos_and_rot[1][2] = -0.4330127f;
point_and_orientation.pos_and_rot[2][0] = -0.125f;
point_and_orientation.pos_and_rot[2][1] = 0.649519f;
point_and_orientation.pos_and_rot[2][2] = 0.75f;
point_and_orientation.pos_and_rot[3][0] = 0.f;
point_and_orientation.pos_and_rot[3][1] = 0.f;
point_and_orientation.pos_and_rot[3][2] = 0.f;
// translation part
point_and_orientation.pos_and_rot[0][3] = 1.f;
point_and_orientation.pos_and_rot[1][3] = 2.f;
point_and_orientation.pos_and_rot[2][3] = 3.f;
point_and_orientation.pos_and_rot[3][3] = 1.f;
// applying extrinsics from i to j on point with orientation
position_and_rotation retransformed_temp = pr_j_to_i * point_and_orientation;
// applying extrinsics from j to i
position_and_rotation retransformed = pr_i_to_j * retransformed_temp;
// checking that the point and orientation are the same as before the transformations
REQUIRE(retransformed.equals(point_and_orientation));
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017 Pierre Fourgeaud
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <bandit/bandit.h>
#include "core/utils.h"
using namespace bandit;
using namespace snowhouse;
using namespace CodeHero;
go_bandit([]() {
describe("::StartsWith", [] {
it("should return true if starts we correct prefix", [] {
AssertThat(StartsWith("This is a test", "This"), IsTrue());
AssertThat(StartsWith("This is a test", "This is a test"), IsTrue());
});
it("should return true if the prefix is empty", [] {
AssertThat(StartsWith("This is a test", ""), IsTrue());
});
it("should return false if the prefix doesn't match the start of the string", [] {
AssertThat(StartsWith("This is a test", "Wrong"), IsFalse());
AssertThat(StartsWith("This is a test", "This iz"), IsFalse());
AssertThat(StartsWith("This is a test", "Zhis is"), IsFalse());
});
});
describe("::EndsWith", [] {
it("should return true if ends with correct suffix", [] {
AssertThat(EndsWith("This is a test", "test"), IsTrue());
AssertThat(EndsWith("This is a test", "This is a test"), IsTrue());
});
it("should return true if suffix is empty", [] {
AssertThat(EndsWith("This is a test", ""), IsTrue());
});
it("should return false if the suffix doesn't match the end of the string", [] {
AssertThat(EndsWith("This is a test", "wrong"), IsFalse());
AssertThat(EndsWith("This is a test", "tesz"), IsFalse());
AssertThat(EndsWith("This is a test", "zest"), IsFalse());
});
});
describe("::Trim", [] {
it("should trim on the left side", [] {
std::string test(" \t This is a test");
std::string result("This is a test");
Trim(test);
AssertThat(test, Equals(result));
});
it("should trim on the right side", [] {
std::string test("This is a test \t ");
std::string result("This is a test");
Trim(test);
AssertThat(test, Equals(result));
});
it("should trim on the both side", [] {
std::string test(" \t This is a test \t ");
std::string result("This is a test");
Trim(test);
AssertThat(test, Equals(result));
});
it("should not modify the string if not needed", [] {
std::string test("This is a test");
std::string result = test;
Trim(test);
AssertThat(test, Equals(result));
});
});
describe("::ToLowerCase", [] {
it("should lower case properly a string regardless of special chars", [] {
std::string test("Th1s 1S pr377Y W31RD !!@#$ ");
std::string result("th1s 1s pr377y w31rd !!@#$ ");
ToLowerCase(test);
AssertThat(test, Equals(result));
});
it("should not do anything on an empty string", [] {
std::string test;
std::string result;
ToLowerCase(test);
AssertThat(test, Equals(result));
});
});
describe("::LowerCased", [] {
it("should lower case properly a string regardless of special chars", [] {
std::string test("Th1s 1S pr377Y W31RD !!@#$ ");
std::string result("th1s 1s pr377y w31rd !!@#$ ");
test = LowerCased(test);
AssertThat(test, Equals(result));
});
it("should not do anything on an empty string", [] {
std::string test;
std::string result;
test = LowerCased(test);
AssertThat(test, Equals(result));
});
});
describe("::Join", [] {
it("should return empty string if the input vector is empty", [] {
std::string test = Join({});
std::string result;
AssertThat(test, Equals(result));
});
it("should return the proper string if delimiter wasn't passed", [] {
std::string test = Join({"This", "is", "a", "test."});
std::string result = "This is a test.";
AssertThat(test, Equals(result));
});
it("should properly join the vector into a string with correct delimiter", [] {
std::string test = Join({"This", "is", "a", "test."}, ' ');
std::string result = "This is a test.";
AssertThat(test, Equals(result));
});
});
describe("::IsIn", [] {
it("should return true if the searched term is inside the array", [] {
AssertThat(IsIn("test", {"test", "is", "in"}), IsTrue());
});
it("should return false if the searched term is not in the array", [] {
AssertThat(IsIn("test", {"is", "not", "in"}), IsFalse());
});
it("should return false if the array is empty", [] {
AssertThat(IsIn("test", {}), IsFalse());
});
});
});<commit_msg>Fixed small type deduction issues in previous change<commit_after>// Copyright (c) 2017 Pierre Fourgeaud
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <bandit/bandit.h>
#include "core/utils.h"
using namespace bandit;
using namespace snowhouse;
using namespace CodeHero;
go_bandit([]() {
describe("::StartsWith", [] {
it("should return true if starts we correct prefix", [] {
AssertThat(StartsWith("This is a test", "This"), IsTrue());
AssertThat(StartsWith("This is a test", "This is a test"), IsTrue());
});
it("should return true if the prefix is empty", [] {
AssertThat(StartsWith("This is a test", ""), IsTrue());
});
it("should return false if the prefix doesn't match the start of the string", [] {
AssertThat(StartsWith("This is a test", "Wrong"), IsFalse());
AssertThat(StartsWith("This is a test", "This iz"), IsFalse());
AssertThat(StartsWith("This is a test", "Zhis is"), IsFalse());
});
});
describe("::EndsWith", [] {
it("should return true if ends with correct suffix", [] {
AssertThat(EndsWith("This is a test", "test"), IsTrue());
AssertThat(EndsWith("This is a test", "This is a test"), IsTrue());
});
it("should return true if suffix is empty", [] {
AssertThat(EndsWith("This is a test", ""), IsTrue());
});
it("should return false if the suffix doesn't match the end of the string", [] {
AssertThat(EndsWith("This is a test", "wrong"), IsFalse());
AssertThat(EndsWith("This is a test", "tesz"), IsFalse());
AssertThat(EndsWith("This is a test", "zest"), IsFalse());
});
});
describe("::Trim", [] {
it("should trim on the left side", [] {
std::string test(" \t This is a test");
std::string result("This is a test");
Trim(test);
AssertThat(test, Equals(result));
});
it("should trim on the right side", [] {
std::string test("This is a test \t ");
std::string result("This is a test");
Trim(test);
AssertThat(test, Equals(result));
});
it("should trim on the both side", [] {
std::string test(" \t This is a test \t ");
std::string result("This is a test");
Trim(test);
AssertThat(test, Equals(result));
});
it("should not modify the string if not needed", [] {
std::string test("This is a test");
std::string result = test;
Trim(test);
AssertThat(test, Equals(result));
});
});
describe("::ToLowerCase", [] {
it("should lower case properly a string regardless of special chars", [] {
std::string test("Th1s 1S pr377Y W31RD !!@#$ ");
std::string result("th1s 1s pr377y w31rd !!@#$ ");
ToLowerCase(test);
AssertThat(test, Equals(result));
});
it("should not do anything on an empty string", [] {
std::string test;
std::string result;
ToLowerCase(test);
AssertThat(test, Equals(result));
});
});
describe("::LowerCased", [] {
it("should lower case properly a string regardless of special chars", [] {
std::string test("Th1s 1S pr377Y W31RD !!@#$ ");
std::string result("th1s 1s pr377y w31rd !!@#$ ");
test = LowerCased(test);
AssertThat(test, Equals(result));
});
it("should not do anything on an empty string", [] {
std::string test;
std::string result;
test = LowerCased(test);
AssertThat(test, Equals(result));
});
});
describe("::Join", [] {
it("should return empty string if the input vector is empty", [] {
std::string test = Join({});
std::string result;
AssertThat(test, Equals(result));
});
it("should return the proper string if delimiter wasn't passed", [] {
std::string test = Join({"This", "is", "a", "test."});
std::string result = "This is a test.";
AssertThat(test, Equals(result));
});
it("should properly join the vector into a string with correct delimiter", [] {
std::string test = Join({"This", "is", "a", "test."}, ' ');
std::string result = "This is a test.";
AssertThat(test, Equals(result));
});
});
describe("::IsIn", [] {
it("should return true if the searched term is inside the array", [] {
std::string toFind = "test";
std::vector<std::string> list = {"test", "is", "in"};
AssertThat(IsIn(toFind, list), IsTrue());
});
it("should return false if the searched term is not in the array", [] {
std::string toFind = "test";
std::vector<std::string> list = {"is", "not", "in"};
AssertThat(IsIn(toFind, list), IsFalse());
});
it("should return false if the array is empty", [] {
std::string toFind = "test";
std::vector<std::string> list = {};
AssertThat(IsIn(toFind, list), IsFalse());
});
});
});<|endoftext|> |
<commit_before>//
// ex10_30.cpp
// Exercise 10.30
//
// Created by pezy on 12/13/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// Use stream iterators, sort, and copy to read a sequence of integers from the
// standard input,
// sort them, and then write them back to the standard output.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::istream_iterator<int> in_iter(std::cin), eof;
std::vector<int> vec;
while (in_iter != eof) vec.push_back(*in_iter++);
std::sort(vec.begin(), vec.end());
std::copy(vec.cbegin(), vec.cend(),
std::ostream_iterator<int>(std::cout, " "));
}<commit_msg>Update ex10_30.cpp<commit_after>//
// ex10_30.cpp
// Exercise 10.30
//
// Created by pezy on 12/13/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// Use stream iterators, sort, and copy to read a sequence of integers from the
// standard input, sort them, and then write them back to the standard output.
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
istream_iterator<int> in_iter(cin), eof;
vector<int> ivec;
copy(in_iter, eof, back_inserter(ivec));
sort(ivec.begin(), ivec.end());
copy(ivec.cbegin(), ivec.cend(), ostream_iterator<int>(cout, " "));
}
<|endoftext|> |
<commit_before>//
// ex10_32.cpp
// Exercise 10.32
//
// Created by pezy on 12/13/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// Rewrite the bookstore problem from 1.6 (p. 24) using a vector to hold the
// transactions
// and various algorithms to do the processing.
// Use sort with your compareIsbn function from 10.3.1 (p. 387) to arrange the
// transactions in order,
// and then use find and accumulate to do the sum.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <numeric>
#include "../include/Sales_item.h"
int main()
{
std::istream_iterator<Sales_item> in_iter(std::cin), in_eof;
std::vector<Sales_item> vec;
while (in_iter != in_eof) vec.push_back(*in_iter++);
sort(vec.begin(), vec.end(),
[](Sales_item const& lhs, Sales_item const& rhs) {
return lhs.isbn() < rhs.isbn();
});
for (auto beg = vec.cbegin(), end = beg; beg != vec.cend(); beg = end) {
end = find_if(beg, vec.cend(), [beg](const Sales_item& item) {
return item.isbn() != beg->isbn();
});
std::cout << std::accumulate(beg, end, Sales_item(beg->isbn()))
<< std::endl;
}
}
<commit_msg>Update ex10_32.cpp<commit_after>//
// ex10_32.cpp
// Exercise 10.32
//
// Created by pezy on 12/13/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// Rewrite the bookstore program from 1.6 (p. 24) using a vector to hold the
// transactions and various algorithms to do the processing.
// Use sort with your compareIsbn function from 10.3.1 (p. 387) to arrange the
// transactions in order, and then use find and accumulate to do the sum.
//
#include <iostream>
#include <vector>
#include <iterator>
#include <numeric>
#include <algorithm>
#include "Sales_item.h"
#include "Version_test.h"
using namespace std;
int main()
{
istream_iterator<Sales_item> in_iter(cin), in_eof;
vector<Sales_item> vec;
while(in_iter!=in_eof)
vec.push_back(*in_iter++);
sort(vec.begin(), vec.end(), [](const Sales_item &lhs, const Sales_item &rhs) {return lhs.isbn()<rhs.isbn();});
for(auto beg=vec.cbegin(), end=beg; beg!=vec.cend(); beg=end)
{
end=find_if(beg, vec.cend(), [beg](const Sales_item &item) {return item.isbn()!=beg->isbn();});
cout<<accumulate(beg, end, Sales_item(beg->isbn()))<<endl;
}
}
<|endoftext|> |
<commit_before>// Copyright Hugh Perkins 2015 hughperkins at gmail
//
// 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/.
#include <iostream>
#include <string>
#include "net/NeuralNet.h"
#include "layer/LayerMakers.h"
#include "util/stringhelper.h"
#include "netdef/NetdefToNet.h"
#include "activate/ActivationFunction.h"
#include "weights/WeightsInitializer.h"
using namespace std;
#undef STATIC
#undef VIRTUAL
#define STATIC
#define VIRTUAL
// string is structured like:
// prefix-nn*(inner)-postfix
// or:
// prefix-nn*inner-postfix
STATIC std::string expandMultipliers(std::string netdef) {
int starPos = netdef.find("*");
if(starPos != (int)string::npos) {
int prefixEnd = netdef.rfind("-", starPos);
string prefix = "";
string nnString = "";
if(prefixEnd == (int)string::npos) {
prefixEnd = -1;
nnString = netdef.substr(0, starPos);
} else {
prefixEnd--;
prefix = netdef.substr(0, prefixEnd + 1);
cout << "prefix: [" << prefix << "]" << endl;
nnString = netdef.substr(prefixEnd + 2, starPos - prefixEnd - 2);
}
cout << "nnString: [" << nnString << "]" << endl;
int repeatNum = atoi(nnString);
cout << "repeatNum " << repeatNum << endl;
string remainderString = netdef.substr(starPos + 1);
cout << "remainderString [" << remainderString << "]" << endl;
string inner = "";
string postfix = "";
if(remainderString.substr(0, 1) == "(") {
// need to find other ')', assume not nested for now...
int rhBracket = remainderString.find(")");
if(rhBracket == (int)string::npos) {
throw runtime_error("matching bracket not found in " + remainderString);
// return false;
}
inner = remainderString.substr(1, rhBracket - 1);
cout << "inner [" << inner << "]" << endl;
string newRemainder = remainderString.substr(rhBracket + 1);
cout << "newRemainder [" << newRemainder << "]" << endl;
if(newRemainder != "") {
if(newRemainder[0] != '-') {
throw runtime_error("expect '-' after ')' in " + remainderString);
// return false;
}
postfix = newRemainder.substr(1);
cout << "postfix [" << postfix << "]" << endl;
}
} else {
int innerEnd = remainderString.find("-");
if(innerEnd == (int)string::npos) {
innerEnd = remainderString.length();
} else {
// innerEnd;
postfix = remainderString.substr(innerEnd + 1);
cout << "postfix [" << postfix << "]" << endl;
}
inner = remainderString.substr(0, innerEnd);
cout << "inner [" << inner << "]" << endl;
// if(remainderString.find("-") != string::npos) {
// sectionEndPos = remainderString.find("-");
// }
}
// return "";
// if remainderString starts with (, then repeat up to next)
// otherwise, repeat up to next -
// int sectionEndPos = remainderString.length();
// remainderString =
string newString = prefix;
for(int i = 0; i < repeatNum; i++) {
if(newString != "") {
newString += "-";
}
newString += expandMultipliers(inner);
}
if(postfix != "") {
newString += "-" + expandMultipliers(postfix);
}
cout << "multiplied string: " << newString << endl;
return newString;
} else {
return netdef;
}
}
STATIC bool NetdefToNet::parseSubstring(WeightsInitializer *weightsInitializer, NeuralNet *net, std::string substring, bool isLast) {
// cout << "substring [" << substring << "]" << endl;
vector<string>splitLayerDef = split(substring, "{");
string baseLayerDef = splitLayerDef[0];
// optionsDef = "";
vector<string> splitOptionsDef;
// cout << "splitlayerdef.size() " << splitLayerDef.size() << endl;
if(splitLayerDef.size() == 2) {
string optionsDef = split(splitLayerDef[1], "}")[0];
// cout << "optionsDef [" << optionsDef << "]" << endl;
splitOptionsDef = split(optionsDef, ",");
}
if(baseLayerDef.find("c") != string::npos) {
vector<string> splitConvDef = split(baseLayerDef, "c");
int numFilters = atoi(splitConvDef[0]);
vector<string> splitConvDef1 = split(splitConvDef[1], "z");
int filterSize = atoi(splitConvDef1[0]);
int skip = 0;
ActivationFunction *fn = 0;
bool padZeros = splitConvDef1.size() == 2 ? true : false;
for(int i = 0; i < (int)splitOptionsDef.size(); i++) {
string optionDef = splitOptionsDef[i];
// cout << "optionDef [" << optionDef << "]" << endl;
vector<string> splitOptionDef = split(optionDef, "=");
string optionName = splitOptionDef[0];
if(splitOptionDef.size() == 2) {
string optionValue = splitOptionDef[1];
if(optionName == "skip") {
skip = atoi(optionValue);
cout << "got skip: " << skip << endl;
}
} else if(splitOptionDef.size() == 1) {
if(optionName == "tanh") {
fn = new TanhActivation();
} else if(optionName == "scaledtanh") {
fn = new ScaledTanhActivation();
} else if(optionName == "sigmoid") {
fn = new SigmoidActivation();
} else if(optionName == "relu") {
fn = new ReluActivation();
} else if(optionName == "elu") {
fn = new EluActivation();
} else if(optionName == "linear") {
fn = new LinearActivation();
} else if(optionName == "padzeros" || optionName == "z") {
padZeros = true;
} else {
cout << "Error: unknown subkey: [" << splitOptionsDef[i] << "]" << endl;
return false;
}
} else {
cout << "Error: unknown subkey: [" << splitOptionsDef[i] << "]" << endl;
return false;
}
}
net->addLayer(ConvolutionalMaker::instance()->numFilters(numFilters)->filterSize(filterSize)->padZeros(padZeros)->biased()->weightsInitializer(weightsInitializer) );
if(fn != 0) {
net->addLayer(ActivationMaker::instance()->fn(fn) );
}
} else if(baseLayerDef.find("mp") != string::npos) {
vector<string> splitPoolDef = split(baseLayerDef, "mp");
int poolingSize = atoi(splitPoolDef[1]);
net->addLayer(PoolingMaker::instance()->poolingSize(poolingSize));
} else if(baseLayerDef.find("drop") != string::npos) {
net->addLayer(DropoutMaker::instance()->dropRatio(0.5f));
} else if(baseLayerDef.find("relu") != string::npos) {
net->addLayer(ActivationMaker::instance()->relu());
} else if(baseLayerDef.find("elu") != string::npos) {
net->addLayer(ActivationMaker::instance()->elu());
} else if(baseLayerDef.find("tanh") != string::npos) {
net->addLayer(ActivationMaker::instance()->tanh());
} else if(baseLayerDef.find("sigmoid") != string::npos) {
net->addLayer(ActivationMaker::instance()->sigmoid());
} else if(baseLayerDef.find("linear") != string::npos) {
net->addLayer(ActivationMaker::instance()->linear()); // kind of pointless nop, but useful for testing
} else if(baseLayerDef.find("rp") != string::npos) {
int patchSize = atoi(split(baseLayerDef, "rp")[1]);
net->addLayer(RandomPatchesMaker::instance()->patchSize(patchSize) );
} else if(baseLayerDef.find("rt") != string::npos) {
int translateSize = atoi(split(baseLayerDef, "rt")[1]);
net->addLayer(RandomTranslationsMaker::instance()->translateSize(translateSize) );
} else if(baseLayerDef.find("n") != string::npos) {
vector<string> fullDef = split(baseLayerDef, "n");
int numPlanes = atoi(fullDef[0]);
ActivationFunction *fn = 0;
// if(isLast) {
// fn = new LinearActivation();
// }
// int padZeros = 0;
bool biased = true;
for(int i = 0; i < (int)splitOptionsDef.size(); i++) {
string optionDef = splitOptionsDef[i];
// cout << "optionDef: " << optionDef << endl;
vector<string> splitOptionDef = split(optionDef, "=");
string optionName = splitOptionDef[0];
if(splitOptionDef.size() == 1) {
if(optionName == "tanh") {
fn = new TanhActivation();
} else if(optionName == "scaledtanh") {
fn = new ScaledTanhActivation();
} else if(optionName == "sigmoid") {
fn = new SigmoidActivation();
} else if(optionName == "relu") {
fn = new ReluActivation();
} else if(optionName == "nobias") {
biased = false;
} else if(optionName == "linear") {
fn = new LinearActivation();
} else {
cout << "Error: unknown subkey: [" << splitOptionsDef[i] << "]" << endl;
return false;
}
} else {
cout << "Error: unknown subkey: [" << splitOptionsDef[i] << "]" << endl;
return false;
}
}
if(isLast && fn != 0) {
cout << "Last fullyconnectedlayer must be linear (because softmax is the 'activationlayer' for this layer)" << endl;
return false;
}
net->addLayer(FullyConnectedMaker::instance()->numPlanes(numPlanes)->imageSize(1)->biased(biased)->weightsInitializer(weightsInitializer) );
if(fn != 0) {
net->addLayer(ActivationMaker::instance()->fn(fn) );
}
} else {
cout << "network definition " << baseLayerDef << " not recognised" << endl;
return false;
}
return true;
}
PUBLICAPI STATIC bool NetdefToNet::createNetFromNetdef(NeuralNet *net, std::string netdef) {
OriginalInitializer originalInitializer;
return createNetFromNetdef(net, netdef, &originalInitializer);
}
PUBLICAPI STATIC bool NetdefToNet::createNetFromNetdefCharStar(NeuralNet *net, const char *netdef) {
OriginalInitializer originalInitializer;
return createNetFromNetdef(net, netdef, &originalInitializer);
}
STATIC bool NetdefToNet::createNetFromNetdef(NeuralNet *net, std::string netdef, WeightsInitializer *weightsInitializer) {
string netDefLower = toLower(netdef);
// cout << "netDefLower [" << netDefLower << "]" << endl;
try {
netDefLower = expandMultipliers(netDefLower);
} catch(runtime_error &e) {
cout << e.what() << endl;
return false;
}
// cout << "netDefLower [" << netDefLower << "]" << endl;
vector<string> splitNetDef = split(netDefLower, "-");
if(netdef != "") {
for(int i = 0; i < (int)splitNetDef.size(); i++) {
string thisLayerDef = splitNetDef[i];
// cout << "thisLayerDef [" << thisLayerDef << "]" << endl;
if(!parseSubstring(weightsInitializer, net, thisLayerDef, i == (int)splitNetDef.size() - 1) ) {
return false;
}
}
}
net->addLayer(SoftMaxMaker::instance());
return true;
}<commit_msg>Removed 5 warnings<commit_after>// Copyright Hugh Perkins 2015 hughperkins at gmail
//
// 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/.
#include <iostream>
#include <string>
#include "net/NeuralNet.h"
#include "layer/LayerMakers.h"
#include "util/stringhelper.h"
#include "netdef/NetdefToNet.h"
#include "activate/ActivationFunction.h"
#include "weights/WeightsInitializer.h"
using namespace std;
#undef STATIC
#undef VIRTUAL
#define STATIC
#define VIRTUAL
// string is structured like:
// prefix-nn*(inner)-postfix
// or:
// prefix-nn*inner-postfix
STATIC std::string expandMultipliers(std::string netdef) {
size_t starPos = netdef.find("*");
if(starPos != string::npos) {
size_t prefixEnd = netdef.rfind("-", starPos);
string prefix = "";
string nnString = "";
if(prefixEnd == string::npos) {
prefixEnd = -1;
nnString = netdef.substr(0, starPos);
} else {
prefixEnd--;
prefix = netdef.substr(0, prefixEnd + 1);
cout << "prefix: [" << prefix << "]" << endl;
nnString = netdef.substr(prefixEnd + 2, starPos - prefixEnd - 2);
}
cout << "nnString: [" << nnString << "]" << endl;
int repeatNum = atoi(nnString);
cout << "repeatNum " << repeatNum << endl;
string remainderString = netdef.substr(starPos + 1);
cout << "remainderString [" << remainderString << "]" << endl;
string inner = "";
string postfix = "";
if(remainderString.substr(0, 1) == "(") {
// need to find other ')', assume not nested for now...
size_t rhBracket = remainderString.find(")");
if(rhBracket == string::npos) {
throw runtime_error("matching bracket not found in " + remainderString);
}
inner = remainderString.substr(1, rhBracket - 1);
cout << "inner [" << inner << "]" << endl;
string newRemainder = remainderString.substr(rhBracket + 1);
cout << "newRemainder [" << newRemainder << "]" << endl;
if(newRemainder != "") {
if(newRemainder[0] != '-') {
throw runtime_error("expect '-' after ')' in " + remainderString);
}
postfix = newRemainder.substr(1);
cout << "postfix [" << postfix << "]" << endl;
}
} else {
size_t innerEnd = remainderString.find("-");
if(innerEnd == string::npos) {
innerEnd = remainderString.length();
} else {
// innerEnd;
postfix = remainderString.substr(innerEnd + 1);
cout << "postfix [" << postfix << "]" << endl;
}
inner = remainderString.substr(0, innerEnd);
cout << "inner [" << inner << "]" << endl;
// if(remainderString.find("-") != string::npos) {
// sectionEndPos = remainderString.find("-");
// }
}
// return "";
// if remainderString starts with (, then repeat up to next)
// otherwise, repeat up to next -
// int sectionEndPos = remainderString.length();
// remainderString =
string newString = prefix;
for(int i = 0; i < repeatNum; i++) {
if(newString != "") {
newString += "-";
}
newString += expandMultipliers(inner);
}
if(postfix != "") {
newString += "-" + expandMultipliers(postfix);
}
cout << "multiplied string: " << newString << endl;
return newString;
} else {
return netdef;
}
}
STATIC bool NetdefToNet::parseSubstring(WeightsInitializer *weightsInitializer, NeuralNet *net, std::string substring, bool isLast) {
// cout << "substring [" << substring << "]" << endl;
vector<string>splitLayerDef = split(substring, "{");
string baseLayerDef = splitLayerDef[0];
// optionsDef = "";
vector<string> splitOptionsDef;
// cout << "splitlayerdef.size() " << splitLayerDef.size() << endl;
if(splitLayerDef.size() == 2) {
string optionsDef = split(splitLayerDef[1], "}")[0];
// cout << "optionsDef [" << optionsDef << "]" << endl;
splitOptionsDef = split(optionsDef, ",");
}
if(baseLayerDef.find("c") != string::npos) {
vector<string> splitConvDef = split(baseLayerDef, "c");
int numFilters = atoi(splitConvDef[0]);
vector<string> splitConvDef1 = split(splitConvDef[1], "z");
int filterSize = atoi(splitConvDef1[0]);
int skip = 0;
ActivationFunction *fn = 0;
bool padZeros = splitConvDef1.size() == 2 ? true : false;
for(int i = 0; i < (int)splitOptionsDef.size(); i++) {
string optionDef = splitOptionsDef[i];
// cout << "optionDef [" << optionDef << "]" << endl;
vector<string> splitOptionDef = split(optionDef, "=");
string optionName = splitOptionDef[0];
if(splitOptionDef.size() == 2) {
string optionValue = splitOptionDef[1];
if(optionName == "skip") {
skip = atoi(optionValue);
cout << "got skip: " << skip << endl;
}
} else if(splitOptionDef.size() == 1) {
if(optionName == "tanh") {
fn = new TanhActivation();
} else if(optionName == "scaledtanh") {
fn = new ScaledTanhActivation();
} else if(optionName == "sigmoid") {
fn = new SigmoidActivation();
} else if(optionName == "relu") {
fn = new ReluActivation();
} else if(optionName == "elu") {
fn = new EluActivation();
} else if(optionName == "linear") {
fn = new LinearActivation();
} else if(optionName == "padzeros" || optionName == "z") {
padZeros = true;
} else {
cout << "Error: unknown subkey: [" << optionName << "]" << endl;
return false;
}
} else {
cout << "Error: unknown subkey: [" << optionName << "]" << endl;
return false;
}
}
net->addLayer(ConvolutionalMaker::instance()->numFilters(numFilters)->filterSize(filterSize)->padZeros(padZeros)->biased()->weightsInitializer(weightsInitializer) );
if(fn != 0) {
net->addLayer(ActivationMaker::instance()->fn(fn) );
}
} else if(baseLayerDef.find("mp") != string::npos) {
vector<string> splitPoolDef = split(baseLayerDef, "mp");
int poolingSize = atoi(splitPoolDef[1]);
net->addLayer(PoolingMaker::instance()->poolingSize(poolingSize));
} else if(baseLayerDef.find("drop") != string::npos) {
net->addLayer(DropoutMaker::instance()->dropRatio(0.5f));
} else if(baseLayerDef.find("relu") != string::npos) {
net->addLayer(ActivationMaker::instance()->relu());
} else if(baseLayerDef.find("elu") != string::npos) {
net->addLayer(ActivationMaker::instance()->elu());
} else if(baseLayerDef.find("tanh") != string::npos) {
net->addLayer(ActivationMaker::instance()->tanh());
} else if(baseLayerDef.find("sigmoid") != string::npos) {
net->addLayer(ActivationMaker::instance()->sigmoid());
} else if(baseLayerDef.find("linear") != string::npos) {
net->addLayer(ActivationMaker::instance()->linear()); // kind of pointless nop, but useful for testing
} else if(baseLayerDef.find("rp") != string::npos) {
int patchSize = atoi(split(baseLayerDef, "rp")[1]);
net->addLayer(RandomPatchesMaker::instance()->patchSize(patchSize) );
} else if(baseLayerDef.find("rt") != string::npos) {
int translateSize = atoi(split(baseLayerDef, "rt")[1]);
net->addLayer(RandomTranslationsMaker::instance()->translateSize(translateSize) );
} else if(baseLayerDef.find("n") != string::npos) {
vector<string> fullDef = split(baseLayerDef, "n");
int numPlanes = atoi(fullDef[0]);
ActivationFunction *fn = 0;
// if(isLast) {
// fn = new LinearActivation();
// }
// int padZeros = 0;
bool biased = true;
for(int i = 0; i < (int)splitOptionsDef.size(); i++) {
string optionDef = splitOptionsDef[i];
// cout << "optionDef: " << optionDef << endl;
vector<string> splitOptionDef = split(optionDef, "=");
string optionName = splitOptionDef[0];
if(splitOptionDef.size() == 1) {
if(optionName == "tanh") {
fn = new TanhActivation();
} else if(optionName == "scaledtanh") {
fn = new ScaledTanhActivation();
} else if(optionName == "sigmoid") {
fn = new SigmoidActivation();
} else if(optionName == "relu") {
fn = new ReluActivation();
} else if(optionName == "nobias") {
biased = false;
} else if(optionName == "linear") {
fn = new LinearActivation();
} else {
cout << "Error: unknown subkey: [" << splitOptionsDef[i] << "]" << endl;
return false;
}
} else {
cout << "Error: unknown subkey: [" << splitOptionsDef[i] << "]" << endl;
return false;
}
}
if(isLast && fn != 0) {
cout << "Last fullyconnectedlayer must be linear (because softmax is the 'activationlayer' for this layer)" << endl;
return false;
}
net->addLayer(FullyConnectedMaker::instance()->numPlanes(numPlanes)->imageSize(1)->biased(biased)->weightsInitializer(weightsInitializer) );
if(fn != 0) {
net->addLayer(ActivationMaker::instance()->fn(fn) );
}
} else {
cout << "network definition " << baseLayerDef << " not recognised" << endl;
return false;
}
return true;
}
PUBLICAPI STATIC bool NetdefToNet::createNetFromNetdef(NeuralNet *net, std::string netdef) {
OriginalInitializer originalInitializer;
return createNetFromNetdef(net, netdef, &originalInitializer);
}
PUBLICAPI STATIC bool NetdefToNet::createNetFromNetdefCharStar(NeuralNet *net, const char *netdef) {
OriginalInitializer originalInitializer;
return createNetFromNetdef(net, netdef, &originalInitializer);
}
STATIC bool NetdefToNet::createNetFromNetdef(NeuralNet *net, std::string netdef, WeightsInitializer *weightsInitializer) {
string netDefLower = toLower(netdef);
// cout << "netDefLower [" << netDefLower << "]" << endl;
try {
netDefLower = expandMultipliers(netDefLower);
} catch(runtime_error &e) {
cout << e.what() << endl;
return false;
}
// cout << "netDefLower [" << netDefLower << "]" << endl;
vector<string> splitNetDef = split(netDefLower, "-");
if(netdef != "") {
for(int i = 0; i < (int)splitNetDef.size(); i++) {
string thisLayerDef = splitNetDef[i];
// cout << "thisLayerDef [" << thisLayerDef << "]" << endl;
if(!parseSubstring(weightsInitializer, net, thisLayerDef, i == (int)splitNetDef.size() - 1) ) {
return false;
}
}
}
net->addLayer(SoftMaxMaker::instance());
return true;
}<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkAMRBaseReader.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 "vtkAMRBaseReader.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkDataObject.h"
#include "vtkMultiProcessController.h"
#include "vtkHierarchicalBoxDataSet.h"
#include "vtkDataArraySelection.h"
#include "vtkCallbackCommand.h"
#include "vtkIndent.h"
#include "vtkSmartPointer.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkAMRDataSetCache.h"
#include "vtkUniformGrid.h"
#include "vtkDataArray.h"
#include "vtkCellData.h"
#include "vtkPointData.h"
#include "vtkAMRUtilities.h"
#include <cassert>
vtkAMRBaseReader::vtkAMRBaseReader()
{
}
//------------------------------------------------------------------------------
vtkAMRBaseReader::~vtkAMRBaseReader()
{
this->PointDataArraySelection->RemoveObserver( this->SelectionObserver );
this->CellDataArraySelection->RemoveObserver( this->SelectionObserver );
this->SelectionObserver->Delete( );
this->CellDataArraySelection->Delete( );
this->PointDataArraySelection->Delete( );
if( this->metadata != NULL )
this->metadata->Delete();
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::FillOutputPortInformation(
int vtkNotUsed(port),vtkInformation *info )
{
info->Set( vtkDataObject::DATA_TYPE_NAME(), "vtkHierarchicalBoxDataSet" );
return 1;
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::PrintSelf( std::ostream &os, vtkIndent indent )
{
this->Superclass::PrintSelf( os, indent );
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::Initialize()
{
this->SetNumberOfInputPorts( 0 );
this->FileName = NULL;
this->MaxLevel = 0;
this->metadata = NULL;
this->Controller = vtkMultiProcessController::GetGlobalController();
this->InitialRequest = true;
this->CellDataArraySelection = vtkDataArraySelection::New();
this->PointDataArraySelection = vtkDataArraySelection::New();
this->SelectionObserver = vtkCallbackCommand::New();
this->SelectionObserver->SetCallback(
&vtkAMRBaseReader::SelectionModifiedCallback);
this->SelectionObserver->SetClientData( this );
this->CellDataArraySelection->AddObserver(
vtkCommand::ModifiedEvent,this->SelectionObserver );
this->PointDataArraySelection->AddObserver(
vtkCommand::ModifiedEvent, this->SelectionObserver );
}
//----------------------------------------------------------------------------
void vtkAMRBaseReader::SelectionModifiedCallback(
vtkObject*, unsigned long, void* clientdata, void*)
{
static_cast<vtkAMRBaseReader*>(clientdata)->Modified();
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::GetNumberOfPointArrays()
{
return( this->PointDataArraySelection->GetNumberOfArrays() );
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::GetNumberOfCellArrays()
{
return( this->CellDataArraySelection->GetNumberOfArrays() );
}
//------------------------------------------------------------------------------
const char* vtkAMRBaseReader::GetPointArrayName(int index)
{
return( this->PointDataArraySelection->GetArrayName( index ) );
}
//------------------------------------------------------------------------------
const char* vtkAMRBaseReader::GetCellArrayName(int index)
{
return( this->CellDataArraySelection->GetArrayName( index ) );
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::GetPointArrayStatus(const char* name)
{
return( this->PointDataArraySelection->ArrayIsEnabled( name ) );
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::GetCellArrayStatus(const char* name)
{
return( this->CellDataArraySelection->ArrayIsEnabled( name ) );
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::SetPointArrayStatus(const char* name, int status)
{
if( status )
{
this->PointDataArraySelection->EnableArray(name);
}
else
{
this->PointDataArraySelection->DisableArray(name);
}
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::SetCellArrayStatus(const char* name, int status)
{
if( status )
{
this->CellDataArraySelection->EnableArray( name );
}
else
{
this->CellDataArraySelection->DisableArray( name );
}
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::GetBlockProcessId( const int blockIdx )
{
// If this is reader instance is serial, return Process 0
// as the Process ID for the corresponding block.
if( !this->IsParallel() )
return 0;
int N = this->Controller->GetNumberOfProcesses();
return( blockIdx%N );
}
//------------------------------------------------------------------------------
bool vtkAMRBaseReader::IsBlockMine( const int blockIdx )
{
// If this reader instance does not run in parallel, then,
// all blocks are owned by this reader.
if( !this->IsParallel() )
return true;
int myRank = this->Controller->GetLocalProcessId();
if( myRank == this->GetBlockProcessId( blockIdx ) )
return true;
return false;
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::InitializeArraySelections()
{
if( this->InitialRequest )
{
this->PointDataArraySelection->DisableAllArrays();
this->CellDataArraySelection->DisableAllArrays();
this->InitialRequest=false;
}
}
//------------------------------------------------------------------------------
bool vtkAMRBaseReader::IsParallel( )
{
if( this->Controller == NULL )
return false;
if( this->Controller->GetNumberOfProcesses() > 1 )
return true;
return false;
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::RequestInformation(
vtkInformation *rqst,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector )
{
this->Superclass::RequestInformation( rqst, inputVector, outputVector );
if( this->metadata == NULL )
{
this->metadata = vtkHierarchicalBoxDataSet::New();
vtkInformation* info = outputVector->GetInformationObject(0);
assert( "pre: output information object is NULL" && (info != NULL) );
this->FillMetaData( );
info->Set( vtkCompositeDataPipeline::COMPOSITE_DATA_META_DATA(),
this->metadata );
}
this->Modified();
return 1;
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::SetupBlockRequest( vtkInformation *outInf )
{
assert( "pre: output information is NULL" && (outInf != NULL) );
if( outInf->Has(
vtkCompositeDataPipeline::UPDATE_COMPOSITE_INDICES() ) )
{
assert( "Metadata should not be null" && (this->metadata!=NULL) );
this->ReadMetaData();
int size =
outInf->Length(vtkCompositeDataPipeline::UPDATE_COMPOSITE_INDICES() );
int *indices =
outInf->Get(vtkCompositeDataPipeline::UPDATE_COMPOSITE_INDICES() );
this->BlockMap.clear();
this->BlockMap.resize( size );
for( int i=0; i < size; ++i )
{
this->BlockMap[ i ] = indices[ i ];
}
}
else
{
this->ReadMetaData();
this->GenerateBlockMap();
}
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::GetAMRData(
const int blockIdx, vtkUniformGrid *block, const char *fieldName )
{
assert( "pre: AMR block is NULL" && (block != NULL) );
assert( "pre: field name is NULL" && (fieldName != NULL) );
// If caching is disabled load the data from file
if( !this->IsCachingEnabled() )
{
this->GetAMRGridData( blockIdx, block, fieldName );
return;
}
// Caching is enabled.
// Check the cache to see if the data has already been read.
// Otherwise, read it and cache it.
if( this->amrCache->HasAMRBlockCellData( blockIdx, fieldName ) )
{
vtkDataArray *data =
this->amrCache->GetAMRBlockCellData( blockIdx, fieldName );
assert( "pre: cached data is NULL!" && (data != NULL) );
block->GetCellData()->AddArray( data );
}
else
{
this->GetAMRGridData( blockIdx, block, fieldName );
std::cout << "Inserting data to cache....\n";
std::cout.flush();
this->amrCache->InsertAMRBlockCellData(
blockIdx, block->GetCellData()->GetArray( fieldName ) );
}
assert( "Code should never reach here!" && (false) );
}
//------------------------------------------------------------------------------
vtkUniformGrid* vtkAMRBaseReader::GetAMRBlock( const int blockIdx )
{
// If caching is disabled load the data from file
if( !this->IsCachingEnabled() )
{
vtkUniformGrid *gridPtr = this->GetAMRGrid( blockIdx );
assert( "pre: grid pointer is NULL" && (gridPtr != NULL) );
return( gridPtr );
}
// Caching is enabled.
// Check the cache to see if the block has already been read.
// Otherwise, read it and cache it.
if( this->amrCache->HasAMRBlock( blockIdx ) )
{
vtkUniformGrid *gridPtr = vtkUniformGrid::New();
vtkUniformGrid *cachedGrid = this->amrCache->GetAMRBlock( blockIdx );
gridPtr->CopyStructure( cachedGrid );
return( gridPtr );
}
else
{
vtkUniformGrid *cachedGrid = vtkUniformGrid::New();
vtkUniformGrid *gridPtr = this->GetAMRGrid( blockIdx );
assert( "pre: grid pointer is NULL" && (gridPtr != NULL) );
cachedGrid->CopyStructure( gridPtr );
std::cout << "Inserting block to cache...";
std::cout.flush();
this->amrCache->InsertAMRBlock( blockIdx, cachedGrid );
return( gridPtr );
}
assert( "Code should never reach here!" && (false) );
return NULL;
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::RequestData(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** vtkNotUsed(inputVector),
vtkInformationVector* outputVector )
{
vtkInformation *outInf = outputVector->GetInformationObject( 0 );
vtkHierarchicalBoxDataSet *output =
vtkHierarchicalBoxDataSet::SafeDownCast(
outInf->Get( vtkDataObject::DATA_OBJECT() ) );
assert( "pre: output AMR dataset is NULL" && ( output != NULL ) );
// Setup the block request
this->SetupBlockRequest( outInf );
// Initialize counter of the number of blocks at each level.
// This counter is used to compute the block index w.r.t. the
// hierarchical box data-structure. Note that then number of blocks
// can change based on user constraints, e.g., the number of levels
// visible.
vtkstd::vector< int > idxcounter;
idxcounter.resize(this->GetNumberOfLevels()+1, 0);
// Find the number of blocks to be processed. BlockMap.size()
// has all the blocks that are to be processesed and may be
// less than or equal to this->GetNumberOfBlocks(), i.e., the
// total number of blocks.
int numBlocks = static_cast< int >( this->BlockMap.size() );
for( int block=0; block < numBlocks; ++block )
{
int blockIdx = this->BlockMap[ block ];
int level = this->GetBlockLevel( blockIdx );
if( this->IsBlockMine(block) )
{
// STEP 0: Get the AMR block
vtkUniformGrid *amrBlock = this->GetAMRBlock( blockIdx );
assert( "pre: AMR block is NULL" && (amrBlock != NULL) );
// STEP 2: Load any point-data
for( int i=0; i < this->GetNumberOfPointArrays(); ++i )
{
if( this->GetPointArrayStatus( this->GetPointArrayName(i) ) )
{
// TODO: load point data
}
}
// STEP 3: Load any cell-data
for( int i=0; i < this->GetNumberOfCellArrays(); ++i )
{
if( this->GetCellArrayStatus( this->GetCellArrayName( i ) ) )
{
this->GetAMRData(
blockIdx,amrBlock,this->GetCellArrayName( i ) );
}
}
output->SetDataSet( level,idxcounter[level],amrBlock );
idxcounter[level]++;
} // END if the block belongs to this process
else
{
output->SetDataSet( idxcounter[level],level,NULL );
idxcounter[level]++;
}
} // END for all blocks
// Generate all the AMR metadata & the visibility arrays
vtkAMRUtilities::GenerateMetaData( output, this->Controller );
output->GenerateVisibilityArrays();
// If this instance of the reader is not parallel, block until all processes
// read their blocks.
if( this->IsParallel() )
this->Controller->Barrier();
outInf = NULL;
output = NULL;
this->Modified();
return 1;
}
<commit_msg>BUGFIX: Allocate AMR cache in vtkAMRBaseReader<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkAMRBaseReader.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 "vtkAMRBaseReader.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkDataObject.h"
#include "vtkMultiProcessController.h"
#include "vtkHierarchicalBoxDataSet.h"
#include "vtkDataArraySelection.h"
#include "vtkCallbackCommand.h"
#include "vtkIndent.h"
#include "vtkSmartPointer.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkAMRDataSetCache.h"
#include "vtkUniformGrid.h"
#include "vtkDataArray.h"
#include "vtkCellData.h"
#include "vtkPointData.h"
#include "vtkAMRUtilities.h"
#include <cassert>
vtkAMRBaseReader::vtkAMRBaseReader()
{
}
//------------------------------------------------------------------------------
vtkAMRBaseReader::~vtkAMRBaseReader()
{
this->PointDataArraySelection->RemoveObserver( this->SelectionObserver );
this->CellDataArraySelection->RemoveObserver( this->SelectionObserver );
this->SelectionObserver->Delete( );
this->CellDataArraySelection->Delete( );
this->PointDataArraySelection->Delete( );
if( this->metadata != NULL )
this->metadata->Delete();
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::FillOutputPortInformation(
int vtkNotUsed(port),vtkInformation *info )
{
info->Set( vtkDataObject::DATA_TYPE_NAME(), "vtkHierarchicalBoxDataSet" );
return 1;
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::PrintSelf( std::ostream &os, vtkIndent indent )
{
this->Superclass::PrintSelf( os, indent );
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::Initialize()
{
this->SetNumberOfInputPorts( 0 );
this->FileName = NULL;
this->MaxLevel = 0;
this->metadata = NULL;
this->Controller = vtkMultiProcessController::GetGlobalController();
this->InitialRequest = true;
this->amrCache = vtkAMRDataSetCache::New();
this->CellDataArraySelection = vtkDataArraySelection::New();
this->PointDataArraySelection = vtkDataArraySelection::New();
this->SelectionObserver = vtkCallbackCommand::New();
this->SelectionObserver->SetCallback(
&vtkAMRBaseReader::SelectionModifiedCallback);
this->SelectionObserver->SetClientData( this );
this->CellDataArraySelection->AddObserver(
vtkCommand::ModifiedEvent,this->SelectionObserver );
this->PointDataArraySelection->AddObserver(
vtkCommand::ModifiedEvent, this->SelectionObserver );
}
//----------------------------------------------------------------------------
void vtkAMRBaseReader::SelectionModifiedCallback(
vtkObject*, unsigned long, void* clientdata, void*)
{
static_cast<vtkAMRBaseReader*>(clientdata)->Modified();
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::GetNumberOfPointArrays()
{
return( this->PointDataArraySelection->GetNumberOfArrays() );
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::GetNumberOfCellArrays()
{
return( this->CellDataArraySelection->GetNumberOfArrays() );
}
//------------------------------------------------------------------------------
const char* vtkAMRBaseReader::GetPointArrayName(int index)
{
return( this->PointDataArraySelection->GetArrayName( index ) );
}
//------------------------------------------------------------------------------
const char* vtkAMRBaseReader::GetCellArrayName(int index)
{
return( this->CellDataArraySelection->GetArrayName( index ) );
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::GetPointArrayStatus(const char* name)
{
return( this->PointDataArraySelection->ArrayIsEnabled( name ) );
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::GetCellArrayStatus(const char* name)
{
return( this->CellDataArraySelection->ArrayIsEnabled( name ) );
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::SetPointArrayStatus(const char* name, int status)
{
if( status )
{
this->PointDataArraySelection->EnableArray(name);
}
else
{
this->PointDataArraySelection->DisableArray(name);
}
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::SetCellArrayStatus(const char* name, int status)
{
if( status )
{
this->CellDataArraySelection->EnableArray( name );
}
else
{
this->CellDataArraySelection->DisableArray( name );
}
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::GetBlockProcessId( const int blockIdx )
{
// If this is reader instance is serial, return Process 0
// as the Process ID for the corresponding block.
if( !this->IsParallel() )
return 0;
int N = this->Controller->GetNumberOfProcesses();
return( blockIdx%N );
}
//------------------------------------------------------------------------------
bool vtkAMRBaseReader::IsBlockMine( const int blockIdx )
{
// If this reader instance does not run in parallel, then,
// all blocks are owned by this reader.
if( !this->IsParallel() )
return true;
int myRank = this->Controller->GetLocalProcessId();
if( myRank == this->GetBlockProcessId( blockIdx ) )
return true;
return false;
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::InitializeArraySelections()
{
if( this->InitialRequest )
{
this->PointDataArraySelection->DisableAllArrays();
this->CellDataArraySelection->DisableAllArrays();
this->InitialRequest=false;
}
}
//------------------------------------------------------------------------------
bool vtkAMRBaseReader::IsParallel( )
{
if( this->Controller == NULL )
return false;
if( this->Controller->GetNumberOfProcesses() > 1 )
return true;
return false;
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::RequestInformation(
vtkInformation *rqst,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector )
{
this->Superclass::RequestInformation( rqst, inputVector, outputVector );
if( this->metadata == NULL )
{
this->metadata = vtkHierarchicalBoxDataSet::New();
vtkInformation* info = outputVector->GetInformationObject(0);
assert( "pre: output information object is NULL" && (info != NULL) );
this->FillMetaData( );
info->Set( vtkCompositeDataPipeline::COMPOSITE_DATA_META_DATA(),
this->metadata );
}
this->Modified();
return 1;
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::SetupBlockRequest( vtkInformation *outInf )
{
assert( "pre: output information is NULL" && (outInf != NULL) );
if( outInf->Has(
vtkCompositeDataPipeline::UPDATE_COMPOSITE_INDICES() ) )
{
assert( "Metadata should not be null" && (this->metadata!=NULL) );
this->ReadMetaData();
int size =
outInf->Length(vtkCompositeDataPipeline::UPDATE_COMPOSITE_INDICES() );
int *indices =
outInf->Get(vtkCompositeDataPipeline::UPDATE_COMPOSITE_INDICES() );
this->BlockMap.clear();
this->BlockMap.resize( size );
for( int i=0; i < size; ++i )
{
this->BlockMap[ i ] = indices[ i ];
}
}
else
{
this->ReadMetaData();
this->GenerateBlockMap();
}
}
//------------------------------------------------------------------------------
void vtkAMRBaseReader::GetAMRData(
const int blockIdx, vtkUniformGrid *block, const char *fieldName )
{
assert( "pre: AMR block is NULL" && (block != NULL) );
assert( "pre: field name is NULL" && (fieldName != NULL) );
// If caching is disabled load the data from file
if( !this->IsCachingEnabled() )
{
this->GetAMRGridData( blockIdx, block, fieldName );
return;
}
// Caching is enabled.
// Check the cache to see if the data has already been read.
// Otherwise, read it and cache it.
if( this->amrCache->HasAMRBlockCellData( blockIdx, fieldName ) )
{
vtkDataArray *data =
this->amrCache->GetAMRBlockCellData( blockIdx, fieldName );
assert( "pre: cached data is NULL!" && (data != NULL) );
block->GetCellData()->AddArray( data );
}
else
{
this->GetAMRGridData( blockIdx, block, fieldName );
std::cout << "Inserting data to cache....\n";
std::cout.flush();
this->amrCache->InsertAMRBlockCellData(
blockIdx, block->GetCellData()->GetArray( fieldName ) );
}
}
//------------------------------------------------------------------------------
vtkUniformGrid* vtkAMRBaseReader::GetAMRBlock( const int blockIdx )
{
// If caching is disabled load the data from file
if( !this->IsCachingEnabled() )
{
vtkUniformGrid *gridPtr = this->GetAMRGrid( blockIdx );
assert( "pre: grid pointer is NULL" && (gridPtr != NULL) );
return( gridPtr );
}
// Caching is enabled.
// Check the cache to see if the block has already been read.
// Otherwise, read it and cache it.
if( this->amrCache->HasAMRBlock( blockIdx ) )
{
vtkUniformGrid *gridPtr = vtkUniformGrid::New();
vtkUniformGrid *cachedGrid = this->amrCache->GetAMRBlock( blockIdx );
gridPtr->CopyStructure( cachedGrid );
return( gridPtr );
}
else
{
vtkUniformGrid *cachedGrid = vtkUniformGrid::New();
vtkUniformGrid *gridPtr = this->GetAMRGrid( blockIdx );
assert( "pre: grid pointer is NULL" && (gridPtr != NULL) );
cachedGrid->CopyStructure( gridPtr );
std::cout << "Inserting block to cache...";
std::cout.flush();
this->amrCache->InsertAMRBlock( blockIdx, cachedGrid );
return( gridPtr );
}
assert( "Code should never reach here!" && (false) );
return NULL;
}
//------------------------------------------------------------------------------
int vtkAMRBaseReader::RequestData(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** vtkNotUsed(inputVector),
vtkInformationVector* outputVector )
{
vtkInformation *outInf = outputVector->GetInformationObject( 0 );
vtkHierarchicalBoxDataSet *output =
vtkHierarchicalBoxDataSet::SafeDownCast(
outInf->Get( vtkDataObject::DATA_OBJECT() ) );
assert( "pre: output AMR dataset is NULL" && ( output != NULL ) );
// Setup the block request
this->SetupBlockRequest( outInf );
// Initialize counter of the number of blocks at each level.
// This counter is used to compute the block index w.r.t. the
// hierarchical box data-structure. Note that then number of blocks
// can change based on user constraints, e.g., the number of levels
// visible.
vtkstd::vector< int > idxcounter;
idxcounter.resize(this->GetNumberOfLevels()+1, 0);
// Find the number of blocks to be processed. BlockMap.size()
// has all the blocks that are to be processesed and may be
// less than or equal to this->GetNumberOfBlocks(), i.e., the
// total number of blocks.
int numBlocks = static_cast< int >( this->BlockMap.size() );
for( int block=0; block < numBlocks; ++block )
{
int blockIdx = this->BlockMap[ block ];
int level = this->GetBlockLevel( blockIdx );
if( this->IsBlockMine(block) )
{
// STEP 0: Get the AMR block
vtkUniformGrid *amrBlock = this->GetAMRBlock( blockIdx );
assert( "pre: AMR block is NULL" && (amrBlock != NULL) );
// STEP 2: Load any point-data
for( int i=0; i < this->GetNumberOfPointArrays(); ++i )
{
if( this->GetPointArrayStatus( this->GetPointArrayName(i) ) )
{
// TODO: load point data
}
}
// STEP 3: Load any cell-data
for( int i=0; i < this->GetNumberOfCellArrays(); ++i )
{
if( this->GetCellArrayStatus( this->GetCellArrayName( i ) ) )
{
this->GetAMRData(
blockIdx,amrBlock,this->GetCellArrayName( i ) );
}
}
output->SetDataSet( level,idxcounter[level],amrBlock );
idxcounter[level]++;
} // END if the block belongs to this process
else
{
output->SetDataSet( idxcounter[level],level,NULL );
idxcounter[level]++;
}
} // END for all blocks
// Generate all the AMR metadata & the visibility arrays
vtkAMRUtilities::GenerateMetaData( output, this->Controller );
output->GenerateVisibilityArrays();
// If this instance of the reader is not parallel, block until all processes
// read their blocks.
if( this->IsParallel() )
this->Controller->Barrier();
outInf = NULL;
output = NULL;
this->Modified();
return 1;
}
<|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. *
**************************************************************************/
//-------------------------------------------------------------------------
// Implementation of the Analysis Oriented Data (AOD) event summary
// Purpose : container of event important information for soft analysis
// Author : Renaud Vernet, IPHC, Strasbourg
//-------------------------------------------------------------------------
#include "AliAODevent.h"
#include "AliESDVertex.h"
#include "AliESD.h"
#include "AliAODv0.h"
#include "AliAODxi.h"
ClassImp(AliAODevent);
AliAODevent::AliAODevent() {
fV0s = new TClonesArray("AliAODv0");
fCascades = new TClonesArray("AliAODxi");
}
AliAODevent::~AliAODevent() {
delete fV0s;
}
AliAODevent::AliAODevent(AliESD* e) {
fV0s = new TClonesArray("AliAODv0");
fCascades = new TClonesArray("AliAODxi");
fRunNumber = (UInt_t)e->GetRunNumber();
fEventNumber = (UInt_t)e->GetEventNumber();
fNumberOfTracks = (UInt_t)e->GetNumberOfTracks();
const AliESDVertex* V = e->GetVertex();
fPrimVertexX = V->GetXv();
fPrimVertexY = V->GetYv();
fPrimVertexZ = V->GetZv();
for (Int_t i=0; i<e->GetNumberOfV0s(); i++) {
AliAODv0* v=new AliAODv0(e->GetV0(i),e);
this->AddV0(v);
delete v;
}
for (Int_t i=0; i<e->GetNumberOfCascades(); i++) {
AliAODxi* c=new AliAODxi(e->GetCascade(i),e);
this->AddCascade(c);
delete c;
}
}
AliAODevent::AliAODevent(const AliAODevent& aod) :
TObject(aod),
fV0s((TClonesArray*)aod.fV0s->Clone()),
fCascades((TClonesArray*)aod.fCascades->Clone()),
fPrimVertexX(aod.fPrimVertexX),
fPrimVertexY(aod.fPrimVertexY),
fPrimVertexZ(aod.fPrimVertexZ),
fRunNumber(aod.fRunNumber),
fEventNumber(aod.fEventNumber),
fNumberOfTracks(aod.fNumberOfTracks)
{
//copy constructor
}
AliAODevent& AliAODevent::operator=(const AliAODevent& aod){
// assignment operator
if(this!=&aod) {
fPrimVertexX = aod.fPrimVertexX;
fPrimVertexY = aod.fPrimVertexY;
fPrimVertexZ = aod.fPrimVertexZ;
fRunNumber = aod.fRunNumber;
fEventNumber = aod.fEventNumber;
fNumberOfTracks = aod.fNumberOfTracks;
delete fV0s;
delete fCascades;
fV0s=(TClonesArray*)aod.fV0s->Clone();
fCascades=(TClonesArray*)aod.fCascades->Clone();
}
return *this;
}
void AliAODevent::AddV0(AliAODv0* v0) {
Int_t idx=fV0s->GetEntries();
TClonesArray& arr=*fV0s;
new(arr[idx]) AliAODv0(*v0);
}
void AliAODevent::AddCascade(AliAODxi* xi) {
Int_t idx=fCascades->GetEntries();
TClonesArray& arr=*fCascades;
new(arr[idx]) AliAODxi(*xi);
}
<commit_msg>Extra ; removed.<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. *
**************************************************************************/
//-------------------------------------------------------------------------
// Implementation of the Analysis Oriented Data (AOD) event summary
// Purpose : container of event important information for soft analysis
// Author : Renaud Vernet, IPHC, Strasbourg
//-------------------------------------------------------------------------
#include "AliAODevent.h"
#include "AliESDVertex.h"
#include "AliESD.h"
#include "AliAODv0.h"
#include "AliAODxi.h"
ClassImp(AliAODevent)
AliAODevent::AliAODevent() {
fV0s = new TClonesArray("AliAODv0");
fCascades = new TClonesArray("AliAODxi");
}
AliAODevent::~AliAODevent() {
delete fV0s;
}
AliAODevent::AliAODevent(AliESD* e) {
fV0s = new TClonesArray("AliAODv0");
fCascades = new TClonesArray("AliAODxi");
fRunNumber = (UInt_t)e->GetRunNumber();
fEventNumber = (UInt_t)e->GetEventNumber();
fNumberOfTracks = (UInt_t)e->GetNumberOfTracks();
const AliESDVertex* V = e->GetVertex();
fPrimVertexX = V->GetXv();
fPrimVertexY = V->GetYv();
fPrimVertexZ = V->GetZv();
for (Int_t i=0; i<e->GetNumberOfV0s(); i++) {
AliAODv0* v=new AliAODv0(e->GetV0(i),e);
this->AddV0(v);
delete v;
}
for (Int_t i=0; i<e->GetNumberOfCascades(); i++) {
AliAODxi* c=new AliAODxi(e->GetCascade(i),e);
this->AddCascade(c);
delete c;
}
}
AliAODevent::AliAODevent(const AliAODevent& aod) :
TObject(aod),
fV0s((TClonesArray*)aod.fV0s->Clone()),
fCascades((TClonesArray*)aod.fCascades->Clone()),
fPrimVertexX(aod.fPrimVertexX),
fPrimVertexY(aod.fPrimVertexY),
fPrimVertexZ(aod.fPrimVertexZ),
fRunNumber(aod.fRunNumber),
fEventNumber(aod.fEventNumber),
fNumberOfTracks(aod.fNumberOfTracks)
{
//copy constructor
}
AliAODevent& AliAODevent::operator=(const AliAODevent& aod){
// assignment operator
if(this!=&aod) {
fPrimVertexX = aod.fPrimVertexX;
fPrimVertexY = aod.fPrimVertexY;
fPrimVertexZ = aod.fPrimVertexZ;
fRunNumber = aod.fRunNumber;
fEventNumber = aod.fEventNumber;
fNumberOfTracks = aod.fNumberOfTracks;
delete fV0s;
delete fCascades;
fV0s=(TClonesArray*)aod.fV0s->Clone();
fCascades=(TClonesArray*)aod.fCascades->Clone();
}
return *this;
}
void AliAODevent::AddV0(AliAODv0* v0) {
Int_t idx=fV0s->GetEntries();
TClonesArray& arr=*fV0s;
new(arr[idx]) AliAODv0(*v0);
}
void AliAODevent::AddCascade(AliAODxi* xi) {
Int_t idx=fCascades->GetEntries();
TClonesArray& arr=*fCascades;
new(arr[idx]) AliAODxi(*xi);
}
<|endoftext|> |
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file ConsoleAPI.cpp
* @brief Console core API.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "ConsoleAPI.h"
#include "ConsoleWidget.h"
#include "ShellInputThread.h"
#include "Application.h"
#include "Profiler.h"
#include "Framework.h"
#include "InputAPI.h"
#include "UiAPI.h"
#include "UiGraphicsView.h"
#include "LoggingFunctions.h"
#include "FunctionInvoker.h"
#include <stdlib.h>
#include <QFile>
#include <QTextStream>
#include "MemoryLeakCheck.h"
ConsoleAPI::ConsoleAPI(Framework *fw) :
QObject(fw),
framework(fw),
enabledLogChannels(LogLevelErrorWarnInfo),
logFile(0),
logFileText(0)
{
if (!fw->IsHeadless())
consoleWidget = new ConsoleWidget(framework);
inputContext = framework->Input()->RegisterInputContext("Console", 100);
inputContext->SetTakeKeyboardEventsOverQt(true);
connect(inputContext.get(), SIGNAL(KeyEventReceived(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
RegisterCommand("help", "Lists all registered commands.", this, SLOT(ListCommands()));
RegisterCommand("clear", "Clears the console log.", this, SLOT(ClearLog()));
RegisterCommand("loglevel", "Sets the current log level. Call with one of the parameters \"error\", \"warning\", \"info\", or \"debug\".",
this, SLOT(SetLogLevel(const QString &)));
shellInputThread = boost::shared_ptr<ShellInputThread>(new ShellInputThread);
QStringList logLevel = fw->CommandLineParameters("--loglevel");
if (logLevel.size() >= 1)
SetLogLevel(logLevel[logLevel.size()-1]);
if (logLevel.size() > 1)
LogWarning("Ignoring multiple --loglevel command line parameters!");
QStringList logFile = fw->CommandLineParameters("--logfile");
if (logFile.size() >= 1)
SetLogFile(logFile[logFile.size()-1]);
if (logFile.size() > 1)
LogWarning("Ignoring multiple --logfile command line parameters!");
}
ConsoleAPI::~ConsoleAPI()
{
Reset();
}
void ConsoleAPI::Reset()
{
commands.clear();
inputContext.reset();
SAFE_DELETE(consoleWidget);
shellInputThread.reset();
SAFE_DELETE(logFileText);
SAFE_DELETE(logFile);
}
QVariant ConsoleCommand::Invoke(const QStringList ¶ms)
{
QVariant returnValue;
// If we have a target QObject, invoke it.
if (target)
{
FunctionInvoker fi;
QString errorMessage;
fi.Invoke(target, functionName, params, &returnValue, &errorMessage);
if (!errorMessage.isEmpty())
LogError("ConsoleCommand::Invoke returned an error: " + errorMessage);
}
// Also, there may exist a script-registered handler that implements this console command - invoke it.
emit Invoked(params);
return returnValue;
}
ConsoleCommand *ConsoleAPI::RegisterCommand(const QString &name, const QString &desc)
{
if (commands.find(name) != commands.end())
{
LogWarning("ConsoleAPI: Command " + name + " is already registered.");
return commands[name].get();
}
boost::shared_ptr<ConsoleCommand> command = boost::shared_ptr<ConsoleCommand>(new ConsoleCommand(name, desc, 0, ""));
commands[name] = command;
return command.get();
}
void ConsoleAPI::RegisterCommand(const QString &name, const QString &desc, QObject *receiver, const char *memberSlot)
{
if (commands.find(name) != commands.end())
{
LogWarning("ConsoleAPI: Command " + name + " is already registered.");
return;
}
boost::shared_ptr<ConsoleCommand> command = boost::shared_ptr<ConsoleCommand>(new ConsoleCommand(name, desc, receiver, memberSlot+1));
commands[name] = command;
}
/// Splits a string of form "MyFunctionName(param1, param2, param3, ...)" into
/// a commandName = "MyFunctionName" and a list of parameters as a StringList.
void ParseCommand(QString command, QString &commandName, QStringList ¶meterList)
{
command = command.trimmed();
if (command.isEmpty())
return;
int split = command.indexOf("(");
if (split == -1)
{
commandName = command;
return;
}
commandName = command.left(split).trimmed();
parameterList = command.mid(split+1).split(",");
}
void ConsoleAPI::ExecuteCommand(const QString &command)
{
PROFILE(ConsoleAPI_ExecuteCommand);
QString commandName;
QStringList parameterList;
ParseCommand(command, commandName, parameterList);
if (commandName.isEmpty())
return;
CommandMap::iterator iter = commands.find(commandName);
if (iter == commands.end())
{
LogError("Cannot find a console command \"" + commandName + "\"!");
return;
}
iter->second->Invoke(parameterList);
}
void ConsoleAPI::Print(const QString &message)
{
if (consoleWidget)
consoleWidget->PrintToConsole(message);
///\todo Temporary hack which appends line ending in case it's not there (output of console commands in headless mode)
if (!message.endsWith("\n"))
{
printf("%s\n", message.toStdString().c_str());
if (logFileText)
{
(*logFileText) << message << "\n";
/// \note If we want to guarantee that each message gets to the log even in the presence of a crash, we must flush()
/// after each write. Tested that on Windows 7, if you kill the process using Ctrl-C on command line, or from
/// task manager, the log will not contain all the text, so this is required for correctness.
/// But this flush() after each message also causes a *serious* performance drawback.
/// One way to try avoiding this issue is to move to using C API for file writing, and at atexit() and other crash
/// handlers, close the file handle gracefully.
logFileText->flush();
}
}
else
{
printf("%s", message.toStdString().c_str());
if (logFileText)
{
(*logFileText) << message;
logFileText->flush(); // See comment about flush() above.
}
}
}
void ConsoleAPI::ListCommands()
{
Print("Available console commands:");
for(CommandMap::iterator iter = commands.begin(); iter != commands.end(); ++iter)
Print(iter->first + " - " + iter->second->Description());
}
void ConsoleAPI::ClearLog()
{
if (consoleWidget)
consoleWidget->ClearLog();
#ifdef _WINDOWS
system("cls");
#else
system("clear");
#endif
}
void ConsoleAPI::SetLogLevel(const QString &level)
{
if (level.compare("error", Qt::CaseInsensitive) == 0)
SetEnabledLogChannels(LogLevelErrorsOnly);
else if (level.compare("warning", Qt::CaseInsensitive) == 0)
SetEnabledLogChannels(LogLevelErrorWarning);
else if (level.compare("info", Qt::CaseInsensitive) == 0)
SetEnabledLogChannels(LogLevelErrorWarnInfo);
else if (level.compare("debug", Qt::CaseInsensitive) == 0)
SetEnabledLogChannels(LogLevelErrorWarnInfoDebug);
else
LogError("Unknown parameter \"" + level + "\" specified to ConsoleAPI::SetLogLevel!");
}
void ConsoleAPI::SetLogFile(const QString &wildCardFilename)
{
QString filename = Application::ParseWildCardFilename(wildCardFilename);
// An empty log file closes the log output writing.
if (filename.isEmpty())
{
SAFE_DELETE(logFileText);
SAFE_DELETE(logFile);
return;
}
logFile = new QFile(filename);
bool isOpen = logFile->open(QIODevice::WriteOnly | QIODevice::Text);
if (!isOpen)
{
LogError("Failed to open file \"" + filename + "\" for logging! (parsed from string \"" + wildCardFilename + "\")");
SAFE_DELETE(logFile);
}
else
{
printf("Opened logging file \"%s\".\n", filename.toStdString().c_str());
logFileText = new QTextStream(logFile);
}
}
void ConsoleAPI::Update(f64 frametime)
{
PROFILE(ConsoleAPI_Update);
std::string input = shellInputThread->GetLine();
if (input.length() > 0)
ExecuteCommand(input.c_str());
}
void ConsoleAPI::ToggleConsole()
{
if (consoleWidget)
consoleWidget->ToggleConsole();
}
void ConsoleAPI::HandleKeyEvent(KeyEvent *e)
{
const QKeySequence &toggleConsole = framework->Input()->KeyBinding("ToggleConsole", QKeySequence(Qt::Key_F1));
if (e->sequence == toggleConsole)
ToggleConsole();
}
void ConsoleAPI::LogInfo(const QString &message)
{
::LogInfo(message);
Print(message);
}
void ConsoleAPI::LogWarning(const QString &message)
{
::LogWarning(message);
Print("Warning: " + message);
}
void ConsoleAPI::LogError(const QString &message)
{
::LogError(message);
Print("Error: " + message);
}
void ConsoleAPI::LogDebug(const QString &message)
{
#ifdef _DEBUG
::LogDebug(message);
Print("Debug: " + message);
#endif
}
void ConsoleAPI::Log(u32 logChannel, const QString &message)
{
if (!IsLogChannelEnabled(logChannel))
return;
Print(message);
}
void ConsoleAPI::SetEnabledLogChannels(u32 newChannels)
{
enabledLogChannels = newChannels;
}
bool ConsoleAPI::IsLogChannelEnabled(u32 logChannel) const
{
return (enabledLogChannels & logChannel) != 0;
}
u32 ConsoleAPI::EnabledLogChannels() const
{
return enabledLogChannels;
}
<commit_msg>ParseCommand: Take into account the possible ending ")" and strip it away from the parameter list. Fixes issue #91, https://github.com/realXtend/naali/issues/91<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file ConsoleAPI.cpp
* @brief Console core API.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "ConsoleAPI.h"
#include "ConsoleWidget.h"
#include "ShellInputThread.h"
#include "Application.h"
#include "Profiler.h"
#include "Framework.h"
#include "InputAPI.h"
#include "UiAPI.h"
#include "UiGraphicsView.h"
#include "LoggingFunctions.h"
#include "FunctionInvoker.h"
#include <stdlib.h>
#include <QFile>
#include <QTextStream>
#include "MemoryLeakCheck.h"
ConsoleAPI::ConsoleAPI(Framework *fw) :
QObject(fw),
framework(fw),
enabledLogChannels(LogLevelErrorWarnInfo),
logFile(0),
logFileText(0)
{
if (!fw->IsHeadless())
consoleWidget = new ConsoleWidget(framework);
inputContext = framework->Input()->RegisterInputContext("Console", 100);
inputContext->SetTakeKeyboardEventsOverQt(true);
connect(inputContext.get(), SIGNAL(KeyEventReceived(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
RegisterCommand("help", "Lists all registered commands.", this, SLOT(ListCommands()));
RegisterCommand("clear", "Clears the console log.", this, SLOT(ClearLog()));
RegisterCommand("loglevel", "Sets the current log level. Call with one of the parameters \"error\", \"warning\", \"info\", or \"debug\".",
this, SLOT(SetLogLevel(const QString &)));
shellInputThread = boost::shared_ptr<ShellInputThread>(new ShellInputThread);
QStringList logLevel = fw->CommandLineParameters("--loglevel");
if (logLevel.size() >= 1)
SetLogLevel(logLevel[logLevel.size()-1]);
if (logLevel.size() > 1)
LogWarning("Ignoring multiple --loglevel command line parameters!");
QStringList logFile = fw->CommandLineParameters("--logfile");
if (logFile.size() >= 1)
SetLogFile(logFile[logFile.size()-1]);
if (logFile.size() > 1)
LogWarning("Ignoring multiple --logfile command line parameters!");
}
ConsoleAPI::~ConsoleAPI()
{
Reset();
}
void ConsoleAPI::Reset()
{
commands.clear();
inputContext.reset();
SAFE_DELETE(consoleWidget);
shellInputThread.reset();
SAFE_DELETE(logFileText);
SAFE_DELETE(logFile);
}
QVariant ConsoleCommand::Invoke(const QStringList ¶ms)
{
QVariant returnValue;
// If we have a target QObject, invoke it.
if (target)
{
FunctionInvoker fi;
QString errorMessage;
fi.Invoke(target, functionName, params, &returnValue, &errorMessage);
if (!errorMessage.isEmpty())
LogError("ConsoleCommand::Invoke returned an error: " + errorMessage);
}
// Also, there may exist a script-registered handler that implements this console command - invoke it.
emit Invoked(params);
return returnValue;
}
ConsoleCommand *ConsoleAPI::RegisterCommand(const QString &name, const QString &desc)
{
if (commands.find(name) != commands.end())
{
LogWarning("ConsoleAPI: Command " + name + " is already registered.");
return commands[name].get();
}
boost::shared_ptr<ConsoleCommand> command = boost::shared_ptr<ConsoleCommand>(new ConsoleCommand(name, desc, 0, ""));
commands[name] = command;
return command.get();
}
void ConsoleAPI::RegisterCommand(const QString &name, const QString &desc, QObject *receiver, const char *memberSlot)
{
if (commands.find(name) != commands.end())
{
LogWarning("ConsoleAPI: Command " + name + " is already registered.");
return;
}
boost::shared_ptr<ConsoleCommand> command = boost::shared_ptr<ConsoleCommand>(new ConsoleCommand(name, desc, receiver, memberSlot+1));
commands[name] = command;
}
/// Splits a string of form "MyFunctionName(param1, param2, param3, ...)" into
/// a commandName = "MyFunctionName" and a list of parameters as a StringList.
void ParseCommand(QString command, QString &commandName, QStringList ¶meterList)
{
command = command.trimmed();
if (command.isEmpty())
return;
int split = command.indexOf("(");
if (split == -1)
{
commandName = command;
return;
}
commandName = command.left(split).trimmed();
// Take into account the possible ending ")" and strip it away from the parameter list.
// Remove it only if it's the last character in the string, as f.ex. some code execution console
// command could contain ')' in the syntax.
int endOfSplit = command.lastIndexOf(")");
if (endOfSplit != -1 && endOfSplit == command.length()-1)
command.remove(endOfSplit, 1);
parameterList = command.mid(split+1).split(",");
}
void ConsoleAPI::ExecuteCommand(const QString &command)
{
PROFILE(ConsoleAPI_ExecuteCommand);
QString commandName;
QStringList parameterList;
ParseCommand(command, commandName, parameterList);
if (commandName.isEmpty())
return;
CommandMap::iterator iter = commands.find(commandName);
if (iter == commands.end())
{
LogError("Cannot find a console command \"" + commandName + "\"!");
return;
}
iter->second->Invoke(parameterList);
}
void ConsoleAPI::Print(const QString &message)
{
if (consoleWidget)
consoleWidget->PrintToConsole(message);
///\todo Temporary hack which appends line ending in case it's not there (output of console commands in headless mode)
if (!message.endsWith("\n"))
{
printf("%s\n", message.toStdString().c_str());
if (logFileText)
{
(*logFileText) << message << "\n";
/// \note If we want to guarantee that each message gets to the log even in the presence of a crash, we must flush()
/// after each write. Tested that on Windows 7, if you kill the process using Ctrl-C on command line, or from
/// task manager, the log will not contain all the text, so this is required for correctness.
/// But this flush() after each message also causes a *serious* performance drawback.
/// One way to try avoiding this issue is to move to using C API for file writing, and at atexit() and other crash
/// handlers, close the file handle gracefully.
logFileText->flush();
}
}
else
{
printf("%s", message.toStdString().c_str());
if (logFileText)
{
(*logFileText) << message;
logFileText->flush(); // See comment about flush() above.
}
}
}
void ConsoleAPI::ListCommands()
{
Print("Available console commands:");
for(CommandMap::iterator iter = commands.begin(); iter != commands.end(); ++iter)
Print(iter->first + " - " + iter->second->Description());
}
void ConsoleAPI::ClearLog()
{
if (consoleWidget)
consoleWidget->ClearLog();
#ifdef _WINDOWS
system("cls");
#else
system("clear");
#endif
}
void ConsoleAPI::SetLogLevel(const QString &level)
{
if (level.compare("error", Qt::CaseInsensitive) == 0)
SetEnabledLogChannels(LogLevelErrorsOnly);
else if (level.compare("warning", Qt::CaseInsensitive) == 0)
SetEnabledLogChannels(LogLevelErrorWarning);
else if (level.compare("info", Qt::CaseInsensitive) == 0)
SetEnabledLogChannels(LogLevelErrorWarnInfo);
else if (level.compare("debug", Qt::CaseInsensitive) == 0)
SetEnabledLogChannels(LogLevelErrorWarnInfoDebug);
else
LogError("Unknown parameter \"" + level + "\" specified to ConsoleAPI::SetLogLevel!");
}
void ConsoleAPI::SetLogFile(const QString &wildCardFilename)
{
QString filename = Application::ParseWildCardFilename(wildCardFilename);
// An empty log file closes the log output writing.
if (filename.isEmpty())
{
SAFE_DELETE(logFileText);
SAFE_DELETE(logFile);
return;
}
logFile = new QFile(filename);
bool isOpen = logFile->open(QIODevice::WriteOnly | QIODevice::Text);
if (!isOpen)
{
LogError("Failed to open file \"" + filename + "\" for logging! (parsed from string \"" + wildCardFilename + "\")");
SAFE_DELETE(logFile);
}
else
{
printf("Opened logging file \"%s\".\n", filename.toStdString().c_str());
logFileText = new QTextStream(logFile);
}
}
void ConsoleAPI::Update(f64 frametime)
{
PROFILE(ConsoleAPI_Update);
std::string input = shellInputThread->GetLine();
if (input.length() > 0)
ExecuteCommand(input.c_str());
}
void ConsoleAPI::ToggleConsole()
{
if (consoleWidget)
consoleWidget->ToggleConsole();
}
void ConsoleAPI::HandleKeyEvent(KeyEvent *e)
{
const QKeySequence &toggleConsole = framework->Input()->KeyBinding("ToggleConsole", QKeySequence(Qt::Key_F1));
if (e->sequence == toggleConsole)
ToggleConsole();
}
void ConsoleAPI::LogInfo(const QString &message)
{
::LogInfo(message);
Print(message);
}
void ConsoleAPI::LogWarning(const QString &message)
{
::LogWarning(message);
Print("Warning: " + message);
}
void ConsoleAPI::LogError(const QString &message)
{
::LogError(message);
Print("Error: " + message);
}
void ConsoleAPI::LogDebug(const QString &message)
{
#ifdef _DEBUG
::LogDebug(message);
Print("Debug: " + message);
#endif
}
void ConsoleAPI::Log(u32 logChannel, const QString &message)
{
if (!IsLogChannelEnabled(logChannel))
return;
Print(message);
}
void ConsoleAPI::SetEnabledLogChannels(u32 newChannels)
{
enabledLogChannels = newChannels;
}
bool ConsoleAPI::IsLogChannelEnabled(u32 logChannel) const
{
return (enabledLogChannels & logChannel) != 0;
}
u32 ConsoleAPI::EnabledLogChannels() const
{
return enabledLogChannels;
}
<|endoftext|> |
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
Random Number Generator implementation
*/
#include <iostream> // for istream, ostream
#include <nupic/utils/Log.hpp>
#include <nupic/utils/Random.hpp>
using namespace nupic;
bool Random::operator==(const Random &o) const {
return seed_ == o.seed_ && \
steps_ == o.steps_ && \
gen == o.gen;
}
Random::Random(UInt64 seed) {
if (seed == 0) {
seed_ = gen(); //generate random value from HW RNG
} else {
seed_ = seed;
}
// if seed is zero at this point, there is a logic error.
NTA_CHECK(seed_ != 0);
gen.seed(seed_); //seed the generator
steps_ = 0;
}
namespace nupic {
std::ostream &operator<<(std::ostream &outStream, const Random &r) {
outStream << "random-v2" << " ";
outStream << r.seed_ << " ";
outStream << r.steps_ << " ";
outStream << "endrandom-v2" << " ";
return outStream;
}
std::istream &operator>>(std::istream &inStream, Random &r) {
std::string version;
inStream >> version;
NTA_CHECK(version == "random-v2") << "Random() deserializer -- found unexpected version string '"
<< version << "'";
inStream >> r.seed_;
r.gen.seed(r.seed_); //reseed
inStream >> r.steps_;
r.gen.discard(r.steps_); //advance n steps
//FIXME we could de/serialize directly RNG gen, it should be multi-platform according to standard,
//but on OSX CI it wasn't (25/11/2018). So "hacking" the above instead.
std::string endtag;
inStream >> endtag;
NTA_CHECK(endtag == "endrandom-v2") << "Random() deserializer -- found unexpected end tag '" << endtag << "'";
inStream.ignore(1);
return inStream;
}
// helper function for seeding RNGs across the plugin barrier
// Unless there is a logic error, should not be called if
// the Random singleton has not been initialized.
UInt32 GetRandomSeed() {
return nupic::Random().getUInt32();
}
} // namespace nupic
<commit_msg>Fix for Random default seed.<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
Random Number Generator implementation
*/
#include <iostream> // for istream, ostream
#include <nupic/utils/Log.hpp>
#include <nupic/utils/Random.hpp>
using namespace nupic;
bool Random::operator==(const Random &o) const {
return seed_ == o.seed_ && \
steps_ == o.steps_ && \
gen == o.gen;
}
std::mt19937 static_gen;
Random::Random(UInt64 seed) {
if (seed == 0) {
seed_ = static_gen(); //generate random value from HW RNG
} else {
seed_ = seed;
}
// if seed is zero at this point, there is a logic error.
NTA_CHECK(seed_ != 0);
gen.seed(seed_); //seed the generator
steps_ = 0;
}
namespace nupic {
std::ostream &operator<<(std::ostream &outStream, const Random &r) {
outStream << "random-v2" << " ";
outStream << r.seed_ << " ";
outStream << r.steps_ << " ";
outStream << "endrandom-v2" << " ";
return outStream;
}
std::istream &operator>>(std::istream &inStream, Random &r) {
std::string version;
inStream >> version;
NTA_CHECK(version == "random-v2") << "Random() deserializer -- found unexpected version string '"
<< version << "'";
inStream >> r.seed_;
r.gen.seed(r.seed_); //reseed
inStream >> r.steps_;
r.gen.discard(r.steps_); //advance n steps
//FIXME we could de/serialize directly RNG gen, it should be multi-platform according to standard,
//but on OSX CI it wasn't (25/11/2018). So "hacking" the above instead.
std::string endtag;
inStream >> endtag;
NTA_CHECK(endtag == "endrandom-v2") << "Random() deserializer -- found unexpected end tag '" << endtag << "'";
inStream.ignore(1);
return inStream;
}
// helper function for seeding RNGs across the plugin barrier
// Unless there is a logic error, should not be called if
// the Random singleton has not been initialized.
UInt32 GetRandomSeed() {
return nupic::Random().getUInt32();
}
} // namespace nupic
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
* drawElements Quality Program EGL Module
* ---------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* 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.
*
*//*!
* \file
* \brief Simple Context construction test.
*//*--------------------------------------------------------------------*/
#include "teglCreateContextTests.hpp"
#include "teglSimpleConfigCase.hpp"
#include "egluStrUtil.hpp"
#include "egluUtil.hpp"
#include "egluUnique.hpp"
#include "eglwLibrary.hpp"
#include "eglwEnums.hpp"
#include "tcuTestLog.hpp"
#include "deSTLUtil.hpp"
namespace deqp
{
namespace egl
{
using std::vector;
using tcu::TestLog;
using namespace eglw;
static const EGLint s_es1Attrs[] = { EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE };
static const EGLint s_es2Attrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
static const EGLint s_es3Attrs[] = { EGL_CONTEXT_MAJOR_VERSION_KHR, 3, EGL_NONE };
static const struct
{
const char* name;
EGLenum api;
EGLint apiBit;
const EGLint* ctxAttrs;
} s_apis[] =
{
{ "OpenGL", EGL_OPENGL_API, EGL_OPENGL_BIT, DE_NULL },
{ "OpenGL ES 1", EGL_OPENGL_ES_API, EGL_OPENGL_ES_BIT, s_es1Attrs },
{ "OpenGL ES 2", EGL_OPENGL_ES_API, EGL_OPENGL_ES2_BIT, s_es2Attrs },
{ "OpenGL ES 3", EGL_OPENGL_ES_API, EGL_OPENGL_ES3_BIT_KHR, s_es3Attrs },
{ "OpenVG", EGL_OPENVG_API, EGL_OPENVG_BIT, DE_NULL }
};
class CreateContextCase : public SimpleConfigCase
{
public:
CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters);
~CreateContextCase (void);
void executeForConfig (EGLDisplay display, EGLConfig config);
};
CreateContextCase::CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters)
: SimpleConfigCase(eglTestCtx, name, description, filters)
{
}
CreateContextCase::~CreateContextCase (void)
{
}
void CreateContextCase::executeForConfig (EGLDisplay display, EGLConfig config)
{
const Library& egl = m_eglTestCtx.getLibrary();
TestLog& log = m_testCtx.getLog();
EGLint id = eglu::getConfigAttribInt(egl, display, config, EGL_CONFIG_ID);
EGLint apiBits = eglu::getConfigAttribInt(egl, display, config, EGL_RENDERABLE_TYPE);
for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
{
if ((apiBits & s_apis[apiNdx].apiBit) == 0)
continue; // Not supported API
log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context with config ID " << id << TestLog::EndMessage;
EGLU_CHECK_MSG(egl, "init");
EGLU_CHECK_CALL(egl, bindAPI(s_apis[apiNdx].api));
EGLContext context = egl.createContext(display, config, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
EGLenum err = egl.getError();
if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
{
log << TestLog::Message << " Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
}
else
{
// Destroy
EGLU_CHECK_CALL(egl, destroyContext(display, context));
log << TestLog::Message << " Pass" << TestLog::EndMessage;
}
}
}
class CreateContextNoConfigCase : public TestCase
{
public:
CreateContextNoConfigCase (EglTestContext& eglTestCtx)
: TestCase(eglTestCtx, "no_config", "EGL_KHR_no_config_context")
{
}
IterateResult iterate (void)
{
const eglw::Library& egl = m_eglTestCtx.getLibrary();
const eglu::UniqueDisplay display (egl, eglu::getAndInitDisplay(m_eglTestCtx.getNativeDisplay(), DE_NULL));
tcu::TestLog& log = m_testCtx.getLog();
if (!eglu::hasExtension(egl, *display, "EGL_KHR_no_config_context"))
TCU_THROW(NotSupportedError, "EGL_KHR_no_config_context is not supported");
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "pass");
for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
{
const EGLenum api = s_apis[apiNdx].api;
if (egl.bindAPI(api) == EGL_FALSE)
{
TCU_CHECK(egl.getError() == EGL_BAD_PARAMETER);
log << TestLog::Message << "eglBindAPI(" << eglu::getAPIStr(api) << ") failed, skipping" << TestLog::EndMessage;
continue;
}
log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context" << TestLog::EndMessage;
const EGLContext context = egl.createContext(*display, (EGLConfig)0, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
const EGLenum err = egl.getError();
if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
{
log << TestLog::Message << " Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
}
else
{
// Destroy
EGLU_CHECK_CALL(egl, destroyContext(*display, context));
log << TestLog::Message << " Pass" << TestLog::EndMessage;
}
}
return STOP;
}
};
CreateContextTests::CreateContextTests (EglTestContext& eglTestCtx)
: TestCaseGroup(eglTestCtx, "create_context", "Basic eglCreateContext() tests")
{
}
CreateContextTests::~CreateContextTests (void)
{
}
void CreateContextTests::init (void)
{
vector<NamedFilterList> filterLists;
getDefaultFilterLists(filterLists, eglu::FilterList());
for (vector<NamedFilterList>::iterator i = filterLists.begin(); i != filterLists.end(); i++)
addChild(new CreateContextCase(m_eglTestCtx, i->getName(), i->getDescription(), *i));
addChild(new CreateContextNoConfigCase(m_eglTestCtx));
}
} // egl
} // deqp
<commit_msg>Handle unsupported no_config contexts am: b60ae978ad am: 307c716b4e am: d217b05e1c<commit_after>/*-------------------------------------------------------------------------
* drawElements Quality Program EGL Module
* ---------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* 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.
*
*//*!
* \file
* \brief Simple Context construction test.
*//*--------------------------------------------------------------------*/
#include "teglCreateContextTests.hpp"
#include "teglSimpleConfigCase.hpp"
#include "egluStrUtil.hpp"
#include "egluUtil.hpp"
#include "egluUnique.hpp"
#include "eglwLibrary.hpp"
#include "eglwEnums.hpp"
#include "tcuTestLog.hpp"
#include "deSTLUtil.hpp"
namespace deqp
{
namespace egl
{
using std::vector;
using tcu::TestLog;
using namespace eglw;
static const EGLint s_glAttrs[] = { EGL_CONTEXT_MAJOR_VERSION_KHR, 3, EGL_NONE };
static const EGLint s_es1Attrs[] = { EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE };
static const EGLint s_es2Attrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
static const EGLint s_es3Attrs[] = { EGL_CONTEXT_MAJOR_VERSION_KHR, 3, EGL_NONE };
static const struct
{
const char* name;
EGLenum api;
EGLint apiBit;
bool noConfigOptional;
const EGLint* ctxAttrs;
} s_apis[] =
{
{ "OpenGL", EGL_OPENGL_API, EGL_OPENGL_BIT, false, s_glAttrs },
{ "OpenGL ES 1", EGL_OPENGL_ES_API, EGL_OPENGL_ES_BIT, true, s_es1Attrs },
{ "OpenGL ES 2", EGL_OPENGL_ES_API, EGL_OPENGL_ES2_BIT, true, s_es2Attrs },
{ "OpenGL ES 3", EGL_OPENGL_ES_API, EGL_OPENGL_ES3_BIT_KHR, false, s_es3Attrs },
{ "OpenVG", EGL_OPENVG_API, EGL_OPENVG_BIT, false, DE_NULL }
};
class CreateContextCase : public SimpleConfigCase
{
public:
CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters);
~CreateContextCase (void);
void executeForConfig (EGLDisplay display, EGLConfig config);
};
CreateContextCase::CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters)
: SimpleConfigCase(eglTestCtx, name, description, filters)
{
}
CreateContextCase::~CreateContextCase (void)
{
}
void CreateContextCase::executeForConfig (EGLDisplay display, EGLConfig config)
{
const Library& egl = m_eglTestCtx.getLibrary();
TestLog& log = m_testCtx.getLog();
EGLint id = eglu::getConfigAttribInt(egl, display, config, EGL_CONFIG_ID);
EGLint apiBits = eglu::getConfigAttribInt(egl, display, config, EGL_RENDERABLE_TYPE);
for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
{
if ((apiBits & s_apis[apiNdx].apiBit) == 0)
continue; // Not supported API
log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context with config ID " << id << TestLog::EndMessage;
EGLU_CHECK_MSG(egl, "init");
EGLU_CHECK_CALL(egl, bindAPI(s_apis[apiNdx].api));
EGLContext context = egl.createContext(display, config, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
EGLenum err = egl.getError();
if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
{
log << TestLog::Message << " Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
}
else
{
// Destroy
EGLU_CHECK_CALL(egl, destroyContext(display, context));
log << TestLog::Message << " Pass" << TestLog::EndMessage;
}
}
}
class CreateContextNoConfigCase : public TestCase
{
public:
CreateContextNoConfigCase (EglTestContext& eglTestCtx)
: TestCase(eglTestCtx, "no_config", "EGL_KHR_no_config_context")
{
}
IterateResult iterate (void)
{
const eglw::Library& egl = m_eglTestCtx.getLibrary();
const eglu::UniqueDisplay display (egl, eglu::getAndInitDisplay(m_eglTestCtx.getNativeDisplay(), DE_NULL));
tcu::TestLog& log = m_testCtx.getLog();
if (!eglu::hasExtension(egl, *display, "EGL_KHR_no_config_context"))
TCU_THROW(NotSupportedError, "EGL_KHR_no_config_context is not supported");
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "pass");
for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
{
const EGLenum api = s_apis[apiNdx].api;
if (egl.bindAPI(api) == EGL_FALSE)
{
TCU_CHECK(egl.getError() == EGL_BAD_PARAMETER);
log << TestLog::Message << "eglBindAPI(" << eglu::getAPIStr(api) << ") failed, skipping" << TestLog::EndMessage;
continue;
}
log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context" << TestLog::EndMessage;
const EGLContext context = egl.createContext(*display, (EGLConfig)0, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
const EGLenum err = egl.getError();
if (context == EGL_NO_CONTEXT && err == EGL_BAD_MATCH && s_apis[apiNdx].noConfigOptional)
{
log << TestLog::Message << " Unsupported" << TestLog::EndMessage;
}
else if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
{
log << TestLog::Message << " Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
}
else
{
// Destroy
EGLU_CHECK_CALL(egl, destroyContext(*display, context));
log << TestLog::Message << " Pass" << TestLog::EndMessage;
}
}
return STOP;
}
};
CreateContextTests::CreateContextTests (EglTestContext& eglTestCtx)
: TestCaseGroup(eglTestCtx, "create_context", "Basic eglCreateContext() tests")
{
}
CreateContextTests::~CreateContextTests (void)
{
}
void CreateContextTests::init (void)
{
vector<NamedFilterList> filterLists;
getDefaultFilterLists(filterLists, eglu::FilterList());
for (vector<NamedFilterList>::iterator i = filterLists.begin(); i != filterLists.end(); i++)
addChild(new CreateContextCase(m_eglTestCtx, i->getName(), i->getDescription(), *i));
addChild(new CreateContextNoConfigCase(m_eglTestCtx));
}
} // egl
} // deqp
<|endoftext|> |
<commit_before>#include "Component.h"
#include "Simulation.h"
#include "MooseApp.h"
unsigned int Component::subdomain_ids = 0;
unsigned int Component::bc_ids = 0;
template<>
InputParameters validParams<Component>()
{
InputParameters params = validParams<R7Object>();
params.addPrivateParam<Simulation *>("_sim");
params.addParam<std::string>("physics_input_file", "Input file with physics");
params.addPrivateParam<std::string>("built_by_action", "add_component");
params.registerBase("Component");
return params;
}
/*
* Class used by Component class to map vector variables through friendly names
* i.e. friendly name = inlet:K_loss; variableName = K_loss, position = 1
*/
RavenMapContainer::RavenMapContainer()
{
}
/*
* CHANGE VARIABLENAME to ControllableName
*/
RavenMapContainer::RavenMapContainer(const std::string & controllableParName, unsigned int & position):
_controllableParName(controllableParName),
_position(position)
{
}
RavenMapContainer::~RavenMapContainer(){
}
const std::string &
RavenMapContainer::getControllableParName(){
return _controllableParName;
}
unsigned int &
RavenMapContainer::getControllableParPosition(){
return _position;
}
/*
* Component implementation
*/
static unsigned int comp_id = 0;
std::string
Component::genName(const std::string & prefix, unsigned int id, const std::string & suffix)
{
std::stringstream ss;
ss << prefix << ":" << id << ":" << suffix;
return ss.str();
}
std::string
Component::genName(const std::string & prefix, const std::string & suffix)
{
std::stringstream ss;
ss << prefix << ":" << suffix;
return ss.str();
}
std::string
Component::genName(const std::string & prefix, const std::string & middle, const std::string & suffix)
{
std::stringstream ss;
ss << prefix << ":" << middle << ":" << suffix;
return ss.str();
}
std::vector<std::string>
Component::split(const std::string & rname)
{
std::vector<std::string> splitted;
MooseUtils::tokenize(rname, splitted, 1, ":");
std::string section_name("");
for (unsigned int i = 0; i < splitted.size() - 1; i++)
{
if (i > 0)
section_name.append(":");
section_name.append(splitted[i]);
}
std::string prop_name = splitted[splitted.size() - 1];
// construct the 2 element array with section and property name
std::vector<std::string> result(2);
result[0] = section_name;
result[1] = prop_name;
return result;
}
Component::Component(const std::string & name, InputParameters parameters) :
R7Object(name, parameters),
_id(comp_id++),
_parent(parameters.have_parameter<Component *>("_parent") ? getParam<Component *>("_parent") : NULL),
_sim(*getParam<Simulation *>("_sim")),
_factory(_app.getFactory()),
_mesh(_sim.mesh()),
_phys_mesh(_sim.physicalMesh()),
_input_file_name(getParam<std::string>("physics_input_file")),
_zero(_sim._zero)
{
}
Component::~Component()
{
}
void
Component::init()
{
}
unsigned int
Component::getNextSubdomainId()
{
unsigned int sd_id = subdomain_ids++;
_subdomains.push_back(sd_id);
if (_parent)
_parent->_subdomains.push_back(sd_id);
return sd_id;
}
unsigned int
Component::getNextBCId()
{
unsigned int id = bc_ids++;
return id;
}
void
Component::aliasParam(const std::string & rname, const std::string & name, Component * comp/* = NULL*/)
{
if (comp == NULL)
_param_alias_map[rname] = std::pair<Component *, std::string>(this, name);
else
_param_alias_map[rname] = std::pair<Component *, std::string>(comp, name);
}
void
Component::aliasVectorParam(const std::string & rname, const std::string & name, unsigned int pos, Component * /*comp = NULL*/)
{
createVectorControllableParMapping(rname, name, pos);
}
void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name)
{
RavenNameEntry rne(mooseName, name);
if (_parent != NULL)
_parent->_rname_map[rname][name].push_back(rne);
else
_rname_map[rname][name].push_back(rne);
}
void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name, const std::string & par_name)
{
RavenNameEntry rne(mooseName, par_name);
if (_parent != NULL)
_parent->_rname_map[rname][name].push_back(rne);
else
_rname_map[rname][name].push_back(rne);
}
void
Component::createVectorControllableParMapping(const std::string & rname, const std::string & mooseName, unsigned int pos)
{
_rvect_map[rname] = RavenMapContainer(mooseName, pos);
}
<commit_msg>Whitespace cleanup - refs idaholab/relap-7#19688<commit_after>#include "Component.h"
#include "Simulation.h"
#include "MooseApp.h"
unsigned int Component::subdomain_ids = 0;
unsigned int Component::bc_ids = 0;
template<>
InputParameters validParams<Component>()
{
InputParameters params = validParams<R7Object>();
params.addPrivateParam<Simulation *>("_sim");
params.addParam<std::string>("physics_input_file", "Input file with physics");
params.addPrivateParam<std::string>("built_by_action", "add_component");
params.registerBase("Component");
return params;
}
/*
* Class used by Component class to map vector variables through friendly names
* i.e. friendly name = inlet:K_loss; variableName = K_loss, position = 1
*/
RavenMapContainer::RavenMapContainer()
{
}
/*
* CHANGE VARIABLENAME to ControllableName
*/
RavenMapContainer::RavenMapContainer(const std::string & controllableParName, unsigned int & position):
_controllableParName(controllableParName),
_position(position)
{
}
RavenMapContainer::~RavenMapContainer(){
}
const std::string &
RavenMapContainer::getControllableParName(){
return _controllableParName;
}
unsigned int &
RavenMapContainer::getControllableParPosition(){
return _position;
}
/*
* Component implementation
*/
static unsigned int comp_id = 0;
std::string
Component::genName(const std::string & prefix, unsigned int id, const std::string & suffix)
{
std::stringstream ss;
ss << prefix << ":" << id << ":" << suffix;
return ss.str();
}
std::string
Component::genName(const std::string & prefix, const std::string & suffix)
{
std::stringstream ss;
ss << prefix << ":" << suffix;
return ss.str();
}
std::string
Component::genName(const std::string & prefix, const std::string & middle, const std::string & suffix)
{
std::stringstream ss;
ss << prefix << ":" << middle << ":" << suffix;
return ss.str();
}
std::vector<std::string>
Component::split(const std::string & rname)
{
std::vector<std::string> splitted;
MooseUtils::tokenize(rname, splitted, 1, ":");
std::string section_name("");
for (unsigned int i = 0; i < splitted.size() - 1; i++)
{
if (i > 0)
section_name.append(":");
section_name.append(splitted[i]);
}
std::string prop_name = splitted[splitted.size() - 1];
// construct the 2 element array with section and property name
std::vector<std::string> result(2);
result[0] = section_name;
result[1] = prop_name;
return result;
}
Component::Component(const std::string & name, InputParameters parameters) :
R7Object(name, parameters),
_id(comp_id++),
_parent(parameters.have_parameter<Component *>("_parent") ? getParam<Component *>("_parent") : NULL),
_sim(*getParam<Simulation *>("_sim")),
_factory(_app.getFactory()),
_mesh(_sim.mesh()),
_phys_mesh(_sim.physicalMesh()),
_input_file_name(getParam<std::string>("physics_input_file")),
_zero(_sim._zero)
{
}
Component::~Component()
{
}
void
Component::init()
{
}
unsigned int
Component::getNextSubdomainId()
{
unsigned int sd_id = subdomain_ids++;
_subdomains.push_back(sd_id);
if (_parent)
_parent->_subdomains.push_back(sd_id);
return sd_id;
}
unsigned int
Component::getNextBCId()
{
unsigned int id = bc_ids++;
return id;
}
void
Component::aliasParam(const std::string & rname, const std::string & name, Component * comp/* = NULL*/)
{
if (comp == NULL)
_param_alias_map[rname] = std::pair<Component *, std::string>(this, name);
else
_param_alias_map[rname] = std::pair<Component *, std::string>(comp, name);
}
void
Component::aliasVectorParam(const std::string & rname, const std::string & name, unsigned int pos, Component * /*comp = NULL*/)
{
createVectorControllableParMapping(rname, name, pos);
}
void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name)
{
RavenNameEntry rne(mooseName, name);
if (_parent != NULL)
_parent->_rname_map[rname][name].push_back(rne);
else
_rname_map[rname][name].push_back(rne);
}
void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name, const std::string & par_name)
{
RavenNameEntry rne(mooseName, par_name);
if (_parent != NULL)
_parent->_rname_map[rname][name].push_back(rne);
else
_rname_map[rname][name].push_back(rne);
}
void
Component::createVectorControllableParMapping(const std::string & rname, const std::string & mooseName, unsigned int pos)
{
_rvect_map[rname] = RavenMapContainer(mooseName, pos);
}
<|endoftext|> |
<commit_before>#include "SolidWall.h"
#include "Simulation.h"
#include "FEProblem.h"
#include "Pipe.h"
#include "Factory.h"
#include "FlowModelSinglePhase.h"
#include "FlowModelTwoPhase.h"
template <>
InputParameters
validParams<SolidWall>()
{
InputParameters params = validParams<FlowBoundary>();
return params;
}
SolidWall::SolidWall(const InputParameters & params) : FlowBoundary(params) {}
void
SolidWall::check()
{
if ((_spatial_discretization == FlowModel::rDG) && (_flow_model_id == RELAP7::FM_TWO_PHASE))
logSpatialDiscretizationNotImplementedError(_spatial_discretization);
}
void
SolidWall::addMooseObjects1Phase()
{
if (_spatial_discretization == FlowModel::CG)
{
InputParameters params = _factory.getValidParams("DirichletBC");
params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA;
params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
params.set<Real>("value") = 0.;
_sim.addBoundaryCondition("DirichletBC", genName(name(), "rhou"), params);
}
else if (_spatial_discretization == FlowModel::rDG)
{
ExecFlagEnum userobject_execute_on(MooseUtils::getDefaultExecFlagEnum());
userobject_execute_on = {EXEC_LINEAR, EXEC_NONLINEAR};
// boundary flux user object
const std::string boundary_flux_name = genName(name(), "boundary_flux");
{
const std::string class_name = "Euler1DVarAreaWallBoundaryFlux";
InputParameters params = _factory.getValidParams(class_name);
params.set<UserObjectName>("rdg_flux") = _rdg_flux_name;
params.set<bool>("implicit") = _implicit_rdg;
params.set<ExecFlagEnum>("execute_on") = userobject_execute_on;
_sim.addUserObject(class_name, boundary_flux_name, params);
}
// BCs
createRDGBoundaryConditions1Phase(boundary_flux_name);
}
}
void
SolidWall::addMooseObjects2Phase()
{
{
InputParameters params = _factory.getValidParams("DirichletBC");
params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_LIQUID;
params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
params.set<Real>("value") = 0.;
_sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_liquid"), params);
}
{
InputParameters params = _factory.getValidParams("DirichletBC");
params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_VAPOR;
params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
params.set<Real>("value") = 0.;
_sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_vapor"), params);
}
}
void
SolidWall::addMooseObjects()
{
if (_flow_model_id == RELAP7::FM_SINGLE_PHASE)
addMooseObjects1Phase();
else if (_flow_model_id == RELAP7::FM_TWO_PHASE)
addMooseObjects2Phase();
}
<commit_msg>Register objects in individual source files instead of RELAP7App.C<commit_after>#include "SolidWall.h"
#include "Simulation.h"
#include "FEProblem.h"
#include "Pipe.h"
#include "Factory.h"
#include "FlowModelSinglePhase.h"
#include "FlowModelTwoPhase.h"
registerMooseObject("RELAP7App", SolidWall);
template <>
InputParameters
validParams<SolidWall>()
{
InputParameters params = validParams<FlowBoundary>();
return params;
}
SolidWall::SolidWall(const InputParameters & params) : FlowBoundary(params) {}
void
SolidWall::check()
{
if ((_spatial_discretization == FlowModel::rDG) && (_flow_model_id == RELAP7::FM_TWO_PHASE))
logSpatialDiscretizationNotImplementedError(_spatial_discretization);
}
void
SolidWall::addMooseObjects1Phase()
{
if (_spatial_discretization == FlowModel::CG)
{
InputParameters params = _factory.getValidParams("DirichletBC");
params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA;
params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
params.set<Real>("value") = 0.;
_sim.addBoundaryCondition("DirichletBC", genName(name(), "rhou"), params);
}
else if (_spatial_discretization == FlowModel::rDG)
{
ExecFlagEnum userobject_execute_on(MooseUtils::getDefaultExecFlagEnum());
userobject_execute_on = {EXEC_LINEAR, EXEC_NONLINEAR};
// boundary flux user object
const std::string boundary_flux_name = genName(name(), "boundary_flux");
{
const std::string class_name = "Euler1DVarAreaWallBoundaryFlux";
InputParameters params = _factory.getValidParams(class_name);
params.set<UserObjectName>("rdg_flux") = _rdg_flux_name;
params.set<bool>("implicit") = _implicit_rdg;
params.set<ExecFlagEnum>("execute_on") = userobject_execute_on;
_sim.addUserObject(class_name, boundary_flux_name, params);
}
// BCs
createRDGBoundaryConditions1Phase(boundary_flux_name);
}
}
void
SolidWall::addMooseObjects2Phase()
{
{
InputParameters params = _factory.getValidParams("DirichletBC");
params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_LIQUID;
params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
params.set<Real>("value") = 0.;
_sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_liquid"), params);
}
{
InputParameters params = _factory.getValidParams("DirichletBC");
params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_VAPOR;
params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
params.set<Real>("value") = 0.;
_sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_vapor"), params);
}
}
void
SolidWall::addMooseObjects()
{
if (_flow_model_id == RELAP7::FM_SINGLE_PHASE)
addMooseObjects1Phase();
else if (_flow_model_id == RELAP7::FM_TWO_PHASE)
addMooseObjects2Phase();
}
<|endoftext|> |
<commit_before>#include "Tilemap.h"
#include "io/FileLoader.h"
#include "graphics/Window.h"
#include "graphics/Drawer.h"
#include "util/Logger.h"
#define DIR "Contents/MainGame/"
//std::string Tilemap::getLocationDir(std::string filename)
//{
// std::string aux;
// int i = filename.find_last_of('/');
// aux.append(filename.substr(0,i) + '/');
// return aux;
//}
std::vector<Uint32> Tilemap::getLayers(int i) const
{
return layers.at(i).data;
}
Tilemap::Tilemap(std::string jsonFile)
{
Json::Value json = FileLoader::LoadJson(jsonFile);
// std::string Dir = getLocationDir(jsonFile);
m_size.x = json["height"].asInt();
m_size.y = json["width"].asInt();
m_tileSize.x = json["tileheight"].asInt();
m_tileSize.y = json["tilewidth"].asInt();
int ArraySize = json["tilesets"].size();
for(int i = 0; i < ArraySize ; ++i)
{
m_tileImages.push_back(new TileImage(FileLoader::LoadTexture(DIR + json["tilesets"][i]["image"].asString()),
json["tilesets"][i]["name"].asString(),
Vector2D<int>(json["tilesets"][i]["imagewidth"].asInt(),
json["tilesets"][i]["imageheight"].asInt()) ));
}
Json::Value jsonLayers = json["layers"];
ArraySize = jsonLayers.size();
for(int i = 0; i < ArraySize; ++i)
{
Layer l1;
l1.size = Vector2D<int>(jsonLayers[i]["width"].asInt(),jsonLayers[i]["height"].asInt());
l1.visible = jsonLayers[i]["visible"].asBool();
if(l1.visible)
{
for(auto iit = jsonLayers[i]["data"].begin();
iit != jsonLayers[i]["data"].end();
++iit)
{
l1.data.push_back((*iit).asInt());
}
layers.push_back(l1);
}
}
tileTexture = std::shared_ptr<Texture>(new Texture(
m_size.x * m_tileSize.x,
m_size.y * m_tileSize.y));
// std::cout << m_size << std::endl;
generateTileMap();
}
Tilemap::~Tilemap()
{
for (auto i : m_tileImages)
delete i;
}
void Tilemap::Render(Vector2D<int> pos)
{
Drawer::Render(tileTexture,pos);
}
void Tilemap::Render(int x, int y)
{
Drawer::Render(tileTexture,x,y);
}
std::vector<Uint32> Tilemap::operator[](int i)
{
return layers.at(i).data;
}
Vector2D<int> Tilemap::getLayerSize()
{
return layers.at(0).size;
}
void Tilemap::generateTileMap()
{
Drawer::RenderTo(tileTexture);
Rect srcrect;
Rect destrect;
Drawer::clearScreen(0,0,0,255);
for(Layer layer : layers)
{
//Pegar o tamanho da imagem em tiles
Vector2D<int> imageSizeIT(m_tileImages[0]->size.x / m_tileSize.x,
m_tileImages[0]->size.y / m_tileSize.y);
//Para cada valor na camada de tiles
for(Uint32 i = 0; i < layer.data.size(); ++i)
{
int value = layer.data[i];
//Gerar um novo retangulo src
srcrect = Rect( ((value-1)%imageSizeIT.x) * m_tileSize.x,
((value-1)/imageSizeIT.x) * m_tileSize.y,
m_tileSize.x,m_tileSize.y);
//Gerar um novo retangulo dest
destrect = Rect( (i%m_size.x) * m_tileSize.x,
(i/m_size.y) * m_tileSize.y,
m_tileSize.x,m_tileSize.y);
m_tileRects.push_back(destrect);
//Renderizar na tela
TileImage *tileimage = m_tileImages[0];
Drawer::Render(tileimage->tex,&srcrect,&destrect);
}
}
Drawer::RenderTo(NULL);
}
<commit_msg>Bug fix: havia um bug na hora de ler os dados do mapa, onde o código pulava uma linha horizontal antes do momento correto<commit_after>#include "Tilemap.h"
#include "io/FileLoader.h"
#include "graphics/Window.h"
#include "graphics/Drawer.h"
#include "util/Logger.h"
#define DIR "Contents/MainGame/"
//std::string Tilemap::getLocationDir(std::string filename)
//{
// std::string aux;
// int i = filename.find_last_of('/');
// aux.append(filename.substr(0,i) + '/');
// return aux;
//}
std::vector<Uint32> Tilemap::getLayers(int i) const
{
return layers.at(i).data;
}
Tilemap::Tilemap(std::string jsonFile)
{
Json::Value json = FileLoader::LoadJson(jsonFile);
// std::string Dir = getLocationDir(jsonFile);
m_size.x = json["width"].asInt();
m_size.y = json["height"].asInt();
m_tileSize.x = json["tilewidth"].asInt();
m_tileSize.y = json["tileheight"].asInt();
int ArraySize = json["tilesets"].size();
for(int i = 0; i < ArraySize ; ++i)
{
m_tileImages.push_back(new TileImage(FileLoader::LoadTexture(DIR + json["tilesets"][i]["image"].asString()),
json["tilesets"][i]["name"].asString(),
Vector2D<int>(json["tilesets"][i]["imagewidth"].asInt(),
json["tilesets"][i]["imageheight"].asInt()) ));
}
Json::Value jsonLayers = json["layers"];
ArraySize = jsonLayers.size();
for(int i = 0; i < ArraySize; ++i)
{
Layer l1;
l1.size = Vector2D<int>(jsonLayers[i]["width"].asInt(),jsonLayers[i]["height"].asInt());
l1.visible = jsonLayers[i]["visible"].asBool();
if(l1.visible)
{
for(auto iit = jsonLayers[i]["data"].begin();
iit != jsonLayers[i]["data"].end();
++iit)
{
l1.data.push_back((*iit).asInt());
}
layers.push_back(l1);
}
}
tileTexture = std::shared_ptr<Texture>(new Texture(
m_size.x * m_tileSize.x,
m_size.y * m_tileSize.y));
// std::cout << m_size << std::endl;
generateTileMap();
}
Tilemap::~Tilemap()
{
for (auto i : m_tileImages)
delete i;
}
void Tilemap::Render(Vector2D<int> pos)
{
Drawer::Render(tileTexture,pos);
}
void Tilemap::Render(int x, int y)
{
Drawer::Render(tileTexture,x,y);
}
std::vector<Uint32> Tilemap::operator[](int i)
{
return layers.at(i).data;
}
Vector2D<int> Tilemap::getLayerSize()
{
return layers.at(0).size;
}
void Tilemap::generateTileMap()
{
Drawer::RenderTo(tileTexture);
Rect srcrect;
Rect destrect;
Drawer::clearScreen(0,0,0,255);
for(Layer layer : layers)
{
//Pegar o tamanho da imagem em tiles
Vector2D<int> imageSizeIT(m_tileImages[0]->size.x / m_tileSize.x,
m_tileImages[0]->size.y / m_tileSize.y);
//Para cada valor na camada de tiles
for(Uint32 i = 0; i < layer.data.size(); ++i)
{
int value = layer.data[i];
//Gerar um novo retangulo src
srcrect = Rect( ((value-1)%imageSizeIT.x) * m_tileSize.x,
((value-1)/imageSizeIT.x) * m_tileSize.y,
m_tileSize.x,m_tileSize.y);
//Gerar um novo retangulo dest
destrect = Rect( (i%m_size.x) * m_tileSize.x,
(i/m_size.x) * m_tileSize.y,
m_tileSize.x,m_tileSize.y);
m_tileRects.push_back(destrect);
//Renderizar na tela
TileImage *tileimage = m_tileImages[0];
Drawer::Render(tileimage->tex,&srcrect,&destrect);
}
}
Drawer::RenderTo(NULL);
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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/>.
*/
/* Patch from Trevor Smigiel */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680
// ---------------------------------------------------------------------------
// A define in the build for each project is also used to control whether
// the export keyword is from the project's viewpoint or the client's.
// These defines provide the platform specific keywords that they need
// to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT
#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_RTTI_AVAILABLE
#define XALAN_NO_TYPEINFO
#define XALAN_SGI_BASED_STL
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_NO_STD_ALLOCATORS
#define XALAN_POSIX2_AVAILABLE
#define XALAN_BIG_ENDIAN
#define XALAN_UNALIGNED
#endif // HPUXDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>Removed #define.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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/>.
*/
/* Patch from Trevor Smigiel */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680
// ---------------------------------------------------------------------------
// A define in the build for each project is also used to control whether
// the export keyword is from the project's viewpoint or the client's.
// These defines provide the platform specific keywords that they need
// to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT
#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_RTTI_AVAILABLE
#define XALAN_SGI_BASED_STL
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_NO_STD_ALLOCATORS
#define XALAN_POSIX2_AVAILABLE
#define XALAN_BIG_ENDIAN
#define XALAN_UNALIGNED
#endif // HPUXDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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/>.
*/
/* Patch from Trevor Smigiel */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680
// ---------------------------------------------------------------------------
// A define in the build for each project is also used to control whether
// the export keyword is from the project's viewpoint or the client's.
// These defines provide the platform specific keywords that they need
// to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT
#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_NO_MEMBER_TEMPLATES
#define XALAN_NO_COVARIANT_RETURN_TYPE
#define XALAN_RTTI_AVAILABLE
#define XALAN_NO_TYPEINFO
#define XALAN_SGI_BASED_STL
#define XALAN_OLD_STYLE_CASTS
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_BIG_ENDIAN
#endif // HPUXDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>HP port based on work from Trevor Smigiel and Troy Heber.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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/>.
*/
/* Patch from Trevor Smigiel */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680
// ---------------------------------------------------------------------------
// A define in the build for each project is also used to control whether
// the export keyword is from the project's viewpoint or the client's.
// These defines provide the platform specific keywords that they need
// to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT
#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_RTTI_AVAILABLE
#define XALAN_SGI_BASED_STL
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_BIG_ENDIAN
#endif // HPUXDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
#include <cassert>
#include <vector>
#include <unordered_map>
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/TypeBuilder.h"
#if (LLVM_VERSION_MINOR >= 5)
#include "llvm/IR/InstIterator.h"
#else
#include "llvm/Support/InstIterator.h"
#endif
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
class InitializeUninitialized : public FunctionPass {
Function *_kms = nullptr; // klee_make_symbolic function
Type *_size_t_Ty = nullptr; // type of size_t
std::unordered_map<llvm::Type *, llvm::GlobalVariable *> added_globals;
// add global of given type and initialize it in may as nondeterministic
GlobalVariable *getGlobalNondet(llvm::Type *, llvm::Module *);
Function *get_klee_make_symbolic(llvm::Module *);
Type *get_size_t(llvm::Module *);
public:
static char ID;
InitializeUninitialized() : FunctionPass(ID) {}
virtual bool runOnFunction(Function &F);
};
static RegisterPass<InitializeUninitialized> INIUNINI("initialize-uninitialized",
"initialize all uninitialized variables to non-deterministic value");
char InitializeUninitialized::ID;
Function *InitializeUninitialized::get_klee_make_symbolic(llvm::Module *M)
{
if (_kms)
return _kms;
LLVMContext& Ctx = M->getContext();
//void klee_make_symbolic(void *addr, size_t nbytes, const char *name);
Constant *C = M->getOrInsertFunction("klee_make_symbolic",
Type::getVoidTy(Ctx),
Type::getInt8PtrTy(Ctx), // addr
get_size_t(M), // nbytes
Type::getInt8PtrTy(Ctx), // name
nullptr);
_kms = cast<Function>(C);
return _kms;
}
Type *InitializeUninitialized::get_size_t(llvm::Module *M)
{
if (_size_t_Ty)
return _size_t_Ty;
std::unique_ptr<DataLayout> DL
= std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));
LLVMContext& Ctx = M->getContext();
if (DL->getPointerSizeInBits() > 32)
_size_t_Ty = Type::getInt64Ty(Ctx);
else
_size_t_Ty = Type::getInt32Ty(Ctx);
return _size_t_Ty;
}
// add global of given type and initialize it in may as nondeterministic
GlobalVariable *InitializeUninitialized::getGlobalNondet(llvm::Type *Ty, llvm::Module *M)
{
auto it = added_globals.find(Ty);
if (it != added_globals.end())
return it->second;
LLVMContext& Ctx = M->getContext();
GlobalVariable *G = new GlobalVariable(*M, Ty, false /* constant */,
GlobalValue::PrivateLinkage,
/* initializer */
Constant::getNullValue(Ty),
"nondet_gl");
added_globals.emplace(Ty, G);
// insert initialization of the new global variable
// at the beginning of main
Function *kms = get_klee_make_symbolic(M);
CastInst *CastI = CastInst::CreatePointerCast(G, Type::getInt8PtrTy(Ctx));
std::vector<Value *> args;
//XXX: we should not build the new DL every time
std::unique_ptr<DataLayout> DL
= std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));
args.push_back(CastI);
args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));
Constant *name = ConstantDataArray::getString(Ctx, "nondet");
GlobalVariable *nameG = new GlobalVariable(*M, name->getType(), true /*constant */,
GlobalVariable::PrivateLinkage, name);
args.push_back(ConstantExpr::getPointerCast(nameG, Type::getInt8PtrTy(Ctx)));
//args.push_back(ConstantPointerNull::get(Type::getInt8PtrTy(Ctx)));
CallInst *CI = CallInst::Create(kms, args);
Function *main = M->getFunction("main");
assert(main && "Do not have main");
BasicBlock& block = main->getBasicBlockList().front();
// there must be some instruction, otherwise we would not be calling
// this function
Instruction& I = *(block.begin());
CastI->insertBefore(&I);
CI->insertBefore(&I);
return G;
}
// no hard analysis, just check wether the alloca is initialized
// in the same block. (we could do an O(n) analysis that would
// do DFS and if the alloca would be initialized on every path
// before reaching some backedge, then it must be initialized),
// for all allocas the running time would be O(n^2) and it could
// probably be decreased (without pointers)
static bool mayBeUnititialized(const llvm::AllocaInst *AI)
{
Type *AITy = AI->getAllocatedType();
if(!AITy->isSized())
return true;
const BasicBlock *block = AI->getParent();
auto I = block->begin();
auto E = block->end();
// shift to AI
while (I != E && (&*I) != AI)
++I;
if (I == E)
return true;
// iterate over instructions after AI in this block
for (++I /* shift after AI */; I != E; ++I) {
if (const StoreInst *SI = dyn_cast<StoreInst>(&*I)) {
// we store into AI and we store the same type
// (that is, we overwrite the whole memory?)
if (SI->getPointerOperand() == AI &&
SI->getValueOperand()->getType() == AITy)
return false;
}
}
return true;
}
bool InitializeUninitialized::runOnFunction(Function &F)
{
// do not run the initializer on __VERIFIER and __INSTR functions
const auto& fname = F.getName();
if (fname.startswith("__VERIFIER_") || fname.startswith("__INSTR_"))
return false;
bool modified = false;
Module *M = F.getParent();
LLVMContext& Ctx = M->getContext();
DataLayout *DL = new DataLayout(M->getDataLayout());
Constant *name_init = ConstantDataArray::getString(Ctx, "nondet");
GlobalVariable *name = new GlobalVariable(*M, name_init->getType(), true,
GlobalValue::PrivateLinkage,
name_init);
Function *C = get_klee_make_symbolic(M);
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E;) {
Instruction *ins = &*I;
++I;
if (AllocaInst *AI = dyn_cast<AllocaInst>(ins)) {
if (!mayBeUnititialized(AI))
continue;
Type *Ty = AI->getAllocatedType();
AllocaInst *newAlloca = nullptr;
CallInst *CI = nullptr;
CastInst *CastI = nullptr;
StoreInst *SI = nullptr;
LoadInst *LI = nullptr;
BinaryOperator *MulI = nullptr;
std::vector<Value *> args;
// create new allocainst, declare it symbolic and store it
// to the original alloca. This way slicer will slice this
// initialization away if program initialize it manually later
if (Ty->isSized()) {
// if this is an array allocation, just call klee_make_symbolic on it,
// since storing whole symbolic array into it would have soo huge overhead
if (Ty->isArrayTy()) {
CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));
args.push_back(CastI);
args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));
args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));
CI = CallInst::Create(C, args);
CastI->insertAfter(AI);
CI->insertAfter(CastI);
} else if (AI->isArrayAllocation()) {
CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));
MulI = BinaryOperator::CreateMul(AI->getArraySize(),
ConstantInt::get(get_size_t(M),
DL->getTypeAllocSize(Ty)),
"val_size");
args.push_back(CastI);
args.push_back(MulI);
args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));
CI = CallInst::Create(C, args);
CastI->insertAfter(AI);
MulI->insertAfter(CastI);
CI->insertAfter(MulI);
} else {
// when this is not an array allocation,
// store the symbolic value into the allocated memory using normal StoreInst.
// That will allow slice away more unneeded allocations
LI = new LoadInst(getGlobalNondet(Ty, M));
SI = new StoreInst(LI, AI);
LI->insertAfter(AI);
SI->insertAfter(LI);
}
modified = true;
}
}
}
delete DL;
return modified;
}
<commit_msg>InitializeUninitialized: make mayBeUninitialized aware of pointers<commit_after>// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
#include <cassert>
#include <vector>
#include <unordered_map>
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/TypeBuilder.h"
#if (LLVM_VERSION_MINOR >= 5)
#include "llvm/IR/InstIterator.h"
#else
#include "llvm/Support/InstIterator.h"
#endif
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
class InitializeUninitialized : public FunctionPass {
Function *_kms = nullptr; // klee_make_symbolic function
Type *_size_t_Ty = nullptr; // type of size_t
std::unordered_map<llvm::Type *, llvm::GlobalVariable *> added_globals;
// add global of given type and initialize it in may as nondeterministic
GlobalVariable *getGlobalNondet(llvm::Type *, llvm::Module *);
Function *get_klee_make_symbolic(llvm::Module *);
Type *get_size_t(llvm::Module *);
public:
static char ID;
InitializeUninitialized() : FunctionPass(ID) {}
virtual bool runOnFunction(Function &F);
};
static RegisterPass<InitializeUninitialized> INIUNINI("initialize-uninitialized",
"initialize all uninitialized variables to non-deterministic value");
char InitializeUninitialized::ID;
Function *InitializeUninitialized::get_klee_make_symbolic(llvm::Module *M)
{
if (_kms)
return _kms;
LLVMContext& Ctx = M->getContext();
//void klee_make_symbolic(void *addr, size_t nbytes, const char *name);
Constant *C = M->getOrInsertFunction("klee_make_symbolic",
Type::getVoidTy(Ctx),
Type::getInt8PtrTy(Ctx), // addr
get_size_t(M), // nbytes
Type::getInt8PtrTy(Ctx), // name
nullptr);
_kms = cast<Function>(C);
return _kms;
}
Type *InitializeUninitialized::get_size_t(llvm::Module *M)
{
if (_size_t_Ty)
return _size_t_Ty;
std::unique_ptr<DataLayout> DL
= std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));
LLVMContext& Ctx = M->getContext();
if (DL->getPointerSizeInBits() > 32)
_size_t_Ty = Type::getInt64Ty(Ctx);
else
_size_t_Ty = Type::getInt32Ty(Ctx);
return _size_t_Ty;
}
// add global of given type and initialize it in may as nondeterministic
GlobalVariable *InitializeUninitialized::getGlobalNondet(llvm::Type *Ty, llvm::Module *M)
{
auto it = added_globals.find(Ty);
if (it != added_globals.end())
return it->second;
LLVMContext& Ctx = M->getContext();
GlobalVariable *G = new GlobalVariable(*M, Ty, false /* constant */,
GlobalValue::PrivateLinkage,
/* initializer */
Constant::getNullValue(Ty),
"nondet_gl");
added_globals.emplace(Ty, G);
// insert initialization of the new global variable
// at the beginning of main
Function *kms = get_klee_make_symbolic(M);
CastInst *CastI = CastInst::CreatePointerCast(G, Type::getInt8PtrTy(Ctx));
std::vector<Value *> args;
//XXX: we should not build the new DL every time
std::unique_ptr<DataLayout> DL
= std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));
args.push_back(CastI);
args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));
Constant *name = ConstantDataArray::getString(Ctx, "nondet");
GlobalVariable *nameG = new GlobalVariable(*M, name->getType(), true /*constant */,
GlobalVariable::PrivateLinkage, name);
args.push_back(ConstantExpr::getPointerCast(nameG, Type::getInt8PtrTy(Ctx)));
//args.push_back(ConstantPointerNull::get(Type::getInt8PtrTy(Ctx)));
CallInst *CI = CallInst::Create(kms, args);
Function *main = M->getFunction("main");
assert(main && "Do not have main");
BasicBlock& block = main->getBasicBlockList().front();
// there must be some instruction, otherwise we would not be calling
// this function
Instruction& I = *(block.begin());
CastI->insertBefore(&I);
CI->insertBefore(&I);
return G;
}
// no hard analysis, just check wether the alloca is initialized
// in the same block. (we could do an O(n) analysis that would
// do DFS and if the alloca would be initialized on every path
// before reaching some backedge, then it must be initialized),
// for all allocas the running time would be O(n^2) and it could
// probably be decreased (without pointers)
static bool mayBeUnititialized(const llvm::AllocaInst *AI)
{
Type *AITy = AI->getAllocatedType();
if(!AITy->isSized())
return true;
const BasicBlock *block = AI->getParent();
auto I = block->begin();
auto E = block->end();
// shift to AI
while (I != E && (&*I) != AI)
++I;
if (I == E)
return true;
// iterate over instructions after AI in this block
for (++I /* shift after AI */; I != E; ++I) {
if (const LoadInst *LI = dyn_cast<LoadInst>(&*I)) {
if (LI->getPointerOperand() == AI)
return true;
} else if (const StoreInst *SI = dyn_cast<StoreInst>(&*I)) {
// we store into AI and we store the same type
// (that is, we overwrite the whole memory?)
if (SI->getPointerOperand() == AI &&
SI->getValueOperand()->getType() == AITy)
return false;
else if (SI->getValueOperand() == AI)
// if we store this address to some pointer,
// we just bail out, since we do not perform
// any points-to analysis
return true;
}
}
return true;
}
bool InitializeUninitialized::runOnFunction(Function &F)
{
// do not run the initializer on __VERIFIER and __INSTR functions
const auto& fname = F.getName();
if (fname.startswith("__VERIFIER_") || fname.startswith("__INSTR_"))
return false;
bool modified = false;
Module *M = F.getParent();
LLVMContext& Ctx = M->getContext();
DataLayout *DL = new DataLayout(M->getDataLayout());
Constant *name_init = ConstantDataArray::getString(Ctx, "nondet");
GlobalVariable *name = new GlobalVariable(*M, name_init->getType(), true,
GlobalValue::PrivateLinkage,
name_init);
Function *C = get_klee_make_symbolic(M);
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E;) {
Instruction *ins = &*I;
++I;
if (AllocaInst *AI = dyn_cast<AllocaInst>(ins)) {
if (!mayBeUnititialized(AI))
continue;
Type *Ty = AI->getAllocatedType();
AllocaInst *newAlloca = nullptr;
CallInst *CI = nullptr;
CastInst *CastI = nullptr;
StoreInst *SI = nullptr;
LoadInst *LI = nullptr;
BinaryOperator *MulI = nullptr;
std::vector<Value *> args;
// create new allocainst, declare it symbolic and store it
// to the original alloca. This way slicer will slice this
// initialization away if program initialize it manually later
if (Ty->isSized()) {
// if this is an array allocation, just call klee_make_symbolic on it,
// since storing whole symbolic array into it would have soo huge overhead
if (Ty->isArrayTy()) {
CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));
args.push_back(CastI);
args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));
args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));
CI = CallInst::Create(C, args);
CastI->insertAfter(AI);
CI->insertAfter(CastI);
} else if (AI->isArrayAllocation()) {
CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));
MulI = BinaryOperator::CreateMul(AI->getArraySize(),
ConstantInt::get(get_size_t(M),
DL->getTypeAllocSize(Ty)),
"val_size");
args.push_back(CastI);
args.push_back(MulI);
args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));
CI = CallInst::Create(C, args);
CastI->insertAfter(AI);
MulI->insertAfter(CastI);
CI->insertAfter(MulI);
} else {
// when this is not an array allocation,
// store the symbolic value into the allocated memory using normal StoreInst.
// That will allow slice away more unneeded allocations
LI = new LoadInst(getGlobalNondet(Ty, M));
SI = new StoreInst(LI, AI);
LI->insertAfter(AI);
SI->insertAfter(LI);
}
modified = true;
}
}
}
delete DL;
return modified;
}
<|endoftext|> |
<commit_before>/*
IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
consideration of your agreement to the following terms, and your use, installation,
modification or redistribution of this Apple software constitutes acceptance of these
terms. If you do not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject to these
terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in
this original Apple software (the "Apple Software"), to use, reproduce, modify and
redistribute the Apple Software, with or without modifications, in source and/or binary
forms; provided that if you redistribute the Apple Software in its entirety and without
modifications, you must retain this notice and the following text and disclaimers in all
such redistributions of the Apple Software. Neither the name, trademarks, service marks
or logos of Apple Computer, Inc. may be used to endorse or promote products derived from
the Apple Software without specific prior written permission from Apple. Except as expressly
stated in this notice, no other rights or licenses, express or implied, are granted by Apple
herein, including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES,
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS
USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND
WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <wtf/Platform.h>
#if PLATFORM(UNIX)
#include <X11/Xlib.h>
#endif
#include "PluginObject.h"
#ifdef WIN32
#define strcasecmp _stricmp
#define NPAPI WINAPI
#else
#define NPAPI
#endif
// Mach-o entry points
extern "C" {
NPError NPAPI NP_Initialize(NPNetscapeFuncs *browserFuncs);
NPError NPAPI NP_GetEntryPoints(NPPluginFuncs *pluginFuncs);
void NPAPI NP_Shutdown(void);
}
// Mach-o entry points
NPError NPAPI NP_Initialize(NPNetscapeFuncs *browserFuncs)
{
browser = browserFuncs;
return NPERR_NO_ERROR;
}
NPError NPAPI NP_GetEntryPoints(NPPluginFuncs *pluginFuncs)
{
pluginFuncs->version = 11;
pluginFuncs->size = sizeof(pluginFuncs);
pluginFuncs->newp = NPP_New;
pluginFuncs->destroy = NPP_Destroy;
pluginFuncs->setwindow = NPP_SetWindow;
pluginFuncs->newstream = NPP_NewStream;
pluginFuncs->destroystream = NPP_DestroyStream;
pluginFuncs->asfile = NPP_StreamAsFile;
pluginFuncs->writeready = NPP_WriteReady;
pluginFuncs->write = (NPP_WriteProcPtr)NPP_Write;
pluginFuncs->print = NPP_Print;
pluginFuncs->event = NPP_HandleEvent;
pluginFuncs->urlnotify = NPP_URLNotify;
pluginFuncs->getvalue = NPP_GetValue;
pluginFuncs->setvalue = NPP_SetValue;
return NPERR_NO_ERROR;
}
void NPAPI NP_Shutdown(void)
{
}
NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved)
{
if (browser->version >= 14) {
PluginObject* obj = (PluginObject*)browser->createobject(instance, getPluginClass());
obj->onStreamLoad = NULL;
for (int i = 0; i < argc; i++) {
if (strcasecmp(argn[i], "onstreamload") == 0 && !obj->onStreamLoad)
obj->onStreamLoad = strdup(argv[i]);
else if (strcasecmp(argn[i], "src") == 0 &&
strcasecmp(argv[i], "data:application/x-webkit-test-netscape,returnerrorfromnewstream") == 0)
obj->returnErrorFromNewStream = TRUE;
else if (strcasecmp(argn[i], "logfirstsetwindow") == 0)
obj->logSetWindow = TRUE;
}
instance->pdata = obj;
}
// On Windows and Unix, plugins only get events if they are windowless.
return browser->setvalue(instance, NPPVpluginWindowBool, NULL);
}
NPError NPP_Destroy(NPP instance, NPSavedData **save)
{
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
if (obj) {
if (obj->onStreamLoad)
free(obj->onStreamLoad);
if (obj->logDestroy)
printf("PLUGIN: NPP_Destroy\n");
browser->releaseobject(&obj->header);
}
fflush(stdout);
return NPERR_NO_ERROR;
}
NPError NPP_SetWindow(NPP instance, NPWindow *window)
{
if (window->window == NULL) {
return NPERR_NO_ERROR;
}
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
if (obj) {
if (obj->logSetWindow) {
printf("PLUGIN: NPP_SetWindow: %d %d\n", (int)window->width, (int)window->height);
obj->logSetWindow = false;
}
}
return NPERR_NO_ERROR;
}
NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream, NPBool seekable, uint16 *stype)
{
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
obj->stream = stream;
*stype = NP_ASFILEONLY;
if (obj->returnErrorFromNewStream)
return NPERR_GENERIC_ERROR;
if (browser->version >= NPVERS_HAS_RESPONSE_HEADERS)
notifyStream(obj, stream->url, stream->headers);
if (obj->onStreamLoad) {
NPObject *windowScriptObject;
browser->getvalue(obj->npp, NPNVWindowNPObject, &windowScriptObject);
NPString script;
script.UTF8Characters = obj->onStreamLoad;
script.UTF8Length = strlen(obj->onStreamLoad);
NPVariant browserResult;
browser->evaluate(obj->npp, windowScriptObject, &script, &browserResult);
browser->releasevariantvalue(&browserResult);
}
return NPERR_NO_ERROR;
}
NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason)
{
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
obj->stream = 0;
return NPERR_NO_ERROR;
}
int32 NPP_WriteReady(NPP instance, NPStream *stream)
{
return 0;
}
int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer)
{
return 0;
}
void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname)
{
}
void NPP_Print(NPP instance, NPPrint *platformPrint)
{
}
int16 NPP_HandleEvent(NPP instance, void *event)
{
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
if (!obj->eventLogging)
return 0;
#ifdef WIN32
// Below is the event handling code. Per the NPAPI spec, the events don't
// map directly between operating systems:
// http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
NPEvent* evt = static_cast<NPEvent*>(event);
short x = static_cast<short>(evt->lParam & 0xffff);
short y = static_cast<short>(evt->lParam >> 16);
switch (evt->event) {
case WM_PAINT:
printf("PLUGIN: updateEvt\n");
break;
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
printf("PLUGIN: mouseDown at (%d, %d)\n", x, y);
break;
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
printf("PLUGIN: mouseUp at (%d, %d)\n", x, y);
break;
case WM_LBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
break;
case WM_MOUSEMOVE:
printf("PLUGIN: adjustCursorEvent\n");
break;
case WM_KEYUP:
// TODO(tc): We need to convert evt->wParam from virtual-key code
// to key code.
printf("NOTIMPLEMENTED PLUGIN: keyUp '%c'\n", ' ');
break;
case WM_KEYDOWN:
// TODO(tc): We need to convert evt->wParam from virtual-key code
// to key code.
printf("NOTIMPLEMENTED PLUGIN: keyDown '%c'\n", ' ');
break;
case WM_SETCURSOR:
break;
case WM_SETFOCUS:
printf("PLUGIN: getFocusEvent\n");
break;
case WM_KILLFOCUS:
printf("PLUGIN: loseFocusEvent\n");
break;
default:
printf("PLUGIN: event %d\n", evt->event);
}
fflush(stdout);
#elif PLATFORM(UNIX)
XEvent* evt = static_cast<XEvent*>(event);
XButtonPressedEvent* bpress_evt = reinterpret_cast<XButtonPressedEvent*>(evt);
XButtonReleasedEvent* brelease_evt = reinterpret_cast<XButtonReleasedEvent*>(evt);
switch (evt->type) {
case ButtonPress:
printf("PLUGIN: mouseDown at (%d, %d)\n", bpress_evt->x, bpress_evt->y);
break;
case ButtonRelease:
printf("PLUGIN: mouseUp at (%d, %d)\n", brelease_evt->x, brelease_evt->y);
break;
case KeyPress:
// TODO: extract key code
printf("NOTIMPLEMENTED PLUGIN: keyDown '%c'\n", ' ');
break;
case KeyRelease:
// TODO: extract key code
printf("NOTIMPLEMENTED PLUGIN: keyUp '%c'\n", ' ');
break;
case GraphicsExpose:
printf("PLUGIN: updateEvt\n");
break;
// NPAPI events
case FocusIn:
printf("PLUGIN: getFocusEvent\n");
break;
case FocusOut:
printf("PLUGIN: loseFocusEvent\n");
break;
case EnterNotify:
case LeaveNotify:
case MotionNotify:
printf("PLUGIN: adjustCursorEvent\n");
break;
default:
printf("PLUGIN: event %d\n", evt->type);
}
fflush(stdout);
#else
EventRecord* evt = static_cast<EventRecord*>(event);
Point pt = { evt->where.v, evt->where.h };
switch (evt->what) {
case nullEvent:
// these are delivered non-deterministically, don't log.
break;
case mouseDown:
GlobalToLocal(&pt);
printf("PLUGIN: mouseDown at (%d, %d)\n", pt.h, pt.v);
break;
case mouseUp:
GlobalToLocal(&pt);
printf("PLUGIN: mouseUp at (%d, %d)\n", pt.h, pt.v);
break;
case keyDown:
printf("PLUGIN: keyDown '%c'\n", (char)(evt->message & 0xFF));
break;
case keyUp:
printf("PLUGIN: keyUp '%c'\n", (char)(evt->message & 0xFF));
break;
case autoKey:
printf("PLUGIN: autoKey '%c'\n", (char)(evt->message & 0xFF));
break;
case updateEvt:
printf("PLUGIN: updateEvt\n");
break;
case diskEvt:
printf("PLUGIN: diskEvt\n");
break;
case activateEvt:
printf("PLUGIN: activateEvt\n");
break;
case osEvt:
printf("PLUGIN: osEvt - ");
switch ((evt->message & 0xFF000000) >> 24) {
case suspendResumeMessage:
printf("%s\n", (evt->message & 0x1) ? "resume" : "suspend");
break;
case mouseMovedMessage:
printf("mouseMoved\n");
break;
default:
printf("%08lX\n", evt->message);
}
break;
case kHighLevelEvent:
printf("PLUGIN: kHighLevelEvent\n");
break;
// NPAPI events
case getFocusEvent:
printf("PLUGIN: getFocusEvent\n");
break;
case loseFocusEvent:
printf("PLUGIN: loseFocusEvent\n");
break;
case adjustCursorEvent:
printf("PLUGIN: adjustCursorEvent\n");
break;
default:
printf("PLUGIN: event %d\n", evt->what);
}
#endif
return 0;
}
void NPP_URLNotify(NPP instance, const char *url, NPReason reason, void *notifyData)
{
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
handleCallback(obj, url, reason, notifyData);
}
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value)
{
if (variable == NPPVpluginScriptableNPObject) {
void **v = (void **)value;
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
// Return value is expected to be retained
browser->retainobject((NPObject *)obj);
*v = obj;
return NPERR_NO_ERROR;
}
return NPERR_GENERIC_ERROR;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value)
{
return NPERR_GENERIC_ERROR;
}
<commit_msg>Temporarily disable any use of Xlib in our code until we get the X development libs on the buildbots.<commit_after>/*
IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
consideration of your agreement to the following terms, and your use, installation,
modification or redistribution of this Apple software constitutes acceptance of these
terms. If you do not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject to these
terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in
this original Apple software (the "Apple Software"), to use, reproduce, modify and
redistribute the Apple Software, with or without modifications, in source and/or binary
forms; provided that if you redistribute the Apple Software in its entirety and without
modifications, you must retain this notice and the following text and disclaimers in all
such redistributions of the Apple Software. Neither the name, trademarks, service marks
or logos of Apple Computer, Inc. may be used to endorse or promote products derived from
the Apple Software without specific prior written permission from Apple. Except as expressly
stated in this notice, no other rights or licenses, express or implied, are granted by Apple
herein, including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES,
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS
USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND
WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <wtf/Platform.h>
// The buildbot doesn't have Xlib. Rather than revert this, I've just
// temporarily ifdef'd it out.
#ifdef XLIB_TEMPORARILY_DISABLED
#if PLATFORM(UNIX)
#include <X11/Xlib.h>
#endif
#endif
#include "PluginObject.h"
#ifdef WIN32
#define strcasecmp _stricmp
#define NPAPI WINAPI
#else
#define NPAPI
#endif
// Mach-o entry points
extern "C" {
NPError NPAPI NP_Initialize(NPNetscapeFuncs *browserFuncs);
NPError NPAPI NP_GetEntryPoints(NPPluginFuncs *pluginFuncs);
void NPAPI NP_Shutdown(void);
}
// Mach-o entry points
NPError NPAPI NP_Initialize(NPNetscapeFuncs *browserFuncs)
{
browser = browserFuncs;
return NPERR_NO_ERROR;
}
NPError NPAPI NP_GetEntryPoints(NPPluginFuncs *pluginFuncs)
{
pluginFuncs->version = 11;
pluginFuncs->size = sizeof(pluginFuncs);
pluginFuncs->newp = NPP_New;
pluginFuncs->destroy = NPP_Destroy;
pluginFuncs->setwindow = NPP_SetWindow;
pluginFuncs->newstream = NPP_NewStream;
pluginFuncs->destroystream = NPP_DestroyStream;
pluginFuncs->asfile = NPP_StreamAsFile;
pluginFuncs->writeready = NPP_WriteReady;
pluginFuncs->write = (NPP_WriteProcPtr)NPP_Write;
pluginFuncs->print = NPP_Print;
pluginFuncs->event = NPP_HandleEvent;
pluginFuncs->urlnotify = NPP_URLNotify;
pluginFuncs->getvalue = NPP_GetValue;
pluginFuncs->setvalue = NPP_SetValue;
return NPERR_NO_ERROR;
}
void NPAPI NP_Shutdown(void)
{
}
NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved)
{
if (browser->version >= 14) {
PluginObject* obj = (PluginObject*)browser->createobject(instance, getPluginClass());
obj->onStreamLoad = NULL;
for (int i = 0; i < argc; i++) {
if (strcasecmp(argn[i], "onstreamload") == 0 && !obj->onStreamLoad)
obj->onStreamLoad = strdup(argv[i]);
else if (strcasecmp(argn[i], "src") == 0 &&
strcasecmp(argv[i], "data:application/x-webkit-test-netscape,returnerrorfromnewstream") == 0)
obj->returnErrorFromNewStream = TRUE;
else if (strcasecmp(argn[i], "logfirstsetwindow") == 0)
obj->logSetWindow = TRUE;
}
instance->pdata = obj;
}
// On Windows and Unix, plugins only get events if they are windowless.
return browser->setvalue(instance, NPPVpluginWindowBool, NULL);
}
NPError NPP_Destroy(NPP instance, NPSavedData **save)
{
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
if (obj) {
if (obj->onStreamLoad)
free(obj->onStreamLoad);
if (obj->logDestroy)
printf("PLUGIN: NPP_Destroy\n");
browser->releaseobject(&obj->header);
}
fflush(stdout);
return NPERR_NO_ERROR;
}
NPError NPP_SetWindow(NPP instance, NPWindow *window)
{
if (window->window == NULL) {
return NPERR_NO_ERROR;
}
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
if (obj) {
if (obj->logSetWindow) {
printf("PLUGIN: NPP_SetWindow: %d %d\n", (int)window->width, (int)window->height);
obj->logSetWindow = false;
}
}
return NPERR_NO_ERROR;
}
NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream, NPBool seekable, uint16 *stype)
{
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
obj->stream = stream;
*stype = NP_ASFILEONLY;
if (obj->returnErrorFromNewStream)
return NPERR_GENERIC_ERROR;
if (browser->version >= NPVERS_HAS_RESPONSE_HEADERS)
notifyStream(obj, stream->url, stream->headers);
if (obj->onStreamLoad) {
NPObject *windowScriptObject;
browser->getvalue(obj->npp, NPNVWindowNPObject, &windowScriptObject);
NPString script;
script.UTF8Characters = obj->onStreamLoad;
script.UTF8Length = strlen(obj->onStreamLoad);
NPVariant browserResult;
browser->evaluate(obj->npp, windowScriptObject, &script, &browserResult);
browser->releasevariantvalue(&browserResult);
}
return NPERR_NO_ERROR;
}
NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason)
{
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
obj->stream = 0;
return NPERR_NO_ERROR;
}
int32 NPP_WriteReady(NPP instance, NPStream *stream)
{
return 0;
}
int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer)
{
return 0;
}
void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname)
{
}
void NPP_Print(NPP instance, NPPrint *platformPrint)
{
}
int16 NPP_HandleEvent(NPP instance, void *event)
{
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
if (!obj->eventLogging)
return 0;
#ifdef WIN32
// Below is the event handling code. Per the NPAPI spec, the events don't
// map directly between operating systems:
// http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
NPEvent* evt = static_cast<NPEvent*>(event);
short x = static_cast<short>(evt->lParam & 0xffff);
short y = static_cast<short>(evt->lParam >> 16);
switch (evt->event) {
case WM_PAINT:
printf("PLUGIN: updateEvt\n");
break;
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
printf("PLUGIN: mouseDown at (%d, %d)\n", x, y);
break;
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
printf("PLUGIN: mouseUp at (%d, %d)\n", x, y);
break;
case WM_LBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
break;
case WM_MOUSEMOVE:
printf("PLUGIN: adjustCursorEvent\n");
break;
case WM_KEYUP:
// TODO(tc): We need to convert evt->wParam from virtual-key code
// to key code.
printf("NOTIMPLEMENTED PLUGIN: keyUp '%c'\n", ' ');
break;
case WM_KEYDOWN:
// TODO(tc): We need to convert evt->wParam from virtual-key code
// to key code.
printf("NOTIMPLEMENTED PLUGIN: keyDown '%c'\n", ' ');
break;
case WM_SETCURSOR:
break;
case WM_SETFOCUS:
printf("PLUGIN: getFocusEvent\n");
break;
case WM_KILLFOCUS:
printf("PLUGIN: loseFocusEvent\n");
break;
default:
printf("PLUGIN: event %d\n", evt->event);
}
fflush(stdout);
#elif PLATFORM(UNIX)
#ifdef XLIB_TEMPORARILY_DISABLED
XEvent* evt = static_cast<XEvent*>(event);
XButtonPressedEvent* bpress_evt = reinterpret_cast<XButtonPressedEvent*>(evt);
XButtonReleasedEvent* brelease_evt = reinterpret_cast<XButtonReleasedEvent*>(evt);
switch (evt->type) {
case ButtonPress:
printf("PLUGIN: mouseDown at (%d, %d)\n", bpress_evt->x, bpress_evt->y);
break;
case ButtonRelease:
printf("PLUGIN: mouseUp at (%d, %d)\n", brelease_evt->x, brelease_evt->y);
break;
case KeyPress:
// TODO: extract key code
printf("NOTIMPLEMENTED PLUGIN: keyDown '%c'\n", ' ');
break;
case KeyRelease:
// TODO: extract key code
printf("NOTIMPLEMENTED PLUGIN: keyUp '%c'\n", ' ');
break;
case GraphicsExpose:
printf("PLUGIN: updateEvt\n");
break;
// NPAPI events
case FocusIn:
printf("PLUGIN: getFocusEvent\n");
break;
case FocusOut:
printf("PLUGIN: loseFocusEvent\n");
break;
case EnterNotify:
case LeaveNotify:
case MotionNotify:
printf("PLUGIN: adjustCursorEvent\n");
break;
default:
printf("PLUGIN: event %d\n", evt->type);
}
fflush(stdout);
#endif // XLIB_TEMPORARILY_DISABLED
#else
EventRecord* evt = static_cast<EventRecord*>(event);
Point pt = { evt->where.v, evt->where.h };
switch (evt->what) {
case nullEvent:
// these are delivered non-deterministically, don't log.
break;
case mouseDown:
GlobalToLocal(&pt);
printf("PLUGIN: mouseDown at (%d, %d)\n", pt.h, pt.v);
break;
case mouseUp:
GlobalToLocal(&pt);
printf("PLUGIN: mouseUp at (%d, %d)\n", pt.h, pt.v);
break;
case keyDown:
printf("PLUGIN: keyDown '%c'\n", (char)(evt->message & 0xFF));
break;
case keyUp:
printf("PLUGIN: keyUp '%c'\n", (char)(evt->message & 0xFF));
break;
case autoKey:
printf("PLUGIN: autoKey '%c'\n", (char)(evt->message & 0xFF));
break;
case updateEvt:
printf("PLUGIN: updateEvt\n");
break;
case diskEvt:
printf("PLUGIN: diskEvt\n");
break;
case activateEvt:
printf("PLUGIN: activateEvt\n");
break;
case osEvt:
printf("PLUGIN: osEvt - ");
switch ((evt->message & 0xFF000000) >> 24) {
case suspendResumeMessage:
printf("%s\n", (evt->message & 0x1) ? "resume" : "suspend");
break;
case mouseMovedMessage:
printf("mouseMoved\n");
break;
default:
printf("%08lX\n", evt->message);
}
break;
case kHighLevelEvent:
printf("PLUGIN: kHighLevelEvent\n");
break;
// NPAPI events
case getFocusEvent:
printf("PLUGIN: getFocusEvent\n");
break;
case loseFocusEvent:
printf("PLUGIN: loseFocusEvent\n");
break;
case adjustCursorEvent:
printf("PLUGIN: adjustCursorEvent\n");
break;
default:
printf("PLUGIN: event %d\n", evt->what);
}
#endif
return 0;
}
void NPP_URLNotify(NPP instance, const char *url, NPReason reason, void *notifyData)
{
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
handleCallback(obj, url, reason, notifyData);
}
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value)
{
if (variable == NPPVpluginScriptableNPObject) {
void **v = (void **)value;
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
// Return value is expected to be retained
browser->retainobject((NPObject *)obj);
*v = obj;
return NPERR_NO_ERROR;
}
return NPERR_GENERIC_ERROR;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value)
{
return NPERR_GENERIC_ERROR;
}
<|endoftext|> |
<commit_before>/*
Copyright 2011 StormMQ 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "Memory/PoolTestSupport.h"
#include "debug_helper.h"
SUITE(Pool)
{
TEST_FIXTURE(InitializedPoolFixture, callback_should_initialize_object)
{
test_type_t *p = (test_type_t *) amqp_allocate(&pool);
CHECK_EQUAL('A', p->important_stuff[0]);
for (unsigned i = 0; i < sizeof(p->important_stuff); i++)
{
CHECK_EQUAL('A' + (int) i, p->important_stuff[i]);
}
amqp_deallocate(&pool, p);
}
#ifdef DISABLE_MEMORY_POOL
TEST_FIXTURE(InitializedPoolFixture, verify_allocation_works_when_pool_disabled)
{
test_type_t *p, *q;
p = (test_type_t *) amqp_allocate(&pool);
q = (test_type_t *) amqp_allocate(&pool);
amqp_deallocate(&pool, p);
amqp_deallocate(&pool, q);
}
#else
TEST_FIXTURE(InitializedPoolFixture, first_allocate_from_pool_allocates_block)
{
CHECK_NULL(pool.block_list);
amqp_memory_pool_t *p = (amqp_memory_pool_t *) amqp_allocate(&pool);
CHECK_NOT_NULL(p);
CHECK_NOT_NULL(pool.block_list);
CHECK_NULL(pool.block_list->header.previous);
CHECK_NULL(pool.block_list->header.next);
amqp_deallocate(&pool, p);
}
TEST_FIXTURE(InitializedPoolFixture, allocate_from_pool)
{
test_type_t *p = (test_type_t *) amqp_allocate(&pool);
CHECK_NOT_NULL(pool.block_list);
CHECK_NULL(pool.block_list->header.previous);
CHECK_NULL(pool.block_list->header.next);
CHECK_EQUAL(0xfe, pool.block_list->header.mask.bytes[0]);
CHECK_NOT_NULL(p);
amqp_deallocate(&pool, p);
}
TEST_FIXTURE(InitializedPoolFixture, allocate_from_pool_increases_allocation_count)
{
int i;
for (i = 0; i < LONG_BIT; i++)
{
allocate_from_pool();
CHECK_EQUAL((unsigned long) (i + 1), pool.stats.outstanding_allocations);
CHECK_EQUAL((unsigned long) (i + 1), pool.stats.total_allocation_calls);
}
while (i > 0)
{
i--;
return_last_allocated_to_pool();
CHECK_EQUAL((unsigned long) i, pool.stats.outstanding_allocations);
}
CHECK_EQUAL((unsigned long) LONG_BIT, pool.stats.total_allocation_calls);
}
TEST_FIXTURE(InitializedPoolFixture, allocations_should_be_reflected_in_mask)
{
allocate_from_pool(7);
CHECK_EQUAL(0x80U, (unsigned) pool.block_list->header.mask.bytes[0]);
allocate_from_pool(1);
CHECK_EQUAL(0x00U, (unsigned) pool.block_list->header.mask.bytes[0]);
CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[1]);
allocate_from_pool(1);
CHECK_EQUAL(0xfeU, (unsigned) pool.block_list->header.mask.bytes[1]);
CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[2]);
allocate_from_pool(6);
CHECK_EQUAL(0x80U, (unsigned) pool.block_list->header.mask.bytes[1]);
allocate_from_pool(1);
CHECK_EQUAL(0x00U, (unsigned) pool.block_list->header.mask.bytes[1]);
CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[2]);
allocate_from_pool(1);
CHECK_EQUAL(0xfeU, (unsigned) pool.block_list->header.mask.bytes[2]);
CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[3]);
}
class BlockChainingTestFixture : public PoolFixture
{
public:
BlockChainingTestFixture() { }
~BlockChainingTestFixture() { }
void test()
{
allocate_from_pool(1);
amqp_memory_block_t *first_block = pool.block_list;
CHECK_NULL(pool.block_list->header.previous);
CHECK_NULL(pool.block_list->header.next);
allocate_from_pool(pool.allocations_per_block - 1);
CHECK_EQUAL(first_block, pool.block_list);
CHECK_NULL(pool.block_list->header.previous);
CHECK_NULL(pool.block_list->header.next);
allocate_from_pool(1);
amqp_memory_block_t *second_block = pool.block_list;
CHECK_EQUAL(first_block, pool.block_list->header.next);
CHECK_NULL(pool.block_list->header.previous);
CHECK_NULL(pool.block_list->header.next->header.next);
CHECK_EQUAL(second_block, pool.block_list->header.next->header.previous);
}
};
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block)
{
initialize_pool();
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_256)
{
break_one();
initialize_pool(256);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_512)
{
initialize_pool(512);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_768)
{
initialize_pool(768);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_1024)
{
initialize_pool(1024);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_1526)
{
initialize_pool(1526);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_2048)
{
initialize_pool(2048);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_4096)
{
initialize_pool(4096);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, free_allocation_in_block_should_result_in_block_removal_from_chain)
{
initialize_pool(256);
CHECK_NULL(pool.block_list); // no blocks on the pool
// allocate first block
allocate_from_pool();
amqp_memory_block_t *first_block = pool.block_list;
// allocate remainder of slots in the first block
allocate_from_pool(pool.allocations_per_block - 1);
CHECK_EQUAL(first_block, pool.block_list);
// allocate second block
allocate_from_pool();
amqp_memory_block_t *second_block = pool.block_list;
CHECK(first_block != second_block);
// allocate remainder of slots in the second block
allocate_from_pool(pool.allocations_per_block - 1);
CHECK_EQUAL(second_block, pool.block_list);
// allocate another causing a third block to be allocated
test_type_t *p = (test_type_t *) amqp_allocate(&pool);
amqp_memory_block_t *third_block = pool.block_list;
CHECK(second_block != third_block);
CHECK_NULL(first_block->header.next);
CHECK_EQUAL(second_block, first_block->header.previous);
CHECK_EQUAL(first_block, second_block->header.next);
CHECK_EQUAL(third_block, second_block->header.previous);
CHECK_EQUAL(second_block, third_block->header.next);
CHECK_NULL(third_block->header.previous);
for (int i = 0; i < pool.allocations_per_block; i++)
{
return_last_allocated_to_pool(); // return last allocated by call to allocate_from_pool();
}
// verify that the second block has been removed from the block list
// because all its allocations have been deallocated
CHECK_EQUAL(third_block, pool.block_list);
CHECK_NULL(third_block->header.previous);
CHECK_EQUAL(first_block, third_block->header.next);
CHECK_NULL(first_block->header.next);
CHECK_EQUAL(third_block, first_block->header.previous);
// now remove the last allocation from the pool causing the third block to be removed from the list.
amqp_deallocate(&pool, p);
CHECK_EQUAL(first_block, pool.block_list);
CHECK_NULL(first_block->header.previous);
CHECK_NULL(first_block->header.next);
// deallocate everything from the first block
for (int i = 0; i < pool.allocations_per_block; i++)
{
return_last_allocated_to_pool(); // return last allocated by call to allocate_from_pool();
}
CHECK_NULL(pool.block_list); // assert that there are no blocks left
}
#endif
}
<commit_msg>Remove an unnecessary check that caused tests on 32-bit linux to fail.<commit_after>/*
Copyright 2011 StormMQ 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "Memory/PoolTestSupport.h"
#include "debug_helper.h"
SUITE(Pool)
{
TEST_FIXTURE(InitializedPoolFixture, callback_should_initialize_object)
{
test_type_t *p = (test_type_t *) amqp_allocate(&pool);
CHECK_EQUAL('A', p->important_stuff[0]);
for (unsigned i = 0; i < sizeof(p->important_stuff); i++)
{
CHECK_EQUAL('A' + (int) i, p->important_stuff[i]);
}
amqp_deallocate(&pool, p);
}
#ifdef DISABLE_MEMORY_POOL
TEST_FIXTURE(InitializedPoolFixture, verify_allocation_works_when_pool_disabled)
{
test_type_t *p, *q;
p = (test_type_t *) amqp_allocate(&pool);
q = (test_type_t *) amqp_allocate(&pool);
amqp_deallocate(&pool, p);
amqp_deallocate(&pool, q);
}
#else
TEST_FIXTURE(InitializedPoolFixture, first_allocate_from_pool_allocates_block)
{
CHECK_NULL(pool.block_list);
amqp_memory_pool_t *p = (amqp_memory_pool_t *) amqp_allocate(&pool);
CHECK_NOT_NULL(p);
CHECK_NOT_NULL(pool.block_list);
CHECK_NULL(pool.block_list->header.previous);
CHECK_NULL(pool.block_list->header.next);
amqp_deallocate(&pool, p);
}
TEST_FIXTURE(InitializedPoolFixture, allocate_from_pool)
{
test_type_t *p = (test_type_t *) amqp_allocate(&pool);
CHECK_NOT_NULL(pool.block_list);
CHECK_NULL(pool.block_list->header.previous);
CHECK_NULL(pool.block_list->header.next);
CHECK_EQUAL(0xfe, pool.block_list->header.mask.bytes[0]);
CHECK_NOT_NULL(p);
amqp_deallocate(&pool, p);
}
TEST_FIXTURE(InitializedPoolFixture, allocate_from_pool_increases_allocation_count)
{
int i;
for (i = 0; i < LONG_BIT; i++)
{
allocate_from_pool();
CHECK_EQUAL((unsigned long) (i + 1), pool.stats.outstanding_allocations);
CHECK_EQUAL((unsigned long) (i + 1), pool.stats.total_allocation_calls);
}
while (i > 0)
{
i--;
return_last_allocated_to_pool();
CHECK_EQUAL((unsigned long) i, pool.stats.outstanding_allocations);
}
CHECK_EQUAL((unsigned long) LONG_BIT, pool.stats.total_allocation_calls);
}
TEST_FIXTURE(InitializedPoolFixture, allocations_should_be_reflected_in_mask)
{
allocate_from_pool(1);
CHECK_EQUAL(0xfeU, (unsigned) pool.block_list->header.mask.bytes[0]);
allocate_from_pool(6);
CHECK_EQUAL(0x80U, (unsigned) pool.block_list->header.mask.bytes[0]);
allocate_from_pool(1);
CHECK_EQUAL(0x00U, (unsigned) pool.block_list->header.mask.bytes[0]);
CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[1]);
allocate_from_pool(1);
CHECK_EQUAL(0xfeU, (unsigned) pool.block_list->header.mask.bytes[1]);
CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[2]);
allocate_from_pool(6);
CHECK_EQUAL(0x80U, (unsigned) pool.block_list->header.mask.bytes[1]);
allocate_from_pool(1);
CHECK_EQUAL(0x00U, (unsigned) pool.block_list->header.mask.bytes[1]);
CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[2]);
allocate_from_pool(1);
CHECK_EQUAL(0xfeU, (unsigned) pool.block_list->header.mask.bytes[2]);
}
class BlockChainingTestFixture : public PoolFixture
{
public:
BlockChainingTestFixture() { }
~BlockChainingTestFixture() { }
void test()
{
allocate_from_pool(1);
amqp_memory_block_t *first_block = pool.block_list;
CHECK_NULL(pool.block_list->header.previous);
CHECK_NULL(pool.block_list->header.next);
allocate_from_pool(pool.allocations_per_block - 1);
CHECK_EQUAL(first_block, pool.block_list);
CHECK_NULL(pool.block_list->header.previous);
CHECK_NULL(pool.block_list->header.next);
allocate_from_pool(1);
amqp_memory_block_t *second_block = pool.block_list;
CHECK_EQUAL(first_block, pool.block_list->header.next);
CHECK_NULL(pool.block_list->header.previous);
CHECK_NULL(pool.block_list->header.next->header.next);
CHECK_EQUAL(second_block, pool.block_list->header.next->header.previous);
}
};
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block)
{
initialize_pool();
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_256)
{
break_one();
initialize_pool(256);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_512)
{
initialize_pool(512);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_768)
{
initialize_pool(768);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_1024)
{
initialize_pool(1024);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_1526)
{
initialize_pool(1526);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_2048)
{
initialize_pool(2048);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_4096)
{
initialize_pool(4096);
test();
}
TEST_FIXTURE(BlockChainingTestFixture, free_allocation_in_block_should_result_in_block_removal_from_chain)
{
initialize_pool(256);
CHECK_NULL(pool.block_list); // no blocks on the pool
// allocate first block
allocate_from_pool();
amqp_memory_block_t *first_block = pool.block_list;
// allocate remainder of slots in the first block
allocate_from_pool(pool.allocations_per_block - 1);
CHECK_EQUAL(first_block, pool.block_list);
// allocate second block
allocate_from_pool();
amqp_memory_block_t *second_block = pool.block_list;
CHECK(first_block != second_block);
// allocate remainder of slots in the second block
allocate_from_pool(pool.allocations_per_block - 1);
CHECK_EQUAL(second_block, pool.block_list);
// allocate another causing a third block to be allocated
test_type_t *p = (test_type_t *) amqp_allocate(&pool);
amqp_memory_block_t *third_block = pool.block_list;
CHECK(second_block != third_block);
CHECK_NULL(first_block->header.next);
CHECK_EQUAL(second_block, first_block->header.previous);
CHECK_EQUAL(first_block, second_block->header.next);
CHECK_EQUAL(third_block, second_block->header.previous);
CHECK_EQUAL(second_block, third_block->header.next);
CHECK_NULL(third_block->header.previous);
for (int i = 0; i < pool.allocations_per_block; i++)
{
return_last_allocated_to_pool(); // return last allocated by call to allocate_from_pool();
}
// verify that the second block has been removed from the block list
// because all its allocations have been deallocated
CHECK_EQUAL(third_block, pool.block_list);
CHECK_NULL(third_block->header.previous);
CHECK_EQUAL(first_block, third_block->header.next);
CHECK_NULL(first_block->header.next);
CHECK_EQUAL(third_block, first_block->header.previous);
// now remove the last allocation from the pool causing the third block to be removed from the list.
amqp_deallocate(&pool, p);
CHECK_EQUAL(first_block, pool.block_list);
CHECK_NULL(first_block->header.previous);
CHECK_NULL(first_block->header.next);
// deallocate everything from the first block
for (int i = 0; i < pool.allocations_per_block; i++)
{
return_last_allocated_to_pool(); // return last allocated by call to allocate_from_pool();
}
CHECK_NULL(pool.block_list); // assert that there are no blocks left
}
#endif
}
<|endoftext|> |
<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/connection_type_histograms.h"
#include "base/histogram.h"
namespace net {
// We're using a histogram as a group of counters. We're only interested in
// the values of the counters. Ignore the shape, average, and standard
// deviation of the histograms because they are meaningless.
//
// We use two groups of counters. In the first group (counter1), each counter
// is a boolean (0 or 1) that indicates whether the user has seen a connection
// of that type during that session. In the second group (counter2), each
// counter is the number of connections of that type the user has seen during
// that session.
void UpdateConnectionTypeHistograms(ConnectionType type) {
static bool had_connection_type[NUM_OF_CONNECTION_TYPES];
static LinearHistogram counter1(L"Net.HadConnectionType",
1, NUM_OF_CONNECTION_TYPES - 1,
NUM_OF_CONNECTION_TYPES);
static LinearHistogram counter2(L"Net.ConnectionTypeCount",
1, NUM_OF_CONNECTION_TYPES - 1,
NUM_OF_CONNECTION_TYPES);
if (type >= 0 && type < NUM_OF_CONNECTION_TYPES) {
if (!had_connection_type[type]) {
had_connection_type[type] = true;
counter1.Add(type);
}
}
counter2.Add(type);
}
} // namespace net
<commit_msg>Push MD5 certificate histograms to UMA.<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/connection_type_histograms.h"
#include "base/histogram.h"
namespace net {
// We're using a histogram as a group of counters. We're only interested in
// the values of the counters. Ignore the shape, average, and standard
// deviation of the histograms because they are meaningless.
//
// We use two groups of counters. In the first group (counter1), each counter
// is a boolean (0 or 1) that indicates whether the user has seen a connection
// of that type during that session. In the second group (counter2), each
// counter is the number of connections of that type the user has seen during
// that session.
//
// Each histogram has an unused bucket at the end to allow seamless future
// expansion.
void UpdateConnectionTypeHistograms(ConnectionType type) {
static bool had_connection_type[NUM_OF_CONNECTION_TYPES];
static LinearHistogram counter1(L"Net.HadConnectionType",
1, NUM_OF_CONNECTION_TYPES,
NUM_OF_CONNECTION_TYPES + 1);
static LinearHistogram counter2(L"Net.ConnectionTypeCount",
1, NUM_OF_CONNECTION_TYPES,
NUM_OF_CONNECTION_TYPES + 1);
if (type >= 0 && type < NUM_OF_CONNECTION_TYPES) {
if (!had_connection_type[type]) {
had_connection_type[type] = true;
counter1.SetFlags(kUmaTargetedHistogramFlag);
counter1.Add(type);
}
}
counter2.SetFlags(kUmaTargetedHistogramFlag);
counter2.Add(type);
}
} // namespace net
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MeasureHandler.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2008-01-10 11:40:22 $
*
* 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 INCLUDED_MEASUREHANDLER_HXX
#define INCLUDED_MEASUREHANDLER_HXX
#ifndef INCLUDED_WRITERFILTERDLLAPI_H
#include <WriterFilterDllApi.hxx>
#endif
#include <resourcemodel/WW8ResourceModel.hxx>
#include <boost/shared_ptr.hpp>
namespace writerfilter {
namespace dmapper
{
class PropertyMap;
/** Handler for sprms that contain a measure and a unit
- Left indent of tables
- Preferred width of tables
*/
class WRITERFILTER_DLLPRIVATE MeasureHandler : public Properties
{
sal_Int32 m_nMeasureValue;
sal_Int32 m_nUnit;
sal_Int16 m_nRowHeightSizeType; //table row height type
public:
MeasureHandler();
virtual ~MeasureHandler();
// Properties
virtual void attribute(Id Name, Value & val);
virtual void sprm(Sprm & sprm);
sal_Int32 getMeasureValue() const;
//at least tables can have automatic width
bool isAutoWidth() const;
sal_Int16 GetRowHeightSizeType() const { return m_nRowHeightSizeType;}
};
typedef boost::shared_ptr
< MeasureHandler > MeasureHandlerPtr;
}}
#endif //
<commit_msg>INTEGRATION: CWS changefileheader (1.4.20); FILE MERGED 2008/04/01 13:02:28 thb 1.4.20.2: #i85898# Stripping all external header guards 2008/03/28 15:53:00 rt 1.4.20.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MeasureHandler.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_MEASUREHANDLER_HXX
#define INCLUDED_MEASUREHANDLER_HXX
#include <WriterFilterDllApi.hxx>
#include <resourcemodel/WW8ResourceModel.hxx>
#include <boost/shared_ptr.hpp>
namespace writerfilter {
namespace dmapper
{
class PropertyMap;
/** Handler for sprms that contain a measure and a unit
- Left indent of tables
- Preferred width of tables
*/
class WRITERFILTER_DLLPRIVATE MeasureHandler : public Properties
{
sal_Int32 m_nMeasureValue;
sal_Int32 m_nUnit;
sal_Int16 m_nRowHeightSizeType; //table row height type
public:
MeasureHandler();
virtual ~MeasureHandler();
// Properties
virtual void attribute(Id Name, Value & val);
virtual void sprm(Sprm & sprm);
sal_Int32 getMeasureValue() const;
//at least tables can have automatic width
bool isAutoWidth() const;
sal_Int16 GetRowHeightSizeType() const { return m_nRowHeightSizeType;}
};
typedef boost::shared_ptr
< MeasureHandler > MeasureHandlerPtr;
}}
#endif //
<|endoftext|> |
<commit_before>#include "OsiCplexSolverInterface.hpp"
#include <CoinMpsIO.hpp>
#include <cplex.h>
//#include <algorithm>
// default constructor
OsiCplexSolverInterface::OsiCplexSolverInterface(): OsiCpxSolverInterface() {
CPXENVptr env = getEnvironmentPtr();
// set parameter number of threads to 1, CPXPARAM_Threads
CPXINT num_threads = 1;
CPXINT status;
// Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
if (status) {
std::cerr << "Cplex status error!" << std::endl;
throw std::exception();
}
}
// copy constructor
OsiCplexSolverInterface::OsiCplexSolverInterface(const OsiCplexSolverInterface & other):
OsiCpxSolverInterface(other) {
CPXENVptr env = getEnvironmentPtr();
// set parameter number of threads to 1, CPXPARAM_Threads
CPXINT num_threads = 1;
CPXINT status;
// Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
if (status) {
std::cerr << "Cplex status error!" << std::endl;
throw std::exception();
}
}
// copy assignment operator
OsiCplexSolverInterface & OsiCplexSolverInterface::operator=(const OsiCplexSolverInterface & rhs) {
// copy rhs to this
OsiCpxSolverInterface::operator=(rhs);
CPXENVptr env = getEnvironmentPtr();
// set parameter number of threads to 1, CPXPARAM_Threads
CPXINT num_threads = 1;
CPXINT status;
// Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
if (status) {
std::cerr << "Cplex status error!" << std::endl;
throw std::exception();
}
return *this;
}
// get conic constraints
void OsiCplexSolverInterface::getConicConstraint(int index,
OsiLorentzConeType & type,
int & numMembers,
int *& members) const {
int ok = 0;
// cplex status, 0 for success
int status;
// number of linear part nonzeros
int linnz;
int linsurplus = 0;
// number of quadratic part nonzeros
int qnz;
numMembers = 0;
CPXLPptr lp = getMutableLpPtr();
CPXENVptr env = getMutableEnvironmentPtr();
// detect array lengths
status = CPXgetqconstr(env, lp, &linnz, &qnz, NULL, NULL,
NULL, NULL, 0, &linsurplus,
NULL, NULL, NULL, 0, &numMembers, index);
if (status==0) {
// means number of variables in cone is 0.
return;
}
else if (status == CPXERR_NEGATIVE_SURPLUS) {
// linear or quadratic cone size was not enough
if (numMembers==0) {
// cone size was enough, means no member in cone
return;
}
else {
// cone size is greater than 0
numMembers = -numMembers;
}
}
// allocate memory for quadratic part
int * qrow = new int[numMembers];
int * qcol = new int[numMembers];
double * qval = new double[numMembers];
int qsurplus;
// call get constraints again with updated cone size
status = CPXgetqconstr(env, lp, &linnz, &qnz, NULL, NULL,
NULL, NULL, 0, &linsurplus,
qrow, qcol, qval, numMembers, &qsurplus, index);
if (status!=0 && status!=CPXERR_NEGATIVE_SURPLUS) {
std::cerr << "Cplex status error!" << std::endl;
throw std::exception();
}
if (qsurplus<0) {
std::cerr << "This should not happen. Cplex cheated!" << std::endl;
throw std::exception();
}
members = qcol;
delete[] qrow;
if (qval[0]==-1.0 && qval[1]==1.0) {
type = OSI_QUAD;
}
else {
std::cerr << "This part is not implemented yet!" << std::endl;
throw std::exception();
}
delete[] qval;
}
// add conic constraint in lorentz cone form
void OsiCplexSolverInterface::addConicConstraint(OsiLorentzConeType type,
int numMembers,
const int * members) {
if (type==OSI_RQUAD) {
std::cerr << "Rotated Cones are not implemented yet!" << std::endl;
throw std::exception();
}
int status;
CPXLPptr lp = getMutableLpPtr();
CPXENVptr env = getEnvironmentPtr();
double * qval = new double[numMembers];
qval[0] = -1.0;
std::fill_n(qval+1, numMembers-1, 1.0);
status = CPXaddqconstr (env, lp, 0, numMembers,
0.0, 'L', NULL, NULL,
members, members, qval, NULL);
if (status != 0) {
std::cerr << "Cplex function is not successful." << std::endl;
throw std::exception();
}
// leading variable is nonnegative
double bound[] = {0.0};
char lu[] = {'L'};
status = CPXchgbds (env, lp, 1, members, lu, bound);
if (status != 0) {
std::cerr << "Cplex function is not successful." << std::endl;
throw std::exception();
}
}
// add conic constraint in |Ax-b| <= dx-h form
void OsiCplexSolverInterface::addConicConstraint(CoinPackedMatrix const * A,
CoinPackedVector const * b,
CoinPackedVector const * d,
double h) {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
void OsiCplexSolverInterface::removeConicConstraint(int index) {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
void OsiCplexSolverInterface::modifyConicConstraint(int index,
OsiLorentzConeType type,
int numMembers,
const int * members) {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
int OsiCplexSolverInterface::getNumCones() const {
CPXLPptr lp = getMutableLpPtr();
CPXENVptr env = getMutableEnvironmentPtr();
int n = CPXgetnumqconstrs(env, lp);
return n;
}
int OsiCplexSolverInterface::getConeSize(int i) const {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
OsiConeType OsiCplexSolverInterface::getConeType(int i) const {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
OsiLorentzConeType OsiCplexSolverInterface::getLorentzConeType(int i) const {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
// fills array of cone sizes.
void OsiCplexSolverInterface::getConeSize(int * size) const {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
// fills array of cone types.
void OsiCplexSolverInterface::getConeType(OsiConeType * type) const {
int num_cones = getNumCones();
for (int i=0; i<num_cones; ++i) {
type[i] = getConeType(i);
}
}
void OsiCplexSolverInterface::getConeType(OsiLorentzConeType * type) const {
int num_cones = getNumCones();
for (int i=0; i<num_cones; ++i) {
type[i] = getLorentzConeType(i);
}
}
OsiConicSolverInterface * OsiCplexSolverInterface::clone(bool copyData) const {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
OsiCplexSolverInterface::~OsiCplexSolverInterface() {
}
int OsiCplexSolverInterface::readMps(const char * filename,
const char * extension) {
OsiConicSolverInterface::readMps(filename, extension);
}
void OsiCplexSolverInterface::initialSolve() {
//todo(aykut) I am not sure what switchToLp() does.
switchToLP();
CPXLPptr lp = getMutableLpPtr();
CPXENVptr env = getEnvironmentPtr();
double objoffset;
double primalobjlimit;
double dualobjlimit;
if (messageHandler()->logLevel() == 0)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 0);
else if (messageHandler()->logLevel() == 1)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 1);
else if (messageHandler()->logLevel() > 1)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 2);
getDblParam(OsiObjOffset, objoffset);
getDblParam(OsiPrimalObjectiveLimit, primalobjlimit);
getDblParam(OsiDualObjectiveLimit, dualobjlimit);
if (getObjSense() == +1) {
if (primalobjlimit < COIN_DBL_MAX)
CPXsetdblparam(env, CPX_PARAM_OBJLLIM, primalobjlimit + objoffset);
if (dualobjlimit > -COIN_DBL_MAX)
CPXsetdblparam(env, CPX_PARAM_OBJULIM, dualobjlimit + objoffset);
}
else {
if (primalobjlimit > -COIN_DBL_MAX)
CPXsetdblparam(env, CPX_PARAM_OBJULIM, primalobjlimit + objoffset);
if (dualobjlimit < COIN_DBL_MAX)
CPXsetdblparam(env, CPX_PARAM_OBJLLIM, dualobjlimit + objoffset);
}
int status = CPXhybbaropt(env, lp, CPX_ALG_NONE);
if (status!=0) {
std::cerr << "Cplex did not return 0 status." << std::endl;
throw std::exception();
}
}
//-----------------------------------------------------------------------------
// resolve is same as initialSolve, no warm start capability.
void OsiCplexSolverInterface::resolve() {
//todo(aykut) I am not sure what switchToLp() does.
switchToLP();
CPXLPptr lp = getMutableLpPtr();
CPXENVptr env = getEnvironmentPtr();
if (messageHandler()->logLevel() == 0)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 0);
else if (messageHandler()->logLevel() == 1)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 1);
else if (messageHandler()->logLevel() > 1)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 2);
int status = CPXhybbaropt(env, lp, CPX_ALG_NONE);
if (status!=0) {
std::cerr << "Cplex did not return 0 status." << std::endl;
throw std::exception();
}
}
<commit_msg>Adding rotated lorentz cones implemented.<commit_after>#include "OsiCplexSolverInterface.hpp"
#include <CoinMpsIO.hpp>
#include <cplex.h>
//#include <algorithm>
// todo(aykut)
// error check routine. Copied from OsiCpxSolverInterface.
// I am not sure whether this is a license violation. This
// may be removed/replaced in future.
// I would not experince any problem if this function was not static
// in OsiCpxSolverInterface.cpp. Since it is, I have to copy it here
// and create redundancy.
static inline void
checkCPXerror(int err, std::string cpxfuncname, std::string osimethod) {
if(err != 0) {
char s[100];
sprintf( s, "%s returned error %d", cpxfuncname.c_str(), err );
#ifdef DEBUG
std::cerr << "ERROR: " << s << " (" << osimethod << " in OsiCpxSolverInterface)" << std::endl;
#endif
throw CoinError(s, osimethod.c_str(), "OsiCplexSolverInterface");
}
}
// default constructor
OsiCplexSolverInterface::OsiCplexSolverInterface(): OsiCpxSolverInterface() {
CPXENVptr env = getEnvironmentPtr();
// set parameter number of threads to 1, CPXPARAM_Threads
CPXINT num_threads = 1;
CPXINT status;
// Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
if (status) {
std::cerr << "Cplex status error!" << std::endl;
throw std::exception();
}
}
// copy constructor
OsiCplexSolverInterface::OsiCplexSolverInterface(const OsiCplexSolverInterface & other):
OsiCpxSolverInterface(other) {
CPXENVptr env = getEnvironmentPtr();
// set parameter number of threads to 1, CPXPARAM_Threads
CPXINT num_threads = 1;
CPXINT status;
// Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
if (status) {
std::cerr << "Cplex status error!" << std::endl;
throw std::exception();
}
}
// copy assignment operator
OsiCplexSolverInterface & OsiCplexSolverInterface::operator=(const OsiCplexSolverInterface & rhs) {
// copy rhs to this
OsiCpxSolverInterface::operator=(rhs);
CPXENVptr env = getEnvironmentPtr();
// set parameter number of threads to 1, CPXPARAM_Threads
CPXINT num_threads = 1;
CPXINT status;
// Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
if (status) {
std::cerr << "Cplex status error!" << std::endl;
throw std::exception();
}
return *this;
}
// get conic constraints
void OsiCplexSolverInterface::getConicConstraint(int index,
OsiLorentzConeType & type,
int & numMembers,
int *& members) const {
int ok = 0;
// cplex status, 0 for success
int status;
// number of linear part nonzeros
int linnz;
int linsurplus = 0;
// number of quadratic part nonzeros
int qnz;
numMembers = 0;
CPXLPptr lp = getMutableLpPtr();
CPXENVptr env = getMutableEnvironmentPtr();
// detect array lengths
status = CPXgetqconstr(env, lp, &linnz, &qnz, NULL, NULL,
NULL, NULL, 0, &linsurplus,
NULL, NULL, NULL, 0, &numMembers, index);
if (status==0) {
// means number of variables in cone is 0.
return;
}
else if (status == CPXERR_NEGATIVE_SURPLUS) {
// linear or quadratic cone size was not enough
if (numMembers==0) {
// cone size was enough, means no member in cone
return;
}
else {
// cone size is greater than 0
numMembers = -numMembers;
}
}
// allocate memory for quadratic part
int * qrow = new int[numMembers];
int * qcol = new int[numMembers];
double * qval = new double[numMembers];
int qsurplus;
// call get constraints again with updated cone size
status = CPXgetqconstr(env, lp, &linnz, &qnz, NULL, NULL,
NULL, NULL, 0, &linsurplus,
qrow, qcol, qval, numMembers, &qsurplus, index);
if (status!=0 && status!=CPXERR_NEGATIVE_SURPLUS) {
std::cerr << "Cplex status error!" << std::endl;
throw std::exception();
}
if (qsurplus<0) {
std::cerr << "This should not happen. Cplex cheated!" << std::endl;
throw std::exception();
}
members = qcol;
delete[] qrow;
if (qval[0]==-1.0 && qval[1]==1.0) {
type = OSI_QUAD;
}
else {
std::cerr << "This part is not implemented yet!" << std::endl;
throw std::exception();
}
delete[] qval;
}
// add conic constraint in lorentz cone form
void OsiCplexSolverInterface::addConicConstraint(OsiLorentzConeType type,
int numMembers,
const int * members) {
int status;
CPXLPptr lp = getMutableLpPtr();
CPXENVptr env = getEnvironmentPtr();
if (type==OSI_QUAD) {
double * qval = new double[numMembers];
qval[0] = -1.0;
std::fill_n(qval+1, numMembers-1, 1.0);
status = CPXaddqconstr (env, lp, 0, numMembers,
0.0, 'L', NULL, NULL,
members, members, qval, NULL);
delete[] qval;
checkCPXerror(status, std::string("CPXaddqconstr"),
std::string("addConicConstraint"));
// leading variable is nonnegative
double bound[] = {0.0};
char lu[] = {'L'};
status = CPXchgbds (env, lp, 1, members, lu, bound);
checkCPXerror(status, std::string("CPXchgbds"),
std::string("addConicConstraint"));
}
else if (type==OSI_RQUAD) {
double * qval = new double[numMembers-1];
qval[0] = -2.0;
std::fill_n(qval+1, numMembers-1, 1.0);
int * members2 = new int[numMembers-1];
members2[0] = members[0];
std::copy(members+2, members+numMembers, members2+1);
status = CPXaddqconstr (env, lp, 0, numMembers-1,
0.0, 'L', NULL, NULL,
members+1, members2, qval, NULL);
delete[] qval;
delete[] members2;
checkCPXerror(status, std::string("CPXaddqconstr"),
std::string("addConicConstraint"));
// leading variable is nonnegative
double bound[] = {0.0};
char lu[] = {'L'};
// update lower bound to 0 for leading variables
status = CPXchgbds (env, lp, 1, members, lu, bound);
checkCPXerror(status, std::string("CPXchgbds"),
std::string("addConicConstraint"));
status = CPXchgbds (env, lp, 1, members+1, lu, bound);
checkCPXerror(status, std::string("CPXchgbds"),
std::string("addConicConstraint"));
}
else {
std::cerr << "Unknown cone type!" << std::endl;
throw std::exception();
}
}
// add conic constraint in |Ax-b| <= dx-h form
void OsiCplexSolverInterface::addConicConstraint(CoinPackedMatrix const * A,
CoinPackedVector const * b,
CoinPackedVector const * d,
double h) {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
void OsiCplexSolverInterface::removeConicConstraint(int index) {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
void OsiCplexSolverInterface::modifyConicConstraint(int index,
OsiLorentzConeType type,
int numMembers,
const int * members) {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
int OsiCplexSolverInterface::getNumCones() const {
CPXLPptr lp = getMutableLpPtr();
CPXENVptr env = getMutableEnvironmentPtr();
int n = CPXgetnumqconstrs(env, lp);
return n;
}
int OsiCplexSolverInterface::getConeSize(int i) const {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
OsiConeType OsiCplexSolverInterface::getConeType(int i) const {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
OsiLorentzConeType OsiCplexSolverInterface::getLorentzConeType(int i) const {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
// fills array of cone sizes.
void OsiCplexSolverInterface::getConeSize(int * size) const {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
// fills array of cone types.
void OsiCplexSolverInterface::getConeType(OsiConeType * type) const {
int num_cones = getNumCones();
for (int i=0; i<num_cones; ++i) {
type[i] = getConeType(i);
}
}
void OsiCplexSolverInterface::getConeType(OsiLorentzConeType * type) const {
int num_cones = getNumCones();
for (int i=0; i<num_cones; ++i) {
type[i] = getLorentzConeType(i);
}
}
OsiConicSolverInterface * OsiCplexSolverInterface::clone(bool copyData) const {
std::cerr << "Not implemented yet!" << std::cerr;
throw std::exception();
}
OsiCplexSolverInterface::~OsiCplexSolverInterface() {
}
int OsiCplexSolverInterface::readMps(const char * filename,
const char * extension) {
OsiConicSolverInterface::readMps(filename, extension);
}
void OsiCplexSolverInterface::initialSolve() {
//todo(aykut) I am not sure what switchToLp() does.
switchToLP();
CPXLPptr lp = getMutableLpPtr();
CPXENVptr env = getEnvironmentPtr();
double objoffset;
double primalobjlimit;
double dualobjlimit;
if (messageHandler()->logLevel() == 0)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 0);
else if (messageHandler()->logLevel() == 1)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 1);
else if (messageHandler()->logLevel() > 1)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 2);
getDblParam(OsiObjOffset, objoffset);
getDblParam(OsiPrimalObjectiveLimit, primalobjlimit);
getDblParam(OsiDualObjectiveLimit, dualobjlimit);
if (getObjSense() == +1) {
if (primalobjlimit < COIN_DBL_MAX)
CPXsetdblparam(env, CPX_PARAM_OBJLLIM, primalobjlimit + objoffset);
if (dualobjlimit > -COIN_DBL_MAX)
CPXsetdblparam(env, CPX_PARAM_OBJULIM, dualobjlimit + objoffset);
}
else {
if (primalobjlimit > -COIN_DBL_MAX)
CPXsetdblparam(env, CPX_PARAM_OBJULIM, primalobjlimit + objoffset);
if (dualobjlimit < COIN_DBL_MAX)
CPXsetdblparam(env, CPX_PARAM_OBJLLIM, dualobjlimit + objoffset);
}
int status = CPXhybbaropt(env, lp, CPX_ALG_NONE);
if (status!=0) {
std::cerr << "Cplex did not return 0 status." << std::endl;
throw std::exception();
}
}
//-----------------------------------------------------------------------------
// resolve is same as initialSolve, no warm start capability.
void OsiCplexSolverInterface::resolve() {
//todo(aykut) I am not sure what switchToLp() does.
switchToLP();
CPXLPptr lp = getMutableLpPtr();
CPXENVptr env = getEnvironmentPtr();
if (messageHandler()->logLevel() == 0)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 0);
else if (messageHandler()->logLevel() == 1)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 1);
else if (messageHandler()->logLevel() > 1)
CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 2);
int status = CPXhybbaropt(env, lp, CPX_ALG_NONE);
if (status!=0) {
std::cerr << "Cplex did not return 0 status." << std::endl;
throw std::exception();
}
}
<|endoftext|> |
<commit_before>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file HydraulicOverCenterValve.hpp
//! @author Mikael Axin <mikael.axin@liu.se>
//! @date 2010-01-13
//!
//! @brief Contains a hydraulic over center valve with first order dynamics
//!
//$Id$
#ifndef HYDRAULICOVERCENTERVALVE_HPP_INCLUDED
#define HYDRAULICOVERCENTERVALVE_HPP_INCLUDED
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
namespace hopsan {
//!
//! @brief
//! @ingroup HydraulicComponents
//!
class HydraulicOverCenterValve : public ComponentQ
{
private:
// Member variables
TurbulentFlowFunction mTurb;
ValveHysteresis mHyst;
FirstOrderTransferFunction mFilterLP;
double mPrevX0, mCs, mCf;
// Port and node data pointers
Port *mpP1, *mpP2, *mpPControl;
double *mpP1_p, *mpP1_q, *mpP1_c, *mpP1_Zc, *mpP2_p, *mpP2_q, *mpP2_c, *mpP2_Zc,
*mpPControl_p, *mpPControl_c;
double *mpPref, *mpPh, *mpArat, *mpXv;
// Constants
double mTao, mKcs, mKcf, mPnom, mQnom;
public:
static Component *Creator()
{
return new HydraulicOverCenterValve();
}
void configure()
{
mpP1 = addPowerPort("P1", "NodeHydraulic");
mpP2 = addPowerPort("P2", "NodeHydraulic");
mpPControl = addPowerPort("P_CONTROL", "NodeHydraulic");
addInputVariable("p_ref", "Reference Opening Pressure", "Pa", 2000000, &mpPref);
addInputVariable("p_h", "Hysteresis Width", "Pa", 500000, &mpPh);
addInputVariable("a_ratio", "Area ratio", "-", 5.0, &mpArat);
addOutputVariable("xv", "Equivalent spool position", "", &mpXv);
addConstant("tao", "Time Constant of Spool", "s", 0.01, mTao);
addConstant("k_cs", "Steady State Characteristic due to Spring", "(m^3/s)/Pa", 0.00000001, mKcs);
addConstant("k_cf", "Steady State Characteristic due to Flow Forces", "(m^3/s)/Pa", 0.00000001, mKcf);
addConstant("q_nom", "Flow with Fully Open Valve and pressure drop p_nom", "m^3/s", 0.001, mQnom);
addConstant("p_nom", "Nominal pressure drop", "Pa", 7e6, mPnom);
}
void initialize()
{
mpP1_p = getSafeNodeDataPtr(mpP1, NodeHydraulic::Pressure);
mpP1_q = getSafeNodeDataPtr(mpP1, NodeHydraulic::Flow);
mpP1_c = getSafeNodeDataPtr(mpP1, NodeHydraulic::WaveVariable);
mpP1_Zc = getSafeNodeDataPtr(mpP1, NodeHydraulic::CharImpedance);
mpP2_p = getSafeNodeDataPtr(mpP2, NodeHydraulic::Pressure);
mpP2_q = getSafeNodeDataPtr(mpP2, NodeHydraulic::Flow);
mpP2_c = getSafeNodeDataPtr(mpP2, NodeHydraulic::WaveVariable);
mpP2_Zc = getSafeNodeDataPtr(mpP2, NodeHydraulic::CharImpedance);
mpPControl_p = getSafeNodeDataPtr(mpPControl, NodeHydraulic::Pressure);
mpPControl_c = getSafeNodeDataPtr(mpPControl, NodeHydraulic::WaveVariable);
mPrevX0 = 0.0;
mCs = sqrt(mPnom)/mKcs;
mCf = 1/(mKcf * sqrt(mPnom));
double x0max = mQnom/sqrt(mPnom);
double wCutoff = 1 / mTao;
double num[2] = {1.0, 0.0};
double den[2] = {1.0, 1.0/wCutoff};
mFilterLP.initialize(mTimestep, num, den, mPrevX0, mPrevX0, 0, x0max);
}
void simulateOneTimestep()
{
//Declare local variables
double p1, q1, c1, Zc1, p2, q2, c2, Zc2, p_control, c_control;
double b1, xs, xh, xsh, pref, ph, arat;
bool cav = false;
//Get variable values from nodes
p1 = (*mpP1_p);
q1 = (*mpP1_q);
c1 = (*mpP1_c);
Zc1 = (*mpP1_Zc);
p2 = (*mpP2_p);
q2 = (*mpP2_q);
c2 = (*mpP2_c);
Zc2 = (*mpP2_Zc);
p_control = (*mpPControl_p);
c_control = (*mpPControl_c);
pref = (*mpPref);
ph = (*mpPh);
arat = (*mpArat);
/* Equations */
b1 = mCs+mCf*(p1-p2); // Help Variable, equals sqrt(p1-p2)/Kctot
xs = (p1 / arat - pref + p_control) / b1; // Spool position calculation
xh = ph/b1;
xsh = mHyst.getValue(xs, xh, mPrevX0); // Hysteresis
double x0 = mFilterLP.update(xsh); // Dynamics
mTurb.setFlowCoefficient(x0); // Turbulent Flow Calculation
q2 = mTurb.getFlow(c1, c2, Zc1, Zc2);
q1 = -q2;
p1 = c1 + Zc1 * q1; // Pressure Calulation
p2 = c2 + Zc2 * q2;
p_control = c_control;
p_control = std::max(0.0, p_control);
if (p1 < 0.0) // Check for cavitation
{
c1 = 0.0;
Zc1 = 0.0;
cav = true;
}
if (p2 < 0.0)
{
c2 = 0.0;
Zc2 = 0.0;
cav = true;
}
if (cav) // Cavitatiaon, redo calculations with new c and Zc
{
q2 = mTurb.getFlow(c1, c2, Zc1, Zc2);
q1 = -q2;
p1 = c1 + Zc1 * q1;
p2 = c2 + Zc2 * q2;
if (p1 < 0.0) { p1 = 0.0; }
if (p2 < 0.0) { p2 = 0.0; }
}
mPrevX0 = x0;
(*mpP1_p) = p1; // Write new values to nodes
(*mpP1_q) = q1;
(*mpP2_p) = p2;
(*mpP2_q) = q2;
(*mpPControl_p) = p_control;
(*mpXv) = x0;
}
};
}
#endif // HYDRAULICPRESSURECONTROLLEDVALVE_HPP_INCLUDED
<commit_msg>Corrected area ratio parameter for over-center valve component. Resolves #1388.<commit_after>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file HydraulicOverCenterValve.hpp
//! @author Mikael Axin <mikael.axin@liu.se>
//! @date 2010-01-13
//!
//! @brief Contains a hydraulic over center valve with first order dynamics
//!
//$Id$
#ifndef HYDRAULICOVERCENTERVALVE_HPP_INCLUDED
#define HYDRAULICOVERCENTERVALVE_HPP_INCLUDED
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
namespace hopsan {
//!
//! @brief
//! @ingroup HydraulicComponents
//!
class HydraulicOverCenterValve : public ComponentQ
{
private:
// Member variables
TurbulentFlowFunction mTurb;
ValveHysteresis mHyst;
FirstOrderTransferFunction mFilterLP;
double mPrevX0, mCs, mCf;
// Port and node data pointers
Port *mpP1, *mpP2, *mpPControl;
double *mpP1_p, *mpP1_q, *mpP1_c, *mpP1_Zc, *mpP2_p, *mpP2_q, *mpP2_c, *mpP2_Zc,
*mpPControl_p, *mpPControl_c;
double *mpPref, *mpPh, *mpArat, *mpXv;
// Constants
double mTao, mKcs, mKcf, mPnom, mQnom;
public:
static Component *Creator()
{
return new HydraulicOverCenterValve();
}
void configure()
{
mpP1 = addPowerPort("P1", "NodeHydraulic");
mpP2 = addPowerPort("P2", "NodeHydraulic");
mpPControl = addPowerPort("P_CONTROL", "NodeHydraulic");
addInputVariable("p_ref", "Reference Opening Pressure", "Pa", 2000000, &mpPref);
addInputVariable("p_h", "Hysteresis Width", "Pa", 500000, &mpPh);
addInputVariable("a_ratio", "Area ratio", "-", 5.0, &mpArat);
addOutputVariable("xv", "Equivalent spool position", "", &mpXv);
addConstant("tao", "Time Constant of Spool", "s", 0.01, mTao);
addConstant("k_cs", "Steady State Characteristic due to Spring", "(m^3/s)/Pa", 0.00000001, mKcs);
addConstant("k_cf", "Steady State Characteristic due to Flow Forces", "(m^3/s)/Pa", 0.00000001, mKcf);
addConstant("q_nom", "Flow with Fully Open Valve and pressure drop p_nom", "m^3/s", 0.001, mQnom);
addConstant("p_nom", "Nominal pressure drop", "Pa", 7e6, mPnom);
}
void initialize()
{
mpP1_p = getSafeNodeDataPtr(mpP1, NodeHydraulic::Pressure);
mpP1_q = getSafeNodeDataPtr(mpP1, NodeHydraulic::Flow);
mpP1_c = getSafeNodeDataPtr(mpP1, NodeHydraulic::WaveVariable);
mpP1_Zc = getSafeNodeDataPtr(mpP1, NodeHydraulic::CharImpedance);
mpP2_p = getSafeNodeDataPtr(mpP2, NodeHydraulic::Pressure);
mpP2_q = getSafeNodeDataPtr(mpP2, NodeHydraulic::Flow);
mpP2_c = getSafeNodeDataPtr(mpP2, NodeHydraulic::WaveVariable);
mpP2_Zc = getSafeNodeDataPtr(mpP2, NodeHydraulic::CharImpedance);
mpPControl_p = getSafeNodeDataPtr(mpPControl, NodeHydraulic::Pressure);
mpPControl_c = getSafeNodeDataPtr(mpPControl, NodeHydraulic::WaveVariable);
mPrevX0 = 0.0;
mCs = sqrt(mPnom)/mKcs;
mCf = 1/(mKcf * sqrt(mPnom));
double x0max = mQnom/sqrt(mPnom);
double wCutoff = 1 / mTao;
double num[2] = {1.0, 0.0};
double den[2] = {1.0, 1.0/wCutoff};
mFilterLP.initialize(mTimestep, num, den, mPrevX0, mPrevX0, 0, x0max);
}
void simulateOneTimestep()
{
//Declare local variables
double p1, q1, c1, Zc1, p2, q2, c2, Zc2, p_control, c_control;
double b1, xs, xh, xsh, pref, ph, arat;
bool cav = false;
//Get variable values from nodes
p1 = (*mpP1_p);
q1 = (*mpP1_q);
c1 = (*mpP1_c);
Zc1 = (*mpP1_Zc);
p2 = (*mpP2_p);
q2 = (*mpP2_q);
c2 = (*mpP2_c);
Zc2 = (*mpP2_Zc);
p_control = (*mpPControl_p);
c_control = (*mpPControl_c);
pref = (*mpPref);
ph = (*mpPh);
arat = (*mpArat);
/* Equations */
b1 = mCs+mCf*(p1-p2); // Help Variable, equals sqrt(p1-p2)/Kctot
xs = (p1 - pref + arat * p_control) / b1; // Spool position calculation
xh = ph/b1;
xsh = mHyst.getValue(xs, xh, mPrevX0); // Hysteresis
double x0 = mFilterLP.update(xsh); // Dynamics
mTurb.setFlowCoefficient(x0); // Turbulent Flow Calculation
q2 = mTurb.getFlow(c1, c2, Zc1, Zc2);
q1 = -q2;
p1 = c1 + Zc1 * q1; // Pressure Calulation
p2 = c2 + Zc2 * q2;
p_control = c_control;
p_control = std::max(0.0, p_control);
if (p1 < 0.0) // Check for cavitation
{
c1 = 0.0;
Zc1 = 0.0;
cav = true;
}
if (p2 < 0.0)
{
c2 = 0.0;
Zc2 = 0.0;
cav = true;
}
if (cav) // Cavitatiaon, redo calculations with new c and Zc
{
q2 = mTurb.getFlow(c1, c2, Zc1, Zc2);
q1 = -q2;
p1 = c1 + Zc1 * q1;
p2 = c2 + Zc2 * q2;
if (p1 < 0.0) { p1 = 0.0; }
if (p2 < 0.0) { p2 = 0.0; }
}
mPrevX0 = x0;
(*mpP1_p) = p1; // Write new values to nodes
(*mpP1_q) = q1;
(*mpP2_p) = p2;
(*mpP2_q) = q2;
(*mpPControl_p) = p_control;
(*mpXv) = x0;
}
};
}
#endif // HYDRAULICPRESSURECONTROLLEDVALVE_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/
#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkKnownDriverIds.inl"
using namespace vk;
namespace vkt
{
namespace api
{
namespace
{
enum TestType
{
TEST_TYPE_DRIVER_ID_MATCH = 0,
TEST_TYPE_NAME_IS_NOT_EMPTY,
TEST_TYPE_NAME_ZERO_TERMINATED,
TEST_TYPE_INFO_ZERO_TERMINATED,
TEST_TYPE_VERSION,
};
static const VkConformanceVersionKHR knownConformanceVersions[] =
{
makeConformanceVersion(1, 2, 7, 0),
makeConformanceVersion(1, 2, 6, 2),
makeConformanceVersion(1, 2, 6, 1),
makeConformanceVersion(1, 2, 6, 0),
makeConformanceVersion(1, 2, 5, 2),
makeConformanceVersion(1, 2, 5, 1),
makeConformanceVersion(1, 2, 5, 0),
makeConformanceVersion(1, 2, 4, 1),
makeConformanceVersion(1, 2, 4, 0),
makeConformanceVersion(1, 2, 3, 3),
makeConformanceVersion(1, 2, 3, 2),
makeConformanceVersion(1, 2, 3, 1),
makeConformanceVersion(1, 2, 3, 0),
makeConformanceVersion(1, 2, 2, 2),
makeConformanceVersion(1, 2, 2, 1),
makeConformanceVersion(1, 2, 2, 0),
makeConformanceVersion(1, 2, 1, 2),
makeConformanceVersion(1, 2, 1, 1),
makeConformanceVersion(1, 2, 1, 0),
makeConformanceVersion(1, 2, 0, 2),
makeConformanceVersion(1, 2, 0, 1),
makeConformanceVersion(1, 2, 0, 0),
makeConformanceVersion(1, 1, 6, 3),
makeConformanceVersion(1, 1, 6, 2),
makeConformanceVersion(1, 1, 6, 1),
makeConformanceVersion(1, 1, 6, 0),
makeConformanceVersion(1, 1, 5, 2),
makeConformanceVersion(1, 1, 5, 1),
makeConformanceVersion(1, 1, 5, 0),
makeConformanceVersion(1, 1, 4, 3),
makeConformanceVersion(1, 1, 4, 2),
makeConformanceVersion(1, 1, 4, 1),
makeConformanceVersion(1, 1, 4, 0),
makeConformanceVersion(1, 1, 3, 3),
makeConformanceVersion(1, 1, 3, 2),
makeConformanceVersion(1, 1, 3, 1),
makeConformanceVersion(1, 1, 3, 0),
};
DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
return deStrnlen(str, maxSize) < maxSize;
}
DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)
{
return ((a.major == b.major) &&
(a.minor == b.minor) &&
(a.subminor == b.subminor) &&
(a.patch == b.patch));
}
void checkSupport (Context& context, const TestType config)
{
DE_UNREF(config);
context.requireDeviceFunctionality("VK_KHR_driver_properties");
}
void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
for (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++)
{
if (deviceDriverProperties.driverID == driverIds[driverNdx].id)
return;
}
TCU_FAIL("Driver ID did not match any known driver");
}
void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (deviceDriverProperties.driverName[0] == 0)
TCU_FAIL("Driver name is empty");
}
void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
TCU_FAIL("Driver name is not a null-terminated string");
}
void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
TCU_FAIL("Driver info is not a null-terminated string");
}
void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)
{
const deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion);
const deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion);
if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||
(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&
deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))
{
TCU_FAIL("Wrong driver conformance version (older than used API version)");
}
for (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions;
pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
++pConformanceVersion)
{
if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
return;
}
TCU_FAIL("Wrong driver conformance version (not known)");
}
tcu::TestStatus testQueryProperties (Context& context, const TestType testType)
{
// Query the driver properties
const VkPhysicalDevice physDevice = context.getPhysicalDevice();
const int memsetPattern = 0xaa;
VkPhysicalDeviceProperties2 deviceProperties2;
VkPhysicalDeviceDriverProperties deviceDriverProperties;
deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
deviceDriverProperties.pNext = DE_NULL;
deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
deviceProperties2.pNext = &deviceDriverProperties;
context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);
// Verify the returned values
switch (testType)
{
case TEST_TYPE_DRIVER_ID_MATCH: testDriverMatch (deviceDriverProperties); break;
case TEST_TYPE_NAME_IS_NOT_EMPTY: testNameIsNotEmpty (deviceDriverProperties); break;
case TEST_TYPE_NAME_ZERO_TERMINATED: testNameZeroTerminated (deviceDriverProperties); break;
case TEST_TYPE_INFO_ZERO_TERMINATED: testInfoZeroTerminated (deviceDriverProperties); break;
case TEST_TYPE_VERSION: testVersion (deviceDriverProperties, context.getUsedApiVersion()); break;
default: TCU_THROW(InternalError, "Unknown test type specified");
}
return tcu::TestStatus::pass("Pass");
}
void createTestCases (tcu::TestCaseGroup* group)
{
addFunctionCase(group, "driver_id_match", "Check driverID is supported", checkSupport, testQueryProperties, TEST_TYPE_DRIVER_ID_MATCH);
addFunctionCase(group, "name_is_not_empty", "Check name field is not empty", checkSupport, testQueryProperties, TEST_TYPE_NAME_IS_NOT_EMPTY);
addFunctionCase(group, "name_zero_terminated", "Check name field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_NAME_ZERO_TERMINATED);
addFunctionCase(group, "info_zero_terminated", "Check info field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_INFO_ZERO_TERMINATED);
addFunctionCase(group, "conformance_version", "Check conformanceVersion reported by driver", checkSupport, testQueryProperties, TEST_TYPE_VERSION);
}
} // anonymous
tcu::TestCaseGroup* createDriverPropertiesTests(tcu::TestContext& testCtx)
{
return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}
} // api
} // vkt
<commit_msg>Allow Vulkan CTS 1.2.7.1<commit_after>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/
#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkKnownDriverIds.inl"
using namespace vk;
namespace vkt
{
namespace api
{
namespace
{
enum TestType
{
TEST_TYPE_DRIVER_ID_MATCH = 0,
TEST_TYPE_NAME_IS_NOT_EMPTY,
TEST_TYPE_NAME_ZERO_TERMINATED,
TEST_TYPE_INFO_ZERO_TERMINATED,
TEST_TYPE_VERSION,
};
static const VkConformanceVersionKHR knownConformanceVersions[] =
{
makeConformanceVersion(1, 2, 7, 1),
makeConformanceVersion(1, 2, 7, 0),
makeConformanceVersion(1, 2, 6, 2),
makeConformanceVersion(1, 2, 6, 1),
makeConformanceVersion(1, 2, 6, 0),
makeConformanceVersion(1, 2, 5, 2),
makeConformanceVersion(1, 2, 5, 1),
makeConformanceVersion(1, 2, 5, 0),
makeConformanceVersion(1, 2, 4, 1),
makeConformanceVersion(1, 2, 4, 0),
makeConformanceVersion(1, 2, 3, 3),
makeConformanceVersion(1, 2, 3, 2),
makeConformanceVersion(1, 2, 3, 1),
makeConformanceVersion(1, 2, 3, 0),
makeConformanceVersion(1, 2, 2, 2),
makeConformanceVersion(1, 2, 2, 1),
makeConformanceVersion(1, 2, 2, 0),
makeConformanceVersion(1, 2, 1, 2),
makeConformanceVersion(1, 2, 1, 1),
makeConformanceVersion(1, 2, 1, 0),
makeConformanceVersion(1, 2, 0, 2),
makeConformanceVersion(1, 2, 0, 1),
makeConformanceVersion(1, 2, 0, 0),
makeConformanceVersion(1, 1, 6, 3),
makeConformanceVersion(1, 1, 6, 2),
makeConformanceVersion(1, 1, 6, 1),
makeConformanceVersion(1, 1, 6, 0),
makeConformanceVersion(1, 1, 5, 2),
makeConformanceVersion(1, 1, 5, 1),
makeConformanceVersion(1, 1, 5, 0),
makeConformanceVersion(1, 1, 4, 3),
makeConformanceVersion(1, 1, 4, 2),
makeConformanceVersion(1, 1, 4, 1),
makeConformanceVersion(1, 1, 4, 0),
makeConformanceVersion(1, 1, 3, 3),
makeConformanceVersion(1, 1, 3, 2),
makeConformanceVersion(1, 1, 3, 1),
makeConformanceVersion(1, 1, 3, 0),
};
DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
return deStrnlen(str, maxSize) < maxSize;
}
DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)
{
return ((a.major == b.major) &&
(a.minor == b.minor) &&
(a.subminor == b.subminor) &&
(a.patch == b.patch));
}
void checkSupport (Context& context, const TestType config)
{
DE_UNREF(config);
context.requireDeviceFunctionality("VK_KHR_driver_properties");
}
void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
for (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++)
{
if (deviceDriverProperties.driverID == driverIds[driverNdx].id)
return;
}
TCU_FAIL("Driver ID did not match any known driver");
}
void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (deviceDriverProperties.driverName[0] == 0)
TCU_FAIL("Driver name is empty");
}
void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
TCU_FAIL("Driver name is not a null-terminated string");
}
void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
TCU_FAIL("Driver info is not a null-terminated string");
}
void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)
{
const deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion);
const deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion);
if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||
(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&
deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))
{
TCU_FAIL("Wrong driver conformance version (older than used API version)");
}
for (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions;
pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
++pConformanceVersion)
{
if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
return;
}
TCU_FAIL("Wrong driver conformance version (not known)");
}
tcu::TestStatus testQueryProperties (Context& context, const TestType testType)
{
// Query the driver properties
const VkPhysicalDevice physDevice = context.getPhysicalDevice();
const int memsetPattern = 0xaa;
VkPhysicalDeviceProperties2 deviceProperties2;
VkPhysicalDeviceDriverProperties deviceDriverProperties;
deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
deviceDriverProperties.pNext = DE_NULL;
deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
deviceProperties2.pNext = &deviceDriverProperties;
context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);
// Verify the returned values
switch (testType)
{
case TEST_TYPE_DRIVER_ID_MATCH: testDriverMatch (deviceDriverProperties); break;
case TEST_TYPE_NAME_IS_NOT_EMPTY: testNameIsNotEmpty (deviceDriverProperties); break;
case TEST_TYPE_NAME_ZERO_TERMINATED: testNameZeroTerminated (deviceDriverProperties); break;
case TEST_TYPE_INFO_ZERO_TERMINATED: testInfoZeroTerminated (deviceDriverProperties); break;
case TEST_TYPE_VERSION: testVersion (deviceDriverProperties, context.getUsedApiVersion()); break;
default: TCU_THROW(InternalError, "Unknown test type specified");
}
return tcu::TestStatus::pass("Pass");
}
void createTestCases (tcu::TestCaseGroup* group)
{
addFunctionCase(group, "driver_id_match", "Check driverID is supported", checkSupport, testQueryProperties, TEST_TYPE_DRIVER_ID_MATCH);
addFunctionCase(group, "name_is_not_empty", "Check name field is not empty", checkSupport, testQueryProperties, TEST_TYPE_NAME_IS_NOT_EMPTY);
addFunctionCase(group, "name_zero_terminated", "Check name field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_NAME_ZERO_TERMINATED);
addFunctionCase(group, "info_zero_terminated", "Check info field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_INFO_ZERO_TERMINATED);
addFunctionCase(group, "conformance_version", "Check conformanceVersion reported by driver", checkSupport, testQueryProperties, TEST_TYPE_VERSION);
}
} // anonymous
tcu::TestCaseGroup* createDriverPropertiesTests(tcu::TestContext& testCtx)
{
return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}
} // api
} // vkt
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
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 FLUSSPFERD_XML_MISC_NODES_HPP
#define FLUSSPFERD_XML_MISC_NODES_HPP
#include "node.hpp"
namespace xml_plugin {
FLUSSPFERD_CLASS_DESCRIPTION(
notation,
(base, node)
(constructible, false)
(full_name, "xml.Notation")
(constructor_name, "Notation")
/*(properties,
("publicId", getter, getPublicId)
("systemId", getter, getSystemId)
)*/
)
{
public:
typedef arabica_notation wrapped_type;
notation(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
: base_type(proto,node, map),
impl_(node)
{ }
// Property getters/setters
//string_type getPublicId() { return impl_.getPublicId(); }
//string_type getSystemId() { return impl_.getSystemId(); }
// Methods
protected:
wrapped_type impl_;
};
FLUSSPFERD_CLASS_DESCRIPTION(
entity,
(base, node)
(constructible, false)
(full_name, "xml.Entity")
(constructor_name, "Entity")
(properties,
//("publicId", getter, getPublicId)
//("systemId", getter, getSystemId)
//("notationName", getter, getNotationName)
)
)
{
public:
typedef arabica_entity wrapped_type;
entity(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
: base_type(proto,node, map),
impl_(node)
{ }
// Property getters/setters
//string_type getPublicId() { return impl_.getPublicId(); }
//string_type getSystemId() { return impl_.getSystemId(); }
//string_type getNotationName() { return impl_.getNotationName(); }
// Methods
protected:
wrapped_type impl_;
};
FLUSSPFERD_CLASS_DESCRIPTION(
entity_ref,
(base, node)
(constructible, false)
(full_name, "xml.EntityReference")
(constructor_name, "EntityReference")
)
{
public:
typedef arabica_entity_ref wrapped_type;
entity_ref(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
: base_type(proto,node, map)
{ }
// No methods or properties on this class
};
FLUSSPFERD_CLASS_DESCRIPTION(
processing_instruction,
(base, node)
(constructible, false)
(full_name, "xml.ProcessingInstruction")
(constructor_name, "ProcessingInstruction")
(properties,
("target", getter, getTarget)
("data", getter_setter, (getData, setData))
)
)
{
public:
typedef arabica_pi wrapped_type;
processing_instruction(flusspferd::object const &proto,
wrapped_type const &node, weak_node_map map)
: base_type(proto,node, map),
impl_(node)
{ }
// Property getters/setters
string_type getTarget() { return impl_.getTarget(); }
string_type getData() { return impl_.getData(); }
void setData(string_type s) { impl_.setData(s); }
// Methods
protected:
wrapped_type impl_;
};
} // namespace xml_plugin
#endif
<commit_msg>xml_arabica: fixed issue with empty properties.<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
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 FLUSSPFERD_XML_MISC_NODES_HPP
#define FLUSSPFERD_XML_MISC_NODES_HPP
#include "node.hpp"
namespace xml_plugin {
FLUSSPFERD_CLASS_DESCRIPTION(
notation,
(base, node)
(constructible, false)
(full_name, "xml.Notation")
(constructor_name, "Notation")
/*(properties,
("publicId", getter, getPublicId)
("systemId", getter, getSystemId)
)*/
)
{
public:
typedef arabica_notation wrapped_type;
notation(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
: base_type(proto,node, map),
impl_(node)
{ }
// Property getters/setters
//string_type getPublicId() { return impl_.getPublicId(); }
//string_type getSystemId() { return impl_.getSystemId(); }
// Methods
protected:
wrapped_type impl_;
};
FLUSSPFERD_CLASS_DESCRIPTION(
entity,
(base, node)
(constructible, false)
(full_name, "xml.Entity")
(constructor_name, "Entity")
/*
(properties,
//("publicId", getter, getPublicId)
//("systemId", getter, getSystemId)
//("notationName", getter, getNotationName)
)
*/
)
{
public:
typedef arabica_entity wrapped_type;
entity(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
: base_type(proto,node, map),
impl_(node)
{ }
// Property getters/setters
//string_type getPublicId() { return impl_.getPublicId(); }
//string_type getSystemId() { return impl_.getSystemId(); }
//string_type getNotationName() { return impl_.getNotationName(); }
// Methods
protected:
wrapped_type impl_;
};
FLUSSPFERD_CLASS_DESCRIPTION(
entity_ref,
(base, node)
(constructible, false)
(full_name, "xml.EntityReference")
(constructor_name, "EntityReference")
)
{
public:
typedef arabica_entity_ref wrapped_type;
entity_ref(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
: base_type(proto,node, map)
{ }
// No methods or properties on this class
};
FLUSSPFERD_CLASS_DESCRIPTION(
processing_instruction,
(base, node)
(constructible, false)
(full_name, "xml.ProcessingInstruction")
(constructor_name, "ProcessingInstruction")
(properties,
("target", getter, getTarget)
("data", getter_setter, (getData, setData))
)
)
{
public:
typedef arabica_pi wrapped_type;
processing_instruction(flusspferd::object const &proto,
wrapped_type const &node, weak_node_map map)
: base_type(proto,node, map),
impl_(node)
{ }
// Property getters/setters
string_type getTarget() { return impl_.getTarget(); }
string_type getData() { return impl_.getData(); }
void setData(string_type s) { impl_.setData(s); }
// Methods
protected:
wrapped_type impl_;
};
} // namespace xml_plugin
#endif
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// FunctionDef.cpp
// Executable function definitions
//
// File is under the MIT license; see LICENSE for details
//------------------------------------------------------------------------------
#include "slang/codegen/FunctionDef.h"
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include "slang/codegen/CodeGenerator.h"
#include "slang/mir/Instr.h"
namespace slang {
using namespace mir;
FunctionDef::FunctionDef(const CodeGenerator& codegen, string_view name, llvm::Type* returnType,
span<const ParamDef> params) :
returnType(returnType),
name(name), params(params) {
SmallVectorSized<llvm::Type*, 8> types;
for (auto& param : params)
types.append(param.nativeType);
if (!returnType)
returnType = llvm::Type::getVoidTy(codegen.getContext());
auto funcType =
llvm::FunctionType::get(returnType, llvm::ArrayRef<llvm::Type*>(types.begin(), types.end()),
/* isVarArg */ false);
nativeFunc =
llvm::Function::Create(funcType, llvm::Function::ExternalLinkage,
llvm::StringRef(name.data(), name.length()), codegen.getModule());
}
FunctionDef FunctionDef::getSystemFunc(CodeGenerator& codegen, SysCallKind kind) {
auto& ctx = codegen.getContext();
auto voidType = llvm::Type::getVoidTy(ctx);
auto boolType = llvm::Type::getInt1Ty(ctx);
auto int8Type = llvm::Type::getInt8Ty(ctx);
auto int32Type = llvm::Type::getInt32Ty(ctx);
SmallVectorSized<ParamDef, 8> params;
switch (kind) {
case SysCallKind::printChar:
params.append({ int8Type });
break;
case SysCallKind::printInt:
params.append({ codegen.getGenericIntPtrType() });
params.append({ int8Type });
params.append({ int32Type });
params.append({ boolType });
break;
default:
THROW_UNREACHABLE;
}
return FunctionDef(codegen, toString(kind), voidType, params.copy(codegen));
}
} // namespace slang<commit_msg>Remove obsolete FunctionDef.cpp file<commit_after><|endoftext|> |
<commit_before>//
// PROJECT: Aspia
// FILE: console/about_dialog.cc
// LICENSE: GNU General Public License 3
// PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)
//
#include "console/about_dialog.h"
#include <QAbstractButton>
#include <QDesktopServices>
#include "version.h"
namespace aspia {
namespace {
const char kGplLink[] = "https://www.gnu.org/licenses/gpl.html";
const char kGplTranslationLink[] = "http://www.gnu.org/licenses/translations.html";
const char kHomeLink[] = "https://aspia.org";
const char kGitHubLink[] = "https://github.com/dchapyshev/aspia";
const char kDonateLink[] = "https://aspia.org/donate";
const char* kDevelopers[] = { "Dmitry Chapyshev (dmitry@aspia.ru)" };
const char* kTranslators[] =
{
"Dmitry Chapyshev (Russian)",
"Mark Jansen (Dutch)"
};
const char* kThirdParty[] =
{
"Qt Framework © 2015 The Qt Company Ltd., GNU General Public License 3.0",
"libvpx © 2010, The WebM Project authors, BSD 3-Clause License",
"libyuv © 2011 The LibYuv Project Authors, BSD 3-Clause License",
"libsodium © 2013-2017 Frank Denis, ISC License",
"protobuf © 2014 Google Inc., BSD 3-Clause License",
"zlib-ng © 1995-2013 Jean-loup Gailly and Mark Adler, Zlib License",
"FatCow Icons © 2009-2014 FatCow Web Hosting, Creative Commons Attribution 3.0 License",
"Fugue Icons © 2013 Yusuke Kamiyamane, Creative Commons Attribution 3.0 License"
};
QString createList(const QString& title, const char* array[], size_t array_size)
{
if (!array_size)
return QString();
QString list;
for (size_t i = 0; i < array_size; ++i)
{
list.append(QString("• %1").arg(array[i]));
if (i + 1 != array_size)
list.append(QLatin1String("<br/>"));
}
return QString("<b>%1</b><br>%2").arg(title).arg(list);
}
} // namespace
AboutDialog::AboutDialog(QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
ui.label_version->setText(tr("Version: %1").arg(QLatin1String(ASPIA_VERSION_STRING)));
QString license =
QString("%1<br>%2<br><a href='%3'>%3</a>")
.arg(tr("Aspia is free software released under GNU General Public License 3."))
.arg(tr("You can get a copy of license here:"))
.arg(kGplLink);
QString license_translation =
QString("%1<br><a href='%2'>%2</a>")
.arg(tr("You can also get a translation of GNU GPL license here:"))
.arg(kGplTranslationLink);
QString links =
QString("<b>%1</b><br>%2 <a href='%3'>%3</a><br>%4 <a href='%5'>%5</a>")
.arg(tr("Links:"))
.arg(tr("Home page:")).arg(kHomeLink)
.arg(tr("GitHub page:")).arg(kGitHubLink);
QString developers =
createList(tr("Developers:"), kDevelopers, _countof(kDevelopers));
QString translators =
createList(tr("Translators:"), kTranslators, _countof(kTranslators));
QString third_party =
createList(tr("Third-party components:"), kThirdParty, _countof(kThirdParty));
QString html;
html += "<html><body>";
html += "<p>" + license + "</p>";
html += "<p>" + license_translation + "</p>";
html += "<p>" + links + "</p>";
html += "<p>" + developers + "</p>";
html += "<p>" + translators + "</p>";
html += "<p>" + third_party + "</p>";
html += "</body><html>";
ui.text_edit->setHtml(html);
connect(ui.push_button_donate, &QPushButton::pressed, [this]()
{
QDesktopServices::openUrl(QUrl(kDonateLink));
});
connect(ui.push_button_close, &QPushButton::pressed, this, &AboutDialog::close);
}
AboutDialog::~AboutDialog() = default;
} // namespace aspia
<commit_msg>- https instead http.<commit_after>//
// PROJECT: Aspia
// FILE: console/about_dialog.cc
// LICENSE: GNU General Public License 3
// PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)
//
#include "console/about_dialog.h"
#include <QAbstractButton>
#include <QDesktopServices>
#include "version.h"
namespace aspia {
namespace {
const char kGplLink[] = "https://www.gnu.org/licenses/gpl.html";
const char kGplTranslationLink[] = "https://www.gnu.org/licenses/translations.html";
const char kHomeLink[] = "https://aspia.org";
const char kGitHubLink[] = "https://github.com/dchapyshev/aspia";
const char kDonateLink[] = "https://aspia.org/donate";
const char* kDevelopers[] = { "Dmitry Chapyshev (dmitry@aspia.ru)" };
const char* kTranslators[] =
{
"Dmitry Chapyshev (Russian)",
"Mark Jansen (Dutch)"
};
const char* kThirdParty[] =
{
"Qt Framework © 2015 The Qt Company Ltd., GNU General Public License 3.0",
"libvpx © 2010, The WebM Project authors, BSD 3-Clause License",
"libyuv © 2011 The LibYuv Project Authors, BSD 3-Clause License",
"libsodium © 2013-2017 Frank Denis, ISC License",
"protobuf © 2014 Google Inc., BSD 3-Clause License",
"zlib-ng © 1995-2013 Jean-loup Gailly and Mark Adler, Zlib License",
"FatCow Icons © 2009-2014 FatCow Web Hosting, Creative Commons Attribution 3.0 License",
"Fugue Icons © 2013 Yusuke Kamiyamane, Creative Commons Attribution 3.0 License"
};
QString createList(const QString& title, const char* array[], size_t array_size)
{
if (!array_size)
return QString();
QString list;
for (size_t i = 0; i < array_size; ++i)
{
list.append(QString("• %1").arg(array[i]));
if (i + 1 != array_size)
list.append(QLatin1String("<br/>"));
}
return QString("<b>%1</b><br>%2").arg(title).arg(list);
}
} // namespace
AboutDialog::AboutDialog(QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
ui.label_version->setText(tr("Version: %1").arg(QLatin1String(ASPIA_VERSION_STRING)));
QString license =
QString("%1<br>%2<br><a href='%3'>%3</a>")
.arg(tr("Aspia is free software released under GNU General Public License 3."))
.arg(tr("You can get a copy of license here:"))
.arg(kGplLink);
QString license_translation =
QString("%1<br><a href='%2'>%2</a>")
.arg(tr("You can also get a translation of GNU GPL license here:"))
.arg(kGplTranslationLink);
QString links =
QString("<b>%1</b><br>%2 <a href='%3'>%3</a><br>%4 <a href='%5'>%5</a>")
.arg(tr("Links:"))
.arg(tr("Home page:")).arg(kHomeLink)
.arg(tr("GitHub page:")).arg(kGitHubLink);
QString developers =
createList(tr("Developers:"), kDevelopers, _countof(kDevelopers));
QString translators =
createList(tr("Translators:"), kTranslators, _countof(kTranslators));
QString third_party =
createList(tr("Third-party components:"), kThirdParty, _countof(kThirdParty));
QString html;
html += "<html><body>";
html += "<p>" + license + "</p>";
html += "<p>" + license_translation + "</p>";
html += "<p>" + links + "</p>";
html += "<p>" + developers + "</p>";
html += "<p>" + translators + "</p>";
html += "<p>" + third_party + "</p>";
html += "</body><html>";
ui.text_edit->setHtml(html);
connect(ui.push_button_donate, &QPushButton::pressed, [this]()
{
QDesktopServices::openUrl(QUrl(kDonateLink));
});
connect(ui.push_button_close, &QPushButton::pressed, this, &AboutDialog::close);
}
AboutDialog::~AboutDialog() = default;
} // namespace aspia
<|endoftext|> |
<commit_before>// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "registryhelpers.h"
#include "dxsubfilter_uuids.h"
#include "dxsubfilter.h"
//------------------------------------------------------------------------------
// Global filter information for proper DirectShow registration
AMOVIESETUP_MEDIATYPE sudVideoMediaTypes[] = {
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AYUV },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_YUY2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_YV12 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_NV12 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_P210 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_P216 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_P010 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_P016 },
};
AMOVIESETUP_MEDIATYPE sudSubtitleMediaTypes[] = {
{ &MEDIATYPE_Text, &MEDIASUBTYPE_None },
{ &MEDIATYPE_Subtitle, &MEDIASUBTYPE_UTF8 },
{ &MEDIATYPE_Subtitle, &MEDIASUBTYPE_SSA },
{ &MEDIATYPE_Subtitle, &MEDIASUBTYPE_ASS },
{ &MEDIATYPE_Subtitle, &MEDIASUBTYPE_VOBSUB },
};
AMOVIESETUP_PIN sudOutputPin = {
L"", // Obsolete, not used.
FALSE, // Is this pin rendered?
TRUE, // Is it an output pin?
FALSE, // Can the filter create zero instances?
FALSE, // Does the filter create multiple instances?
&GUID_NULL, // Obsolete.
NULL, // Obsolete.
ARRAYSIZE(sudVideoMediaTypes), // Number of media types.
sudVideoMediaTypes // Pointer to media types.
};
AMOVIESETUP_PIN sudInputVideoPin = {
L"", // Obsolete, not used.
FALSE, // Is this pin rendered?
FALSE, // Is it an output pin?
FALSE, // Can the filter create zero instances?
FALSE, // Does the filter create multiple instances?
&GUID_NULL, // Obsolete.
NULL, // Obsolete.
ARRAYSIZE(sudVideoMediaTypes), // Number of media types.
sudVideoMediaTypes // Pointer to media types.
};
AMOVIESETUP_PIN sudInputSubtitlePin = {
L"", // Obsolete, not used.
FALSE, // Is this pin rendered?
FALSE, // Is it an output pin?
FALSE, // Can the filter create zero instances?
FALSE, // Does the filter create multiple instances?
&GUID_NULL, // Obsolete.
NULL, // Obsolete.
ARRAYSIZE(sudSubtitleMediaTypes), // Number of media types.
sudSubtitleMediaTypes // Pointer to media types.
};
AMOVIESETUP_PIN sudDXSubFilterPins[] = {
sudInputVideoPin,
sudInputSubtitlePin,
sudOutputPin,
};
AMOVIESETUP_FILTER sudDXSubFilterReg = {
&CLSID_DXSubFilter, // Filter CLSID.
L"DXSubFilter", // Filter name.
MERIT_NORMAL, // Merit.
ARRAYSIZE(sudDXSubFilterPins), // Number of pin types.
sudDXSubFilterPins // Pointer to pin information.
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/* List of class IDs and creator functions for the class factory. This
provides the link between the OLE entry point in the DLL and an object
being created. The class factory will call the static CreateInstance
function when it is asked to create a CLSID_DXSubFilter object */
CFactoryTemplate g_Templates[1] = {
{
L"CDXSubFilter", // Name
&CLSID_DXSubFilter, // CLSID
DXSubFilter::CDXSubFilter::CreateInstance, // Creation function
NULL, // Initialization function (optional)
&sudDXSubFilterReg // Pointer to filter information
}
};
int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DLL Entry Point for normal DLLs.
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// The following functions are actually defined in BaseClasses, but we need to give their
// function signature here so we can call them correctly.
extern "C" void __cdecl __security_init_cookie(void);
extern "C" BOOL WINAPI _DllEntryPoint(HINSTANCE, ULONG, __inout_opt LPVOID);
// DLL Entry Point for DirectShow filters.
DECLSPEC_NOINLINE
BOOL
WINAPI
DllEntryPoint(
HINSTANCE hInstance,
ULONG ulReason,
__inout_opt LPVOID pv
)
{
if ( ulReason == DLL_PROCESS_ATTACH ) {
// Must happen before any other code is executed. Thankfully - it's re-entrant
__security_init_cookie();
}
return _DllEntryPoint(hInstance, ulReason, pv);
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// To be self registering, OLE servers must export functions named
// DllRegisterServer and DllUnregisterServer. These are the functions that are
// called when RegSrv32.exe is run.
STDAPI DllRegisterServer()
{
DXSubFilter::WriteFilterConfigurationDataToRegistry();
return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
DXSubFilter::RemoveFilterConfigurationDataFromRegistry();
return AMovieDllRegisterServer2(FALSE);
}
<commit_msg>Fixed filter not registering correctly. Fucking undocumented Microsoft behaviour.<commit_after>// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "registryhelpers.h"
#include "dxsubfilter_uuids.h"
#include "dxsubfilter.h"
//------------------------------------------------------------------------------
// Global filter information for proper DirectShow registration
AMOVIESETUP_MEDIATYPE sudVideoMediaTypes[] = {
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AYUV },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_YUY2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_YV12 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_NV12 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_P210 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_P216 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_P010 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_P016 },
};
AMOVIESETUP_MEDIATYPE sudSubtitleMediaTypes[] = {
{ &MEDIATYPE_Text, &MEDIASUBTYPE_None },
{ &MEDIATYPE_Subtitle, &MEDIASUBTYPE_UTF8 },
{ &MEDIATYPE_Subtitle, &MEDIASUBTYPE_SSA },
{ &MEDIATYPE_Subtitle, &MEDIASUBTYPE_ASS },
{ &MEDIATYPE_Subtitle, &MEDIASUBTYPE_VOBSUB },
};
AMOVIESETUP_PIN sudOutputPin = {
L"", // Obsolete, not used.
FALSE, // Is this pin rendered?
TRUE, // Is it an output pin?
FALSE, // Can the filter create zero instances?
FALSE, // Does the filter create multiple instances?
&GUID_NULL, // Obsolete.
NULL, // Obsolete.
ARRAYSIZE(sudVideoMediaTypes), // Number of media types.
sudVideoMediaTypes // Pointer to media types.
};
AMOVIESETUP_PIN sudInputVideoPin = {
L"", // Obsolete, not used.
FALSE, // Is this pin rendered?
FALSE, // Is it an output pin?
FALSE, // Can the filter create zero instances?
FALSE, // Does the filter create multiple instances?
&GUID_NULL, // Obsolete.
NULL, // Obsolete.
ARRAYSIZE(sudVideoMediaTypes), // Number of media types.
sudVideoMediaTypes // Pointer to media types.
};
AMOVIESETUP_PIN sudInputSubtitlePin = {
L"", // Obsolete, not used.
FALSE, // Is this pin rendered?
FALSE, // Is it an output pin?
FALSE, // Can the filter create zero instances?
FALSE, // Does the filter create multiple instances?
&GUID_NULL, // Obsolete.
NULL, // Obsolete.
ARRAYSIZE(sudSubtitleMediaTypes), // Number of media types.
sudSubtitleMediaTypes // Pointer to media types.
};
AMOVIESETUP_PIN sudDXSubFilterPins[] = {
sudInputVideoPin,
sudInputSubtitlePin,
sudOutputPin,
};
AMOVIESETUP_FILTER sudDXSubFilterReg = {
&CLSID_DXSubFilter, // Filter CLSID.
L"DXSubFilter", // Filter name.
MERIT_NORMAL, // Merit.
ARRAYSIZE(sudDXSubFilterPins), // Number of pin types.
sudDXSubFilterPins // Pointer to pin information.
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/* List of class IDs and creator functions for the class factory. This
provides the link between the OLE entry point in the DLL and an object
being created. The class factory will call the static CreateInstance
function when it is asked to create a CLSID_DXSubFilter object */
CFactoryTemplate g_Templates[1] = {
{
L"CDXSubFilter", // Name
&CLSID_DXSubFilter, // CLSID
DXSubFilter::CDXSubFilter::CreateInstance, // Creation function
NULL, // Initialization function (optional)
&sudDXSubFilterReg // Pointer to filter information
}
};
int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// The following functions are actually defined in BaseClasses, but we need to give their
// function signature here so we can call them correctly.
extern "C" void __cdecl __security_init_cookie(void);
extern "C" BOOL WINAPI _DllEntryPoint(HINSTANCE, ULONG, __inout_opt LPVOID);
// DLL Entry Point for DirectShow filters.
DECLSPEC_NOINLINE
BOOL
WINAPI
DllEntryPoint(
HINSTANCE hInstance,
ULONG ulReason,
__inout_opt LPVOID pv
)
{
if ( ulReason == DLL_PROCESS_ATTACH ) {
// Must happen before any other code is executed. Thankfully - it's re-entrant
__security_init_cookie();
}
return _DllEntryPoint(hInstance, ulReason, pv);
}
// DLL Entry Point for normal DLLs.
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
// Microsoft DirectShow fail: DllMain is actually called by RegSvr32, but we need to run
// DllEntryPoint to run the proper DirectShow specific stuff. Consequently, we need to
// manually call DllEntryPoint ourselves. This solves the problem of our filter registering
// incorrectly as RegSvr32.exe instead of itself.
return DllEntryPoint(reinterpret_cast<HINSTANCE>(hModule), ul_reason_for_call, lpReserved);
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// To be self registering, OLE servers must export functions named
// DllRegisterServer and DllUnregisterServer. These are the functions that are
// called when RegSrv32.exe is run.
STDAPI DllRegisterServer()
{
DXSubFilter::WriteFilterConfigurationDataToRegistry();
return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
DXSubFilter::RemoveFilterConfigurationDataFromRegistry();
return AMovieDllRegisterServer2(FALSE);
}
<|endoftext|> |
<commit_before>#include "gateway.h"
#include "type.pb.h"
#include <boost/thread/locks.hpp>
#include <ctime>
#include <iostream>
#include <google/protobuf/descriptor.h>
#include "interface.h"
#include <curlpp/Exception.hpp>
#include <log4cplus/logger.h>
Worker::Worker(Pool &){
register_api("/query", boost::bind(&Worker::handle, this, _1, _2), "traite les requétes");
register_api("/load", boost::bind(&Worker::load, this, _1, _2), "traite les requétes");
register_api("/register", boost::bind(&Worker::register_navitia, this, _1, _2), "ajout d'un NAViTiA au pool");
register_api("/status", boost::bind(&Worker::status, this, _1, _2), "status");
register_api("/unregister", boost::bind(&Worker::unregister_navitia, this, _1, _2), "suppression d'un NAViTiA du pool");
}
webservice::ResponseData Worker::status(webservice::RequestData& request, Pool& pool){
webservice::ResponseData rd;
Context context;
render_status(request, rd, context, pool);
return rd;
}
webservice::ResponseData Worker::register_navitia(webservice::RequestData& request, Pool& pool){
webservice::ResponseData rd;
int thread = 8;
if(request.params.find("url") == request.params.end()){
rd.status_code = 500;
return rd;
}
auto it = request.params.find("thread");
if(it != request.params.end()){
thread = atoi(it->second.c_str());
}
//TODO valider l'url
pool.add_navitia(new Navitia(request.params["url"], thread));
return status(request, pool);
}
webservice::ResponseData Worker::unregister_navitia(webservice::RequestData& request, Pool& pool){
webservice::ResponseData rd;
if(request.params.find("url") == request.params.end()){
rd.status_code = 500;
return rd;
}
//TODO valider l'url
pool.remove_navitia(Navitia(request.params["url"], 8));
return status(request, pool);
}
webservice::ResponseData Worker::handle(webservice::RequestData& request, Pool& pool){
pool.check_desactivated_navitia();
webservice::ResponseData rd;
Context context;
dispatcher(request, rd, pool, context);
render(request, rd, context);
return rd;
}
webservice::ResponseData Worker::load(webservice::RequestData& request, Pool& pool){
//TODO gestion de la desactivation
BOOST_FOREACH(Navitia* nav, pool.navitia_list){
nav->load();
}
return this->status(request, pool);
}
void Dispatcher::operator()(webservice::RequestData& request, webservice::ResponseData& response, Pool& pool, Context& context){
std::pair<int, std::string> res;
int nb_try = 0;
bool ok = true;
do{
ok = true;
nb_try++;
Navitia* nav = pool.next();
try{
res = nav->query(request.path.substr(request.path.find_last_of('/')) + "?" + request.raw_params);
pool.release_navitia(nav);
}catch(long& code){
ok = false;
nav->on_error();
log4cplus::Logger logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("logger"));
LOG4CPLUS_WARN(logger, "la requétes a échouer");
pool.release_navitia(nav);
response.status_code = code;
continue;
}
std::unique_ptr<pbnavitia::PTRefResponse> resp(new pbnavitia::PTRefResponse());
if(resp->ParseFromString(res.second)){
context.pb = std::move(resp);
context.service = Context::PTREF;
}else{
ok = false;
nav->on_error();
log4cplus::Logger logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("logger"));
LOG4CPLUS_WARN(logger, "erreur de chargement du protobuf");
context.str = res.second;
context.service = Context::BAD_RESPONSE;
response.status_code = res.first;
}
}while(!ok && nb_try < 4);
}
MAKE_WEBSERVICE(Pool, Worker)
<commit_msg>gestion des erreurs de ptref<commit_after>#include "gateway.h"
#include "type.pb.h"
#include <boost/thread/locks.hpp>
#include <ctime>
#include <iostream>
#include <google/protobuf/descriptor.h>
#include "interface.h"
#include <curlpp/Exception.hpp>
#include <log4cplus/logger.h>
Worker::Worker(Pool &){
register_api("/query", boost::bind(&Worker::handle, this, _1, _2), "traite les requétes");
register_api("/load", boost::bind(&Worker::load, this, _1, _2), "traite les requétes");
register_api("/register", boost::bind(&Worker::register_navitia, this, _1, _2), "ajout d'un NAViTiA au pool");
register_api("/status", boost::bind(&Worker::status, this, _1, _2), "status");
register_api("/unregister", boost::bind(&Worker::unregister_navitia, this, _1, _2), "suppression d'un NAViTiA du pool");
}
webservice::ResponseData Worker::status(webservice::RequestData& request, Pool& pool){
webservice::ResponseData rd;
Context context;
render_status(request, rd, context, pool);
return rd;
}
webservice::ResponseData Worker::register_navitia(webservice::RequestData& request, Pool& pool){
webservice::ResponseData rd;
int thread = 8;
if(request.params.find("url") == request.params.end()){
rd.status_code = 500;
return rd;
}
auto it = request.params.find("thread");
if(it != request.params.end()){
thread = atoi(it->second.c_str());
}
//TODO valider l'url
pool.add_navitia(new Navitia(request.params["url"], thread));
return status(request, pool);
}
webservice::ResponseData Worker::unregister_navitia(webservice::RequestData& request, Pool& pool){
webservice::ResponseData rd;
if(request.params.find("url") == request.params.end()){
rd.status_code = 500;
return rd;
}
//TODO valider l'url
pool.remove_navitia(Navitia(request.params["url"], 8));
return status(request, pool);
}
webservice::ResponseData Worker::handle(webservice::RequestData& request, Pool& pool){
pool.check_desactivated_navitia();
webservice::ResponseData rd;
Context context;
dispatcher(request, rd, pool, context);
render(request, rd, context);
return rd;
}
webservice::ResponseData Worker::load(webservice::RequestData& request, Pool& pool){
//TODO gestion de la desactivation
BOOST_FOREACH(Navitia* nav, pool.navitia_list){
nav->load();
}
return this->status(request, pool);
}
void Dispatcher::operator()(webservice::RequestData& request, webservice::ResponseData& response, Pool& pool, Context& context){
std::pair<int, std::string> res;
int nb_try = 0;
bool ok = true;
do{
ok = true;
nb_try++;
Navitia* nav = pool.next();
try{
res = nav->query(request.path.substr(request.path.find_last_of('/')) + "?" + request.raw_params);
pool.release_navitia(nav);
}catch(long& code){
ok = false;
nav->on_error();
log4cplus::Logger logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("logger"));
LOG4CPLUS_WARN(logger, "la requétes a échouer");
pool.release_navitia(nav);
response.status_code = code;
continue;
}
std::unique_ptr<pbnavitia::PTRefResponse> resp(new pbnavitia::PTRefResponse());
if(resp->ParseFromString(res.second)){
if(resp->has_error()){
ok = false;
nav->on_error();
context.str = resp->error();
context.service = Context::BAD_RESPONSE;
continue;
}
context.pb = std::move(resp);
context.service = Context::PTREF;
}else{
ok = false;
nav->on_error();
log4cplus::Logger logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("logger"));
LOG4CPLUS_WARN(logger, "erreur de chargement du protobuf");
context.str = res.second;
context.service = Context::BAD_RESPONSE;
response.status_code = res.first;
}
}while(!ok && nb_try < 4);
}
MAKE_WEBSERVICE(Pool, Worker)
<|endoftext|> |
<commit_before>/***************************************************************************//**
* FILE : block_array.hpp
*
* Implements an array container allocated in blocks.
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is cmgui.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#if !defined (BLOCK_ARRAY_HPP)
#define BLOCK_ARRAY_HPP
#include "general/debug.h"
template <typename IndexType, typename EntryType, int blockLength = 256 >
class block_array
{
private:
// Note: any new attributes must be handled by swap()
EntryType **blocks;
IndexType blockCount;
EntryType* getOrCreateBlock(IndexType blockIndex)
{
if (blockIndex >= blockCount)
{
IndexType newBlockCount = blockIndex + 1;
if (newBlockCount < blockCount*2)
{
newBlockCount = blockCount*2;
}
EntryType **newBlocks;
if (!REALLOCATE(newBlocks, blocks, EntryType *, newBlockCount))
return NULL;
for (IndexType i = blockCount; i < newBlockCount; i++)
{
newBlocks[i] = NULL;
}
blocks = newBlocks;
blockCount = newBlockCount;
}
EntryType *block = blocks[blockIndex];
if (!block)
{
if (ALLOCATE(block, EntryType, blockLength))
{
for (IndexType i = 0; i < blockLength; i++)
{
block[i] = 0; // only works for numeric or pointer types
}
blocks[blockIndex] = block;
}
}
return block;
}
public:
block_array() :
blocks(NULL),
blockCount(0)
{
}
~block_array()
{
clear();
}
void clear()
{
for (IndexType i = 0; i < blockCount; i++)
{
if (blocks[i])
{
DEALLOCATE(blocks[i]);
}
}
if (blocks)
{
DEALLOCATE(blocks);
}
blockCount = 0;
}
/** Swaps all data with other block_array. Cannot fail. */
void swap(block_array& other)
{
EntryType **temp_blocks = blocks;
IndexType temp_blockCount = blockCount;
blocks = other.blocks;
blockCount = other.blockCount;
other.blocks = temp_blocks;
other.blockCount = temp_blockCount;
}
/**
* Get a value from the block_array.
* @param index The index of the value to retrieve, starting at 0.
* @param value On success, filled with value held at index.
* @return 1 if value returned, 0 if no value at index.
*/
int getValue(IndexType index, EntryType& value) const
{
IndexType blockIndex = index / blockLength;
if (blockIndex < blockCount)
{
EntryType *block = blocks[blockIndex];
if (block)
{
IndexType entryIndex = index % blockLength;
value = block[entryIndex];
return 1;
}
}
return 0;
}
/**
* Set a value in the block_array.
* @param index The index of the value to set, starting at 0.
* @param value Value to set at index.
* @return 1 if value set, 0 if failed.
*/
int setValue(IndexType index, EntryType value)
{
IndexType blockIndex = index / blockLength;
EntryType* block = getOrCreateBlock(blockIndex);
if (!block)
return 0;
IndexType entryIndex = index % blockLength;
block[entryIndex] = value;
return 1;
}
bool setValues(IndexType minIndex, IndexType maxIndex, EntryType value)
{
// GRC: can be made faster
for (IndexType index = minIndex; index <= maxIndex; index++)
{
if (!setValue(index, value))
return false;
}
return true;
}
};
/** stores boolean values as individual bits, with no value equivalent to false */
template <typename IndexType, int intBlockLength = 32>
class bool_array : private block_array<IndexType, unsigned int, intBlockLength>
{
public:
void clear()
{
block_array<IndexType, unsigned int, intBlockLength>::clear();
}
void swap(bool_array& other)
{
block_array<IndexType, unsigned int, intBlockLength>::swap(other);
}
/** @param oldValue Returns old value so client can determine if status changed */
int setBool(IndexType index, bool value, bool& oldValue)
{
IndexType intIndex = index >> 5;
unsigned int intValue = 0;
int hasValue = getValue(intIndex, intValue);
if (hasValue || value)
{
unsigned int mask = (1 << (index & 0x1F));
oldValue = (0 != (intValue & mask));
if (oldValue != value)
{
return setValue(intIndex, intValue ^ mask);
}
}
else
{
oldValue = false;
}
return 1;
}
bool getBool(IndexType index) const
{
IndexType intIndex = index >> 5;
unsigned int intValue = 0;
if (getValue(intIndex, intValue))
{
unsigned int mask = (1 << (index & 0x1F));
return (0 != (intValue & mask));
}
return false;
}
/**
* @param lastTrueIndex Updated to equal or next lower index with true value.
* @return true if found, false if none.
*/
bool updateLastTrueIndex(IndexType& lastTrueIndex)
{
// GRC this can be made much more efficient
while (!getBool(lastTrueIndex))
{
--lastTrueIndex;
if (lastTrueIndex < 0)
return false;
}
return true;
}
/** @return true if values for all indexes in range are true; false otherwise */
bool isRangeTrue(IndexType minIndex, IndexType maxIndex)
{
if (minIndex > maxIndex)
return false;
// GRC this can be made much more efficient
IndexType index = minIndex;
while (getBool(index))
{
if (index == maxIndex)
return true;
index++;
}
return false;
}
/** Sets all entries from index 0..indexCount-1 to true.
* @return true if completely successful, false otherwise */
bool setAllTrue(IndexType indexCount)
{
IndexType intIndexCount = indexCount >> 5;
// bulk set the flags in lots of 32 bits
if (!setValues(0, intIndexCount-1, 0xFFFFFFFF))
return false;
// individually set remaining bits
for (IndexType index = intIndexCount*32; index < indexCount; index++)
{
bool oldValue;
if (!setBool(index, true, oldValue))
return false;
}
return true;
}
};
#endif /* !defined (BLOCK_ARRAY_HPP) */
<commit_msg>Compilation fixes for gcc 4.7.1.<commit_after>/***************************************************************************//**
* FILE : block_array.hpp
*
* Implements an array container allocated in blocks.
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is cmgui.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#if !defined (BLOCK_ARRAY_HPP)
#define BLOCK_ARRAY_HPP
#include "general/debug.h"
template <typename IndexType, typename EntryType, int blockLength = 256 >
class block_array
{
private:
// Note: any new attributes must be handled by swap()
EntryType **blocks;
IndexType blockCount;
EntryType* getOrCreateBlock(IndexType blockIndex)
{
if (blockIndex >= blockCount)
{
IndexType newBlockCount = blockIndex + 1;
if (newBlockCount < blockCount*2)
{
newBlockCount = blockCount*2;
}
EntryType **newBlocks;
if (!REALLOCATE(newBlocks, blocks, EntryType *, newBlockCount))
return NULL;
for (IndexType i = blockCount; i < newBlockCount; i++)
{
newBlocks[i] = NULL;
}
blocks = newBlocks;
blockCount = newBlockCount;
}
EntryType *block = blocks[blockIndex];
if (!block)
{
if (ALLOCATE(block, EntryType, blockLength))
{
for (IndexType i = 0; i < blockLength; i++)
{
block[i] = 0; // only works for numeric or pointer types
}
blocks[blockIndex] = block;
}
}
return block;
}
public:
block_array() :
blocks(NULL),
blockCount(0)
{
}
~block_array()
{
clear();
}
void clear()
{
for (IndexType i = 0; i < blockCount; i++)
{
if (blocks[i])
{
DEALLOCATE(blocks[i]);
}
}
if (blocks)
{
DEALLOCATE(blocks);
}
blockCount = 0;
}
/** Swaps all data with other block_array. Cannot fail. */
void swap(block_array& other)
{
EntryType **temp_blocks = blocks;
IndexType temp_blockCount = blockCount;
blocks = other.blocks;
blockCount = other.blockCount;
other.blocks = temp_blocks;
other.blockCount = temp_blockCount;
}
/**
* Get a value from the block_array.
* @param index The index of the value to retrieve, starting at 0.
* @param value On success, filled with value held at index.
* @return 1 if value returned, 0 if no value at index.
*/
int getValue(IndexType index, EntryType& value) const
{
IndexType blockIndex = index / blockLength;
if (blockIndex < blockCount)
{
EntryType *block = blocks[blockIndex];
if (block)
{
IndexType entryIndex = index % blockLength;
value = block[entryIndex];
return 1;
}
}
return 0;
}
/**
* Set a value in the block_array.
* @param index The index of the value to set, starting at 0.
* @param value Value to set at index.
* @return 1 if value set, 0 if failed.
*/
int setValue(IndexType index, EntryType value)
{
IndexType blockIndex = index / blockLength;
EntryType* block = getOrCreateBlock(blockIndex);
if (!block)
return 0;
IndexType entryIndex = index % blockLength;
block[entryIndex] = value;
return 1;
}
bool setValues(IndexType minIndex, IndexType maxIndex, EntryType value)
{
// GRC: can be made faster
for (IndexType index = minIndex; index <= maxIndex; index++)
{
if (!setValue(index, value))
return false;
}
return true;
}
};
/** stores boolean values as individual bits, with no value equivalent to false */
template <typename IndexType, int intBlockLength = 32>
class bool_array : private block_array<IndexType, unsigned int, intBlockLength>
{
public:
void clear()
{
block_array<IndexType, unsigned int, intBlockLength>::clear();
}
void swap(bool_array& other)
{
block_array<IndexType, unsigned int, intBlockLength>::swap(other);
}
using block_array<IndexType, unsigned int, intBlockLength>::getValue;
using block_array<IndexType, unsigned int, intBlockLength>::setValue;
using block_array<IndexType, unsigned int, intBlockLength>::setValues;
/** @param oldValue Returns old value so client can determine if status changed */
int setBool(IndexType index, bool value, bool& oldValue)
{
IndexType intIndex = index >> 5;
unsigned int intValue = 0;
int hasValue = getValue(intIndex, intValue);
if (hasValue || value)
{
unsigned int mask = (1 << (index & 0x1F));
oldValue = (0 != (intValue & mask));
if (oldValue != value)
{
return setValue(intIndex, intValue ^ mask);
}
}
else
{
oldValue = false;
}
return 1;
}
bool getBool(IndexType index) const
{
IndexType intIndex = index >> 5;
unsigned int intValue = 0;
if (getValue(intIndex, intValue))
{
unsigned int mask = (1 << (index & 0x1F));
return (0 != (intValue & mask));
}
return false;
}
/**
* @param lastTrueIndex Updated to equal or next lower index with true value.
* @return true if found, false if none.
*/
bool updateLastTrueIndex(IndexType& lastTrueIndex)
{
// GRC this can be made much more efficient
while (!getBool(lastTrueIndex))
{
--lastTrueIndex;
if (lastTrueIndex < 0)
return false;
}
return true;
}
/** @return true if values for all indexes in range are true; false otherwise */
bool isRangeTrue(IndexType minIndex, IndexType maxIndex)
{
if (minIndex > maxIndex)
return false;
// GRC this can be made much more efficient
IndexType index = minIndex;
while (getBool(index))
{
if (index == maxIndex)
return true;
index++;
}
return false;
}
/** Sets all entries from index 0..indexCount-1 to true.
* @return true if completely successful, false otherwise */
bool setAllTrue(IndexType indexCount)
{
IndexType intIndexCount = indexCount >> 5;
// bulk set the flags in lots of 32 bits
if (!setValues(0, intIndexCount-1, 0xFFFFFFFF))
return false;
// individually set remaining bits
for (IndexType index = intIndexCount*32; index < indexCount; index++)
{
bool oldValue;
if (!setBool(index, true, oldValue))
return false;
}
return true;
}
};
#endif /* !defined (BLOCK_ARRAY_HPP) */
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Aldebaran
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <iostream>
#include <kdl_parser/kdl_parser.hpp>
#include <kdl/tree.hpp>
#include <tf/transform_datatypes.h>
#include <robot_state_publisher/robot_state_publisher.h>
#include "joint_state.hpp"
namespace alros
{
namespace publisher
{
JointStatePublisher::JointStatePublisher( const std::string& name, const std::string& topic, float frequency, qi::SessionPtr& session ):
BasePublisher( name, topic, frequency, session ),
p_motion_( session->service("ALMotion") )
{}
void JointStatePublisher::publish()
{
// get joint state values
std::vector<float> al_joint_angles = p_motion_.call<std::vector<float> >("getAngles", "JointActuators", true );
msg_joint_states_.header.stamp = ros::Time::now();
// STUPID CONVERTION FROM FLOAT TO DOUBLE ARRAY --> OPTIMIZE THAT!
msg_joint_states_.position = std::vector<double>( al_joint_angles.begin(), al_joint_angles.end() );
pub_joint_states_.publish( msg_joint_states_ );
// Leg might be an artificial joint in between all wheels of pepper
std::vector<float> al_odometry_data = p_motion_.call<std::vector<float> >( "getRobotPosition", true );
msg_nav_odom_.header.stamp = ros::Time::now();
msg_tf_odom_.header.stamp = ros::Time::now();
const float& odomX = al_odometry_data[0];
const float& odomY = al_odometry_data[1];
const float& odomTheta = al_odometry_data[2];
// we can improve this with a velocity computation as well
// with this we simply set the velocity as the diff between (odomX - msg_odom_.pose.pose.position.x)/dt
msg_nav_odom_.pose.pose.position.x = odomX;
msg_nav_odom_.pose.pose.position.y = odomY;
msg_nav_odom_.pose.pose.position.z = 0;
msg_nav_odom_.pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw( 0, 0, odomTheta );
// fill in velocity components here
pub_odom_.publish(msg_nav_odom_);
// put joint states in tf broadcaster
std::map< std::string, double > joint_state_map;
// stupid version --> change this with std::transform c++11 ??!
std::transform( msg_joint_states_.name.begin(), msg_joint_states_.name.end(), msg_joint_states_.position.begin(), std::inserter( joint_state_map, joint_state_map.end() ), std::make_pair<std::string, double>);
static const std::string& jt_tf_prefix = "";
rspPtr_->publishTransforms( joint_state_map, msg_joint_states_.header.stamp, jt_tf_prefix );
rspPtr_->publishFixedTransforms( jt_tf_prefix );
//const geometry_msgs::Point& p = msg_nav_odom_.pose.pose.position;
//const geometry_msgs::Quaternion& q = msg_nav_odom_.pose.pose.orientation;
//msg_tf_odom_.transform.translation.x = odomX;
//msg_tf_odom_.transform.translation.y = odomY;
//msg_tf_odom_.transform.translation.z = 0;
//msg_tf_odom_.transform.rotation = msg_nav_odom_.pose.pose.orientation;
// DEBUG
static tf::Transform transform;
transform.setOrigin( tf::Vector3(odomX, odomY, 0) );
tf::Quaternion q;
q.setRPY(0, 0, odomTheta);
transform.setRotation(q);
tf_br_.sendTransform( tf::StampedTransform(transform, msg_tf_odom_.header.stamp, "base_footprint", "odom" ) );
//tf_br_.sendTransform( msg_tf_odom_ );
}
void JointStatePublisher::reset( ros::NodeHandle& nh )
{
pub_joint_states_ = nh.advertise<sensor_msgs::JointState>( topic_, 10 );
pub_odom_ = nh.advertise<nav_msgs::Odometry>( "/odom", 10 );
// load urdf from param server (alternatively from file)
if ( nh.hasParam("/robot_description") )
{
KDL::Tree tree;
std::string robot_desc;
nh.getParam("/robot_description", robot_desc);
kdl_parser::treeFromString( robot_desc, tree );
rspPtr_.reset( new robot_state_publisher::RobotStatePublisher(tree) );
}
else{
std::cerr << "failed to load robot description in joint_state_publisher" << std::endl;
is_initialized_ = false;
return;
}
// pre-fill joint states message
msg_joint_states_.name = p_motion_.call<std::vector<std::string> >("getBodyNames", "JointActuators" );
// pre-fill odometry message
msg_nav_odom_.header.frame_id = "odom";
msg_nav_odom_.child_frame_id = "base_footprint";
msg_tf_odom_.header.frame_id = "odom";
msg_tf_odom_.child_frame_id = "base_footprint";
is_initialized_ = true;
}
bool JointStatePublisher::isSubscribed() const
{
// assume JS and TF as essential, so publish always
return true;
}
} //publisher
} // alros
<commit_msg>correct odometry frame<commit_after>/*
* Copyright 2015 Aldebaran
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <iostream>
#include <kdl_parser/kdl_parser.hpp>
#include <kdl/tree.hpp>
#include <tf/transform_datatypes.h>
#include <robot_state_publisher/robot_state_publisher.h>
#include "joint_state.hpp"
namespace alros
{
namespace publisher
{
JointStatePublisher::JointStatePublisher( const std::string& name, const std::string& topic, float frequency, qi::SessionPtr& session ):
BasePublisher( name, topic, frequency, session ),
p_motion_( session->service("ALMotion") )
{}
void JointStatePublisher::publish()
{
// get joint state values
std::vector<float> al_joint_angles = p_motion_.call<std::vector<float> >("getAngles", "Body", true );
// Leg might be an artificial joint in between all wheels of pepper
std::vector<float> al_odometry_data = p_motion_.call<std::vector<float> >( "getPosition", "Torso", 1, true );
const ros::Time& stamp = ros::Time::now();
const float& odomX = al_odometry_data[0];
const float& odomY = al_odometry_data[1];
const float& odomZ = al_odometry_data[2];
const float& odomWX = al_odometry_data[3];
const float& odomWY = al_odometry_data[4];
const float& odomWZ = al_odometry_data[5];
//since all odometry is 6DOF we'll need a quaternion created from yaw
geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromRollPitchYaw( odomWX, odomWY, odomWZ );
/**
* JOINT STATE PUBLISHER
*/
msg_joint_states_.header.stamp = stamp;
// STUPID CONVERTION FROM FLOAT TO DOUBLE ARRAY --> OPTIMIZE THAT!
msg_joint_states_.position = std::vector<double>( al_joint_angles.begin(), al_joint_angles.end() );
pub_joint_states_.publish( msg_joint_states_ );
/**
* ROBOT STATE PUBLISHER
*/
// put joint states in tf broadcaster
std::map< std::string, double > joint_state_map;
// stupid version --> change this with std::transform c++11 ??!
std::transform( msg_joint_states_.name.begin(), msg_joint_states_.name.end(), msg_joint_states_.position.begin(), std::inserter( joint_state_map, joint_state_map.end() ), std::make_pair<std::string, double>);
static const std::string& jt_tf_prefix = "";
rspPtr_->publishTransforms( joint_state_map, stamp, jt_tf_prefix );
rspPtr_->publishFixedTransforms( jt_tf_prefix );
/**
* ODOMETRY FRAME
*/
msg_tf_odom_.header.stamp = stamp+ros::Duration(0.5);
msg_tf_odom_.transform.translation.x = odomX;
msg_tf_odom_.transform.translation.y = odomY;
msg_tf_odom_.transform.translation.z = odomZ;
msg_tf_odom_.transform.rotation = odom_quat;
tf_br_.sendTransform( msg_tf_odom_ );
/**
* ODOMETRY MESSAGE
*/
// we can improve this with a velocity computation as well
// with this we simply set the velocity as the diff between (odomX - msg_odom_.pose.pose.position.x)/dt
// msg_nav_odom_.header.stamp = msg_tf_odom_.header.stamp;
//
// msg_nav_odom_.pose.pose.position.x = odomX;
// msg_nav_odom_.pose.pose.position.y = odomY;
// msg_nav_odom_.pose.pose.position.z = 0;
// msg_nav_odom_.pose.pose.orientation = odom_quat;
// // fill in velocity components here
// pub_odom_.publish(msg_nav_odom_);
}
void JointStatePublisher::reset( ros::NodeHandle& nh )
{
pub_joint_states_ = nh.advertise<sensor_msgs::JointState>( topic_, 10 );
pub_odom_ = nh.advertise<nav_msgs::Odometry>( "/odom", 10 );
// load urdf from param server (alternatively from file)
if ( nh.hasParam("/robot_description") )
{
KDL::Tree tree;
std::string robot_desc;
nh.getParam("/robot_description", robot_desc);
kdl_parser::treeFromString( robot_desc, tree );
rspPtr_.reset( new robot_state_publisher::RobotStatePublisher(tree) );
}
else{
std::cerr << "failed to load robot description in joint_state_publisher" << std::endl;
is_initialized_ = false;
return;
}
// pre-fill joint states message
msg_joint_states_.name = p_motion_.call<std::vector<std::string> >("getBodyNames", "Body" );
msg_tf_odom_.header.frame_id = "odom";
msg_tf_odom_.child_frame_id = "base_link";
// pre-fill odometry message
msg_nav_odom_.header.frame_id = "odom";
msg_nav_odom_.child_frame_id = "base_footprint";
is_initialized_ = true;
}
bool JointStatePublisher::isSubscribed() const
{
// assume JS and TF as essential, so publish always
return true;
}
} //publisher
} // alros
<|endoftext|> |
<commit_before>/* Copyright (c) 2018 PaddlePaddle 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 <glog/logging.h>
#include <gtest/gtest.h>
#include "gflags/gflags.h"
#include "paddle/fluid/inference/tests/api/trt_test_helper.h"
namespace paddle {
namespace inference {
void run(const AnalysisConfig& config, std::vector<float>* out_data) {
auto predictor = CreatePaddlePredictor(config);
auto input_names = predictor->GetInputNames();
int run_batch = 1;
const int run_seq_len = 128;
std::vector<int64_t> tmp_input;
std::vector<float> tmp_four_input;
tmp_input.reserve(run_batch * run_seq_len);
tmp_four_input.reserve(run_batch * run_seq_len);
int64_t i0[run_seq_len] = {
1, 3558, 4, 75, 491, 89, 340, 313, 93, 4, 255, 10, 75, 321,
4095, 1902, 4, 134, 49, 75, 311, 14, 44, 178, 543, 15, 12043, 2,
75, 201, 340, 9, 14, 44, 486, 218, 1140, 279, 12043, 2};
int64_t i1[run_seq_len] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int64_t i2[run_seq_len] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
float i3[run_seq_len] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
// first input
auto input_t = predictor->GetInputTensor(input_names[0]);
input_t->Reshape({run_batch, run_seq_len, 1});
input_t->copy_from_cpu(i0);
// second input
auto input_t2 = predictor->GetInputTensor(input_names[1]);
input_t2->Reshape({run_batch, run_seq_len, 1});
input_t2->copy_from_cpu(i1);
// third input.
auto input_t3 = predictor->GetInputTensor(input_names[2]);
input_t3->Reshape({run_batch, run_seq_len, 1});
input_t3->copy_from_cpu(i2);
auto input_t4 = predictor->GetInputTensor(input_names[3]);
input_t4->Reshape({run_batch, run_seq_len, 1});
input_t4->copy_from_cpu(i3);
ASSERT_TRUE(predictor->ZeroCopyRun());
auto output_names = predictor->GetOutputNames();
auto output_t = predictor->GetOutputTensor(output_names[0]);
std::vector<int> output_shape = output_t->shape();
int out_num = std::accumulate(output_shape.begin(), output_shape.end(), 1,
std::multiplies<int>());
out_data->resize(out_num);
output_t->copy_to_cpu(out_data->data());
}
void trt_ernie(bool with_fp16, std::vector<float> result) {
AnalysisConfig config;
std::string model_dir = FLAGS_infer_model;
SetConfig(&config, model_dir, true);
config.SwitchUseFeedFetchOps(false);
int batch = 32;
int min_seq_len = 1;
int max_seq_len = 128;
int opt_seq_len = 128;
std::vector<int> min_shape = {1, min_seq_len, 1};
std::vector<int> max_shape = {batch, max_seq_len, 1};
std::vector<int> opt_shape = {batch, opt_seq_len, 1};
// Set the input's min, max, opt shape
std::map<std::string, std::vector<int>> min_input_shape = {
{"read_file_0.tmp_0", min_shape},
{"read_file_0.tmp_1", min_shape},
{"read_file_0.tmp_2", min_shape},
{"read_file_0.tmp_3", min_shape}};
std::map<std::string, std::vector<int>> max_input_shape = {
{"read_file_0.tmp_0", max_shape},
{"read_file_0.tmp_1", max_shape},
{"read_file_0.tmp_2", max_shape},
{"read_file_0.tmp_3", max_shape}};
std::map<std::string, std::vector<int>> opt_input_shape = {
{"read_file_0.tmp_0", opt_shape},
{"read_file_0.tmp_1", opt_shape},
{"read_file_0.tmp_2", opt_shape},
{"read_file_0.tmp_3", opt_shape}};
auto precision = AnalysisConfig::Precision::kFloat32;
if (with_fp16) {
precision = AnalysisConfig::Precision::kHalf;
}
config.EnableTensorRtEngine(1 << 30, 1, 12, precision, false, false);
config.SetTRTDynamicShapeInfo(min_input_shape, max_input_shape,
opt_input_shape);
std::vector<float> out_data;
run(config, &out_data);
for (size_t i = 0; i < out_data.size(); i++) {
EXPECT_NEAR(result[i], out_data[i], 2e-3);
}
}
TEST(AnalysisPredictor, no_fp16) {
std::vector<float> result = {0.498667, 0.501333};
trt_ernie(false, result);
}
} // namespace inference
} // namespace paddle
<commit_msg>Fix wrong inputs (#39700)<commit_after>/* Copyright (c) 2018 PaddlePaddle 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 <glog/logging.h>
#include <gtest/gtest.h>
#include "gflags/gflags.h"
#include "paddle/fluid/inference/tests/api/trt_test_helper.h"
namespace paddle {
namespace inference {
void run(const AnalysisConfig& config, std::vector<float>* out_data) {
auto predictor = CreatePaddlePredictor(config);
auto input_names = predictor->GetInputNames();
int run_batch = 1;
const int run_seq_len = 128;
std::vector<int64_t> tmp_input;
std::vector<float> tmp_four_input;
tmp_input.reserve(run_batch * run_seq_len);
tmp_four_input.reserve(run_batch * run_seq_len);
int64_t i0[run_seq_len] = {
1, 3558, 4, 75, 491, 89, 340, 313, 93, 4, 255, 10, 75, 321,
4095, 1902, 4, 134, 49, 75, 311, 14, 44, 178, 543, 15, 12043, 2,
75, 201, 340, 9, 14, 44, 486, 218, 1140, 279, 12043, 2};
int64_t i1[run_seq_len] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
int64_t i2[run_seq_len] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
float i3[run_seq_len] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
// first input
auto input_t = predictor->GetInputTensor(input_names[0]);
input_t->Reshape({run_batch, run_seq_len, 1});
input_t->copy_from_cpu(i0);
// second input
auto input_t2 = predictor->GetInputTensor(input_names[1]);
input_t2->Reshape({run_batch, run_seq_len, 1});
input_t2->copy_from_cpu(i1);
// third input.
auto input_t3 = predictor->GetInputTensor(input_names[2]);
input_t3->Reshape({run_batch, run_seq_len, 1});
input_t3->copy_from_cpu(i2);
auto input_t4 = predictor->GetInputTensor(input_names[3]);
input_t4->Reshape({run_batch, run_seq_len, 1});
input_t4->copy_from_cpu(i3);
ASSERT_TRUE(predictor->ZeroCopyRun());
auto output_names = predictor->GetOutputNames();
auto output_t = predictor->GetOutputTensor(output_names[0]);
std::vector<int> output_shape = output_t->shape();
int out_num = std::accumulate(output_shape.begin(), output_shape.end(), 1,
std::multiplies<int>());
out_data->resize(out_num);
output_t->copy_to_cpu(out_data->data());
}
void trt_ernie(bool with_fp16, std::vector<float> result) {
AnalysisConfig config;
std::string model_dir = FLAGS_infer_model;
SetConfig(&config, model_dir, true);
config.SwitchUseFeedFetchOps(false);
int batch = 32;
int min_seq_len = 1;
int max_seq_len = 128;
int opt_seq_len = 128;
std::vector<int> min_shape = {1, min_seq_len, 1};
std::vector<int> max_shape = {batch, max_seq_len, 1};
std::vector<int> opt_shape = {batch, opt_seq_len, 1};
// Set the input's min, max, opt shape
std::map<std::string, std::vector<int>> min_input_shape = {
{"read_file_0.tmp_0", min_shape},
{"read_file_0.tmp_1", min_shape},
{"read_file_0.tmp_2", min_shape},
{"read_file_0.tmp_3", min_shape}};
std::map<std::string, std::vector<int>> max_input_shape = {
{"read_file_0.tmp_0", max_shape},
{"read_file_0.tmp_1", max_shape},
{"read_file_0.tmp_2", max_shape},
{"read_file_0.tmp_3", max_shape}};
std::map<std::string, std::vector<int>> opt_input_shape = {
{"read_file_0.tmp_0", opt_shape},
{"read_file_0.tmp_1", opt_shape},
{"read_file_0.tmp_2", opt_shape},
{"read_file_0.tmp_3", opt_shape}};
auto precision = AnalysisConfig::Precision::kFloat32;
if (with_fp16) {
precision = AnalysisConfig::Precision::kHalf;
}
config.EnableTensorRtEngine(1 << 30, 1, 12, precision, false, false);
config.SetTRTDynamicShapeInfo(min_input_shape, max_input_shape,
opt_input_shape);
std::vector<float> out_data;
run(config, &out_data);
for (size_t i = 0; i < out_data.size(); i++) {
EXPECT_NEAR(result[i], out_data[i], 2e-3);
}
}
TEST(AnalysisPredictor, no_fp16) {
std::vector<float> result = {0.498667, 0.501333};
trt_ernie(false, result);
}
} // namespace inference
} // namespace paddle
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief MAX7219 ドライバー
Copyright 2016 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include <cstring>
#include "common/iica_io.hpp"
#include "common/time.h"
namespace chip {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief MAX7219 テンプレートクラス
@param[in] SPI SPI クラス
@param[in] SELECT デバイス選択
@param[in] CHAIN デージー・チェイン数
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class SPI, class SELECT, uint32_t CHAIN = 1>
class MAX7219 {
SPI& spi_;
uint16_t limit_;
uint8_t data_[CHAIN * 8];
enum class command : uint8_t {
NO_OP = 0x00,
DIGIT_0 = 0x01,
DIGIT_1 = 0x02,
DIGIT_2 = 0x03,
DIGIT_3 = 0x04,
DIGIT_4 = 0x05,
DIGIT_5 = 0x06,
DIGIT_6 = 0x07,
DIGIT_7 = 0x08,
DECODE_MODE = 0x09,
INTENSITY = 0x0A,
SCAN_LIMIT = 0x0B,
SHUTDOWN = 0x0C,
DISPLAY_TEST = 0x0F,
};
// MAX7212 MSB first, 2 bytes
void out_(command cmd, uint8_t dat) {
SELECT::P = 0;
uint8_t tmp[2];
tmp[0] = static_cast<uint8_t>(cmd);
tmp[1] = dat;
spi_.send(tmp, 2);
SELECT::P = 1; // load
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] spi SPI クラスを参照で渡す
*/
//-----------------------------------------------------------------//
MAX7219(SPI& spi) : spi_(spi), limit_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] limit スキャン・リミット
@return エラーなら「false」を返す
*/
//-----------------------------------------------------------------//
bool start(uint8_t limit = (CHAIN * 8)) {
if(limit_ > (8 * CHAIN) || limit == 0) {
return false;
}
limit_ = limit;
SELECT::DIR = 1; // output;
SELECT::PU = 0; // pull-up disable
SELECT::P = 1; // /CS = H
for(uint8_t i = 0; i < sizeof(data_); ++i) {
data_[i] = 0;
}
out_(command::SHUTDOWN, 0x01); // ノーマル・モード
out_(command::DECODE_MODE, 0x00); // デコード・モード
out_(command::SCAN_LIMIT, limit - 1); // 表示桁設定
set_intensity(0); // 輝度(最低)
service();
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 輝度の設定
@param[in] inten 輝度値(最小:0、最大:15)
@return エラー(初期化不良)なら「false」
*/
//-----------------------------------------------------------------//
bool set_intensity(uint8_t inten) {
if(limit_ == 0) return false;
out_(command::INTENSITY, inten);
return true;
}
//-----------------------------------------------------------------//
/*!
@brief データ転送
@return エラー(初期化不良)なら「false」
*/
//-----------------------------------------------------------------//
bool service() {
if(limit_ == 0) return false;
for(uint8_t i = 0; i < limit_; ++i) {
out_(static_cast<command>(static_cast<uint8_t>(command::DIGIT_0) + i), data_[i]);
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 値の取得
@param[in] idx インデックス(0~7)
@return 値
*/
//-----------------------------------------------------------------//
uint8_t get(uint8_t idx) {
if(idx < limit_) {
return data_[idx];
}
return 0;
}
//-----------------------------------------------------------------//
/*!
@brief 値の設定
@param[in] idx インデックス(0~7)
@param[in] dat データ
*/
//-----------------------------------------------------------------//
void set(uint8_t idx, uint8_t dat) {
if(idx < limit_) {
data_[idx] = dat;
}
}
//-----------------------------------------------------------------//
/*!
@brief キャラクターの設定
@param[in] idx インデックス(0~7)
@param[in] cha キャラクターコード
@param[in] dp 小数点
*/
//-----------------------------------------------------------------//
void set_cha(uint8_t idx, char cha, bool dp = false) {
uint8_t d = 0;
switch(cha) {
case ' ':
break;
case '-':
d = 0b0000001;
break;
case '_':
d = 0b0001000;
break;
case '~':
d = 0b1000000;
break;
case '0':
d = 0b1111110;
break;
case '1':
d = 0b0110000;
break;
case '2':
d = 0b1101101;
break;
case '3':
d = 0b1111001;
break;
case '4':
d = 0b0110011;
break;
case '5':
d = 0b1011011;
break;
case '6':
d = 0b1011111;
break;
case '7':
d = 0b1110000;
break;
case '8':
d = 0b1111111;
break;
case '9':
d = 0b1111011;
break;
case 'A':
case 'a':
d = 0b1110111;
break;
case 'B':
case 'b':
d = 0b0011111;
break;
case 'C':
d = 0b1001110;
break;
case 'c':
d = 0b0001101;
break;
case 'D':
case 'd':
d = 0b0111101;
break;
case 'E':
case 'e':
d = 0b1001111;
break;
case 'F':
case 'f':
d = 0b1000111;
break;
case 'G':
case 'g':
d = 0b1011110;
break;
case 'H':
case 'h':
d = 0b0010111;
break;
case 'I':
case 'i':
d = 0b0000100;
break;
case 'J':
case 'j':
d = 0b0111100;
break;
case 'K':
case 'k':
d = 0b1010111;
break;
case 'L':
case 'l':
d = 0b0001110;
break;
case 'M':
case 'm':
d = 0b1110110;
break;
case 'N':
case 'n':
d = 0b0010101;
break;
case 'O':
case 'o':
d = 0b0011101;
break;
case 'P':
case 'p':
d = 0b1100111;
break;
case 'Q':
case 'q':
d = 0b1101111;
break;
case 'R':
case 'r':
d = 0b0000101;
break;
case 'S':
case 's':
d = 0b0011011;
break;
case 'T':
case 't':
d = 0b0001111;
break;
case 'U':
case 'u':
d = 0b0011100;
break;
case 'V':
case 'v':
d = 0b0111110;
break;
case 'W':
case 'w':
d = 0b0111111;
break;
case 'X':
case 'x':
d = 0b0110111;
break;
case 'Y':
case 'y':
d = 0b0111011;
break;
case 'Z':
case 'z':
d = 0b1101100;
break;
default:
break;
}
if(dp) d |= 0x80;
set(idx, d);
}
//-----------------------------------------------------------------//
/*!
@brief シフト、バッファ先頭
@param[in] fill 埋めるデータ
*/
//-----------------------------------------------------------------//
uint8_t shift_begin(uint8_t fill = 0) {
uint8_t full = data_[0];
std::memmove(&data_[1], &data_[0], 7);
data_[0] = fill;
return full;
}
//-----------------------------------------------------------------//
/*!
@brief シフト、バッファ
@param[in] fill 埋めるデータ
*/
//-----------------------------------------------------------------//
void shift_last(uint8_t fill = 0) {
uint8_t full = data_[7];
std::memmove(&data_[0], &data_[1], 7);
data_[7] = fill;
return full;
}
};
}
<commit_msg>fix shift API<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief MAX7219 ドライバー
Copyright 2016 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include <cstring>
#include "common/iica_io.hpp"
#include "common/time.h"
namespace chip {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief MAX7219 テンプレートクラス
@param[in] SPI SPI クラス
@param[in] SELECT デバイス選択
@param[in] CHAIN デージー・チェイン数
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class SPI, class SELECT, uint32_t CHAIN = 1>
class MAX7219 {
SPI& spi_;
uint16_t limit_;
uint8_t data_[CHAIN * 8];
enum class command : uint8_t {
NO_OP = 0x00,
DIGIT_0 = 0x01,
DIGIT_1 = 0x02,
DIGIT_2 = 0x03,
DIGIT_3 = 0x04,
DIGIT_4 = 0x05,
DIGIT_5 = 0x06,
DIGIT_6 = 0x07,
DIGIT_7 = 0x08,
DECODE_MODE = 0x09,
INTENSITY = 0x0A,
SCAN_LIMIT = 0x0B,
SHUTDOWN = 0x0C,
DISPLAY_TEST = 0x0F,
};
// MAX7212 MSB first, 2 bytes
void out_(command cmd, uint8_t dat) {
SELECT::P = 0;
uint8_t tmp[2];
tmp[0] = static_cast<uint8_t>(cmd);
tmp[1] = dat;
spi_.send(tmp, 2);
SELECT::P = 1; // load
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] spi SPI クラスを参照で渡す
*/
//-----------------------------------------------------------------//
MAX7219(SPI& spi) : spi_(spi), limit_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] limit スキャン・リミット
@return エラーなら「false」を返す
*/
//-----------------------------------------------------------------//
bool start(uint8_t limit = (CHAIN * 8)) {
if(limit_ > (8 * CHAIN) || limit == 0) {
return false;
}
limit_ = limit;
SELECT::DIR = 1; // output;
SELECT::PU = 0; // pull-up disable
SELECT::P = 1; // /CS = H
for(uint8_t i = 0; i < sizeof(data_); ++i) {
data_[i] = 0;
}
out_(command::SHUTDOWN, 0x01); // ノーマル・モード
out_(command::DECODE_MODE, 0x00); // デコード・モード
out_(command::SCAN_LIMIT, limit - 1); // 表示桁設定
set_intensity(0); // 輝度(最低)
service();
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 輝度の設定
@param[in] inten 輝度値(最小:0、最大:15)
@return エラー(初期化不良)なら「false」
*/
//-----------------------------------------------------------------//
bool set_intensity(uint8_t inten) {
if(limit_ == 0) return false;
out_(command::INTENSITY, inten);
return true;
}
//-----------------------------------------------------------------//
/*!
@brief データ転送
@return エラー(初期化不良)なら「false」
*/
//-----------------------------------------------------------------//
bool service() {
if(limit_ == 0) return false;
for(uint8_t i = 0; i < limit_; ++i) {
out_(static_cast<command>(static_cast<uint8_t>(command::DIGIT_0) + i), data_[i]);
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 値の取得
@param[in] idx インデックス(0~7)
@return 値
*/
//-----------------------------------------------------------------//
uint8_t get(uint8_t idx) {
if(idx < limit_) {
return data_[idx];
}
return 0;
}
//-----------------------------------------------------------------//
/*!
@brief 値の設定
@param[in] idx インデックス(0~7)
@param[in] dat データ
*/
//-----------------------------------------------------------------//
void set(uint8_t idx, uint8_t dat) {
if(idx < limit_) {
data_[idx] = dat;
}
}
//-----------------------------------------------------------------//
/*!
@brief キャラクターの設定
@param[in] idx インデックス(0~7)
@param[in] cha キャラクターコード
@param[in] dp 小数点
*/
//-----------------------------------------------------------------//
void set_cha(uint8_t idx, char cha, bool dp = false) {
uint8_t d = 0;
switch(cha) {
case ' ':
break;
case '-':
d = 0b0000001;
break;
case '_':
d = 0b0001000;
break;
case '~':
d = 0b1000000;
break;
case '0':
d = 0b1111110;
break;
case '1':
d = 0b0110000;
break;
case '2':
d = 0b1101101;
break;
case '3':
d = 0b1111001;
break;
case '4':
d = 0b0110011;
break;
case '5':
d = 0b1011011;
break;
case '6':
d = 0b1011111;
break;
case '7':
d = 0b1110000;
break;
case '8':
d = 0b1111111;
break;
case '9':
d = 0b1111011;
break;
case 'A':
case 'a':
d = 0b1110111;
break;
case 'B':
case 'b':
d = 0b0011111;
break;
case 'C':
d = 0b1001110;
break;
case 'c':
d = 0b0001101;
break;
case 'D':
case 'd':
d = 0b0111101;
break;
case 'E':
case 'e':
d = 0b1001111;
break;
case 'F':
case 'f':
d = 0b1000111;
break;
case 'G':
case 'g':
d = 0b1011110;
break;
case 'H':
case 'h':
d = 0b0010111;
break;
case 'I':
case 'i':
d = 0b0000100;
break;
case 'J':
case 'j':
d = 0b0111100;
break;
case 'K':
case 'k':
d = 0b1010111;
break;
case 'L':
case 'l':
d = 0b0001110;
break;
case 'M':
case 'm':
d = 0b1110110;
break;
case 'N':
case 'n':
d = 0b0010101;
break;
case 'O':
case 'o':
d = 0b0011101;
break;
case 'P':
case 'p':
d = 0b1100111;
break;
case 'Q':
case 'q':
d = 0b1101111;
break;
case 'R':
case 'r':
d = 0b0000101;
break;
case 'S':
case 's':
d = 0b0011011;
break;
case 'T':
case 't':
d = 0b0001111;
break;
case 'U':
case 'u':
d = 0b0011100;
break;
case 'V':
case 'v':
d = 0b0111110;
break;
case 'W':
case 'w':
d = 0b0111111;
break;
case 'X':
case 'x':
d = 0b0110111;
break;
case 'Y':
case 'y':
d = 0b0111011;
break;
case 'Z':
case 'z':
d = 0b1101100;
break;
default:
break;
}
if(dp) d |= 0x80;
set(idx, d);
}
//-----------------------------------------------------------------//
/*!
@brief シフト、バッファ先頭
@param[in] fill 埋めるデータ
*/
//-----------------------------------------------------------------//
uint8_t shift_top(uint8_t fill = 0) {
uint8_t full = data_[0];
std::memmove(&data_[1], &data_[0], 7);
data_[0] = fill;
return full;
}
//-----------------------------------------------------------------//
/*!
@brief シフト、バッファ終端
@param[in] fill 埋めるデータ
*/
//-----------------------------------------------------------------//
uint8_t shift_end(uint8_t fill = 0) {
uint8_t full = data_[7];
std::memmove(&data_[0], &data_[1], 7);
data_[7] = fill;
return full;
}
};
}
<|endoftext|> |
<commit_before>#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include "overviewpage.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("UltraCoin will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
<commit_msg>Update encrypt message<commit_after>#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include "overviewpage.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>. <br/> Always encrypt your wallet and save your password or <b>you could lose your coins forever</b>"));
setWindowTitle(tr("Encrypt wallet"));
break;
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("UltraCoin will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include <string>
#include <memory>
#include <windows.h>
#include <psapi.h> //GetModuleFileNameEx
#include <TlHelp32.h>
// Setting DLL access controls
#include <AccCtrl.h>
#include <Aclapi.h>
#include <Sddl.h>
// UWP
#include <atlbase.h>
#include <appmodel.h>
#include "MinConsole.hpp"
namespace Console = MinConsole;
const wchar_t* DLLFile = L"UWPDumper.dll";
void SetAccessControl(
const std::wstring &ExecutableName,
const wchar_t *AccessString
);
bool DLLInjectRemote(uint32_t ProcessID, const std::wstring &DLLpath);
std::wstring GetRunningDirectory();
int main()
{
SetConsoleOutputCP(437);
Console::SetTextColor(Console::Color::Green | Console::Color::Bright);
std::wcout << "UWPInjector Build date (" << __DATE__ << " : " << __TIME__ << ")" << std::endl;
Console::SetTextColor(Console::Color::Input);
std::wcout << "\t-https://github.com/Wunkolo/UWPDumper\n";
Console::SetTextColor(Console::Color::Magenta);
std::wcout << std::wstring(Console::GetWidth() - 1, '-') << std::endl;
Console::SetTextColor(Console::Color::Info);
uint32_t ProcessID = 0;
std::cout << "Currently running UWP Apps:" << std::endl;
void* ProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 ProcessEntry;
ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
if( Process32First(ProcessSnapshot, &ProcessEntry) )
{
while( Process32Next(ProcessSnapshot, &ProcessEntry) )
{
void* ProcessHandle = OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION,
false,
ProcessEntry.th32ProcessID
);
if( ProcessHandle )
{
uint32_t NameLength = 0;
int32_t ProcessCode = GetPackageFamilyName(
ProcessHandle,
&NameLength,
nullptr
);
if( NameLength )
{
Console::SetTextColor(Console::Color::Green | Console::Color::Bright);
std::wcout
<< std::setw(12)
<< ProcessEntry.th32ProcessID;
Console::SetTextColor(Console::Color::Info);
std::wcout
<< " | "
<< ProcessEntry.szExeFile << " :\n\t\t-";
std::unique_ptr<wchar_t[]> PackageName(new wchar_t[NameLength]());
ProcessCode = GetPackageFamilyName(
ProcessHandle,
&NameLength,
PackageName.get()
);
if( ProcessCode != ERROR_SUCCESS )
{
std::wcout << "GetPackageFamilyName Error: " << ProcessCode;
}
std::wcout << PackageName.get() << std::endl;
PackageName.reset();
}
}
CloseHandle(ProcessHandle);
}
}
else
{
// Error iterating processes
}
std::cout << "Enter ProcessID: ";
Console::SetTextColor(Console::Color::Green | Console::Color::Bright);
std::cin >> ProcessID;
Console::SetTextColor(Console::Color::Info);
SetAccessControl(GetRunningDirectory() + L"\\" + DLLFile, L"S-1-15-2-1");
if( DLLInjectRemote(ProcessID, GetRunningDirectory() + L"\\" + DLLFile) )
{
Console::SetTextColor(Console::Color::Green | Console::Color::Bright);
std::cout << "Success!" << std::endl;
}
else
{
Console::SetTextColor(Console::Color::Red | Console::Color::Bright);
std::cout << "Failed" << std::endl;
system("pause");
}
return 0;
}
void SetAccessControl(const std::wstring &ExecutableName, const wchar_t* AccessString)
{
PSECURITY_DESCRIPTOR SecurityDescriptor = nullptr;
EXPLICIT_ACCESSW ExplicitAccess = { 0 };
ACL *AccessControlCurrent = nullptr;
ACL *AccessControlNew = nullptr;
SECURITY_INFORMATION SecurityInfo = DACL_SECURITY_INFORMATION;
PSID SecurityIdentifier = nullptr;
if( GetNamedSecurityInfoW(
ExecutableName.c_str(),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
nullptr,
nullptr,
&AccessControlCurrent,
nullptr,
&SecurityDescriptor) == ERROR_SUCCESS
)
{
ConvertStringSidToSidW(AccessString, &SecurityIdentifier);
if( SecurityIdentifier != nullptr )
{
ExplicitAccess.grfAccessPermissions = GENERIC_READ | GENERIC_EXECUTE;
ExplicitAccess.grfAccessMode = SET_ACCESS;
ExplicitAccess.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
ExplicitAccess.Trustee.ptstrName = reinterpret_cast<wchar_t*>(SecurityIdentifier);
if( SetEntriesInAclW(
1,
&ExplicitAccess,
AccessControlCurrent,
&AccessControlNew) == ERROR_SUCCESS )
{
SetNamedSecurityInfoW(
const_cast<wchar_t*>(ExecutableName.c_str()),
SE_FILE_OBJECT,
SecurityInfo,
nullptr,
nullptr,
AccessControlNew,
nullptr
);
};
}
}
if( SecurityDescriptor )
{
LocalFree(
reinterpret_cast<HLOCAL>(SecurityDescriptor)
);
}
if( AccessControlNew )
{
LocalFree(
reinterpret_cast<HLOCAL>(AccessControlNew)
);
}
}
bool DLLInjectRemote(uint32_t ProcessID, const std::wstring& DLLpath)
{
const size_t DLLPathSize = ((DLLpath.size() + 1) * sizeof(wchar_t));
uint32_t Result = 0;
if( !ProcessID )
{
std::wcout << "Invalid Process ID: " << ProcessID << std::endl;
return false;
}
if( GetFileAttributesW(DLLpath.c_str()) == INVALID_FILE_ATTRIBUTES )
{
std::wcout << "DLL file: " << DLLpath << " does not exists" << std::endl;
return false;
}
SetAccessControl(DLLpath, L"S-1-15-2-1");
void* ProcLoadLibrary = reinterpret_cast<void*>(
GetProcAddress(
GetModuleHandleW(L"kernel32.dll"),
"LoadLibraryW")
);
if( !ProcLoadLibrary )
{
std::wcout << "Unable to find LoadLibraryW procedure" << std::endl;
return false;
}
void* Process = OpenProcess(
PROCESS_ALL_ACCESS,
false,
ProcessID);
if( Process == nullptr )
{
std::wcout << "Unable to open process ID" << ProcessID << " for writing" << std::endl;
return false;
}
void* VirtualAlloc = reinterpret_cast<void*>(
VirtualAllocEx(
Process,
nullptr,
DLLPathSize,
MEM_RESERVE | MEM_COMMIT,
PAGE_READWRITE
)
);
if( VirtualAlloc == nullptr )
{
std::wcout << "Unable to remotely allocate memory" << std::endl;
CloseHandle(Process);
return false;
}
SIZE_T BytesWritten = 0;
Result = WriteProcessMemory(
Process,
VirtualAlloc,
DLLpath.data(),
DLLPathSize,
&BytesWritten
);
if( Result == 0 )
{
std::wcout << "Unable to write process memory" << std::endl;
CloseHandle(Process);
return false;
}
if( BytesWritten != DLLPathSize )
{
std::wcout << "Failed to write remote DLL path name" << std::endl;
CloseHandle(Process);
return false;
}
void* RemoteThread =
CreateRemoteThread(
Process,
nullptr,
0,
reinterpret_cast<LPTHREAD_START_ROUTINE>(ProcLoadLibrary),
VirtualAlloc,
0,
0
);
// Wait for remote thread to finish
if( RemoteThread )
{
// Explicitly wait for LoadLibraryW to complete before releasing memory
// avoids causing a remote memory leak
WaitForSingleObject(RemoteThread, INFINITE);
CloseHandle(RemoteThread);
}
else
{
// Failed to create thread
std::wcout << "Unable to create remote thread" << std::endl;
}
VirtualFreeEx(Process, VirtualAlloc, 0, MEM_RELEASE);
CloseHandle(Process);
return true;
}
std::wstring GetRunningDirectory()
{
wchar_t RunPath[MAX_PATH];
GetModuleFileNameW(GetModuleHandleW(nullptr), RunPath, MAX_PATH);
PathRemoveFileSpecW(RunPath);
return std::wstring(RunPath);
}<commit_msg>Add process iteration failure message<commit_after>#include <iostream>
#include <iomanip>
#include <string>
#include <memory>
#include <windows.h>
#include <psapi.h> //GetModuleFileNameEx
#include <TlHelp32.h>
// Setting DLL access controls
#include <AccCtrl.h>
#include <Aclapi.h>
#include <Sddl.h>
// UWP
#include <atlbase.h>
#include <appmodel.h>
#include "MinConsole.hpp"
namespace Console = MinConsole;
const wchar_t* DLLFile = L"UWPDumper.dll";
void SetAccessControl(
const std::wstring &ExecutableName,
const wchar_t *AccessString
);
bool DLLInjectRemote(uint32_t ProcessID, const std::wstring &DLLpath);
std::wstring GetRunningDirectory();
int main()
{
SetConsoleOutputCP(437);
Console::SetTextColor(Console::Color::Green | Console::Color::Bright);
std::wcout << "UWPInjector Build date (" << __DATE__ << " : " << __TIME__ << ")" << std::endl;
Console::SetTextColor(Console::Color::Input);
std::wcout << "\t-https://github.com/Wunkolo/UWPDumper\n";
Console::SetTextColor(Console::Color::Magenta);
std::wcout << std::wstring(Console::GetWidth() - 1, '-') << std::endl;
Console::SetTextColor(Console::Color::Info);
uint32_t ProcessID = 0;
std::cout << "Currently running UWP Apps:" << std::endl;
void* ProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 ProcessEntry;
ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
if( Process32First(ProcessSnapshot, &ProcessEntry) )
{
while( Process32Next(ProcessSnapshot, &ProcessEntry) )
{
void* ProcessHandle = OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION,
false,
ProcessEntry.th32ProcessID
);
if( ProcessHandle )
{
uint32_t NameLength = 0;
int32_t ProcessCode = GetPackageFamilyName(
ProcessHandle,
&NameLength,
nullptr
);
if( NameLength )
{
Console::SetTextColor(Console::Color::Green | Console::Color::Bright);
std::wcout
<< std::setw(12)
<< ProcessEntry.th32ProcessID;
Console::SetTextColor(Console::Color::Info);
std::wcout
<< " | "
<< ProcessEntry.szExeFile << " :\n\t\t-";
std::unique_ptr<wchar_t[]> PackageName(new wchar_t[NameLength]());
ProcessCode = GetPackageFamilyName(
ProcessHandle,
&NameLength,
PackageName.get()
);
if( ProcessCode != ERROR_SUCCESS )
{
std::wcout << "GetPackageFamilyName Error: " << ProcessCode;
}
std::wcout << PackageName.get() << std::endl;
PackageName.reset();
}
}
CloseHandle(ProcessHandle);
}
}
else
{
Console::SetTextColor(Console::Color::Red | Console::Color::Bright);
std::cout << "Unable to iterate active processes" << std::endl;
system("pause");
return 1;
}
std::cout << "Enter ProcessID: ";
Console::SetTextColor(Console::Color::Green | Console::Color::Bright);
std::cin >> ProcessID;
Console::SetTextColor(Console::Color::Info);
SetAccessControl(GetRunningDirectory() + L"\\" + DLLFile, L"S-1-15-2-1");
if( DLLInjectRemote(ProcessID, GetRunningDirectory() + L"\\" + DLLFile) )
{
Console::SetTextColor(Console::Color::Green | Console::Color::Bright);
std::cout << "Success!" << std::endl;
}
else
{
Console::SetTextColor(Console::Color::Red | Console::Color::Bright);
std::cout << "Failed" << std::endl;
system("pause");
}
return 0;
}
void SetAccessControl(const std::wstring &ExecutableName, const wchar_t* AccessString)
{
PSECURITY_DESCRIPTOR SecurityDescriptor = nullptr;
EXPLICIT_ACCESSW ExplicitAccess = { 0 };
ACL *AccessControlCurrent = nullptr;
ACL *AccessControlNew = nullptr;
SECURITY_INFORMATION SecurityInfo = DACL_SECURITY_INFORMATION;
PSID SecurityIdentifier = nullptr;
if( GetNamedSecurityInfoW(
ExecutableName.c_str(),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
nullptr,
nullptr,
&AccessControlCurrent,
nullptr,
&SecurityDescriptor) == ERROR_SUCCESS
)
{
ConvertStringSidToSidW(AccessString, &SecurityIdentifier);
if( SecurityIdentifier != nullptr )
{
ExplicitAccess.grfAccessPermissions = GENERIC_READ | GENERIC_EXECUTE;
ExplicitAccess.grfAccessMode = SET_ACCESS;
ExplicitAccess.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
ExplicitAccess.Trustee.ptstrName = reinterpret_cast<wchar_t*>(SecurityIdentifier);
if( SetEntriesInAclW(
1,
&ExplicitAccess,
AccessControlCurrent,
&AccessControlNew) == ERROR_SUCCESS )
{
SetNamedSecurityInfoW(
const_cast<wchar_t*>(ExecutableName.c_str()),
SE_FILE_OBJECT,
SecurityInfo,
nullptr,
nullptr,
AccessControlNew,
nullptr
);
};
}
}
if( SecurityDescriptor )
{
LocalFree(
reinterpret_cast<HLOCAL>(SecurityDescriptor)
);
}
if( AccessControlNew )
{
LocalFree(
reinterpret_cast<HLOCAL>(AccessControlNew)
);
}
}
bool DLLInjectRemote(uint32_t ProcessID, const std::wstring& DLLpath)
{
const size_t DLLPathSize = ((DLLpath.size() + 1) * sizeof(wchar_t));
uint32_t Result = 0;
if( !ProcessID )
{
std::wcout << "Invalid Process ID: " << ProcessID << std::endl;
return false;
}
if( GetFileAttributesW(DLLpath.c_str()) == INVALID_FILE_ATTRIBUTES )
{
std::wcout << "DLL file: " << DLLpath << " does not exists" << std::endl;
return false;
}
SetAccessControl(DLLpath, L"S-1-15-2-1");
void* ProcLoadLibrary = reinterpret_cast<void*>(
GetProcAddress(
GetModuleHandleW(L"kernel32.dll"),
"LoadLibraryW")
);
if( !ProcLoadLibrary )
{
std::wcout << "Unable to find LoadLibraryW procedure" << std::endl;
return false;
}
void* Process = OpenProcess(
PROCESS_ALL_ACCESS,
false,
ProcessID);
if( Process == nullptr )
{
std::wcout << "Unable to open process ID" << ProcessID << " for writing" << std::endl;
return false;
}
void* VirtualAlloc = reinterpret_cast<void*>(
VirtualAllocEx(
Process,
nullptr,
DLLPathSize,
MEM_RESERVE | MEM_COMMIT,
PAGE_READWRITE
)
);
if( VirtualAlloc == nullptr )
{
std::wcout << "Unable to remotely allocate memory" << std::endl;
CloseHandle(Process);
return false;
}
SIZE_T BytesWritten = 0;
Result = WriteProcessMemory(
Process,
VirtualAlloc,
DLLpath.data(),
DLLPathSize,
&BytesWritten
);
if( Result == 0 )
{
std::wcout << "Unable to write process memory" << std::endl;
CloseHandle(Process);
return false;
}
if( BytesWritten != DLLPathSize )
{
std::wcout << "Failed to write remote DLL path name" << std::endl;
CloseHandle(Process);
return false;
}
void* RemoteThread =
CreateRemoteThread(
Process,
nullptr,
0,
reinterpret_cast<LPTHREAD_START_ROUTINE>(ProcLoadLibrary),
VirtualAlloc,
0,
0
);
// Wait for remote thread to finish
if( RemoteThread )
{
// Explicitly wait for LoadLibraryW to complete before releasing memory
// avoids causing a remote memory leak
WaitForSingleObject(RemoteThread, INFINITE);
CloseHandle(RemoteThread);
}
else
{
// Failed to create thread
std::wcout << "Unable to create remote thread" << std::endl;
}
VirtualFreeEx(Process, VirtualAlloc, 0, MEM_RELEASE);
CloseHandle(Process);
return true;
}
std::wstring GetRunningDirectory()
{
wchar_t RunPath[MAX_PATH];
GetModuleFileNameW(GetModuleHandleW(nullptr), RunPath, MAX_PATH);
PathRemoveFileSpecW(RunPath);
return std::wstring(RunPath);
}<|endoftext|> |
<commit_before>// Copyright (c) 2016-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/test/rpcnestedtests.h>
#include <interfaces/node.h>
#include <rpc/server.h>
#include <qt/rpcconsole.h>
#include <test/util/setup_common.h>
#include <univalue.h>
#include <util/system.h>
#include <QDir>
#include <QtGlobal>
static RPCHelpMan rpcNestedTest_rpc()
{
return RPCHelpMan{
"rpcNestedTest",
"echo the passed string(s)",
{
{"arg1", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""},
{"arg2", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""},
{"arg3", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""},
},
{},
RPCExamples{""},
[](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
return request.params.write(0, 0);
},
};
}
static const CRPCCommand vRPCCommands[] = {
{"test", "rpcNestedTest", &rpcNestedTest_rpc, {"arg1", "arg2", "arg3"}},
};
void RPCNestedTests::rpcNestedTests()
{
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]);
TestingSetup test;
if (RPCIsInWarmup(nullptr)) SetRPCWarmupFinished();
std::string result;
std::string result2;
std::string filtered;
interfaces::Node* node = &m_node;
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())"); //simple 2 level nesting
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getblock(getbestblockhash())[hash], true)");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child containing the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(*node, result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
(RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parameters is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())[tx][0]", &filtered);
QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b");
QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]");
RPCConsole::RPCParseCommandLine(nullptr, result, "importprivkey", false, &filtered);
QVERIFY(filtered == "importprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc,def", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signrawtransactionwithkey(abc)", false, &filtered);
QVERIFY(filtered == "signrawtransactionwithkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrase(help())", false, &filtered);
QVERIFY(filtered == "walletpassphrase(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
QVERIFY(filtered == "walletpassphrasechange(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(encryptwallet(abc, def))", false, &filtered);
QVERIFY(filtered == "help(encryptwallet(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey())", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(help()))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest");
QVERIFY(result == "[]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()()()")); //tolerate non command brackts
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(True)"), UniValue); //invalid argument
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "a(getblockchaininfo(True))"), UniValue); //method not found
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
}
<commit_msg>qt/test: [FIX] Add forgotten Context setting in RPCNestedTests<commit_after>// Copyright (c) 2016-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/test/rpcnestedtests.h>
#include <interfaces/node.h>
#include <rpc/server.h>
#include <qt/rpcconsole.h>
#include <test/util/setup_common.h>
#include <univalue.h>
#include <util/system.h>
#include <QDir>
#include <QtGlobal>
static RPCHelpMan rpcNestedTest_rpc()
{
return RPCHelpMan{
"rpcNestedTest",
"echo the passed string(s)",
{
{"arg1", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""},
{"arg2", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""},
{"arg3", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""},
},
{},
RPCExamples{""},
[](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
return request.params.write(0, 0);
},
};
}
static const CRPCCommand vRPCCommands[] = {
{"test", "rpcNestedTest", &rpcNestedTest_rpc, {"arg1", "arg2", "arg3"}},
};
void RPCNestedTests::rpcNestedTests()
{
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]);
TestingSetup test;
m_node.setContext(&test.m_node);
if (RPCIsInWarmup(nullptr)) SetRPCWarmupFinished();
std::string result;
std::string result2;
std::string filtered;
RPCConsole::RPCExecuteCommandLine(m_node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
RPCConsole::RPCExecuteCommandLine(m_node, result, "getblock(getbestblockhash())"); //simple 2 level nesting
RPCConsole::RPCExecuteCommandLine(m_node, result, "getblock(getblock(getbestblockhash())[hash], true)");
RPCConsole::RPCExecuteCommandLine(m_node, result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
RPCConsole::RPCExecuteCommandLine(m_node, result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(m_node, result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(m_node, result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
(RPCConsole::RPCExecuteCommandLine(m_node, result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child containing the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(m_node, result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(m_node, result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
(RPCConsole::RPCExecuteCommandLine(m_node, result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parameters is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(m_node, result, "getblock(getbestblockhash())[tx][0]", &filtered);
QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b");
QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]");
RPCConsole::RPCParseCommandLine(nullptr, result, "importprivkey", false, &filtered);
QVERIFY(filtered == "importprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc,def", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signrawtransactionwithkey(abc)", false, &filtered);
QVERIFY(filtered == "signrawtransactionwithkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrase(help())", false, &filtered);
QVERIFY(filtered == "walletpassphrase(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
QVERIFY(filtered == "walletpassphrasechange(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(encryptwallet(abc, def))", false, &filtered);
QVERIFY(filtered == "help(encryptwallet(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey())", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(help()))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))");
RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest");
QVERIFY(result == "[]");
RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(m_node, result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(m_node, result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
(RPCConsole::RPCExecuteCommandLine(m_node, result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
(RPCConsole::RPCExecuteCommandLine(m_node, result, "getblockchaininfo()()()")); //tolerate non command brackts
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(m_node, result, "getblockchaininfo(True)"), UniValue); //invalid argument
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(m_node, result, "a(getblockchaininfo(True))"), UniValue); //method not found
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(m_node, result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.