text
stringlengths 54
60.6k
|
---|
<commit_before>/**
* @file hud_fox.cpp
* @brief Purpose: Contains methods to game class' management.
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*/
#include "../include/hud_fox.hpp"
using namespace mindscape;
/**
* @brief Class Contructor.
*
* Sets Hud Fox's firsts informations (attributes' values).
* (Hud Fox: Fox's health bar).
*
* @param name Hud Fox's name(name of the object).
* @param position Hud Fox's coordinates in the game's map.
* @param priority Hud Fox's priority in game's execution.
* @return void.
*/
HudFox::HudFox(
std::string name,
std::pair<int, int> position,
int priority)
:engine::GameObject(
name,
position,
priority,
{
//No engine Keyboard Event needed.
}
) {
initialize_animations();
initialize_audio_effects();
};
/**
* @brief Initiates Hud Fox's music.
*
* Sets sound effect of heart.
* @return void.
*/
void HudFox::initialize_audio_effects() {
engine::Audio * take_this_hp = new engine::Audio(
"heart", "../assets/audios/effects_songs/mindscape_heart.wav",
engine::Audio::CHUNK);
take_this_hp->set_duration(1);
add_component(take_this_hp);
}
/**
* @brief Notifies Hud Fox of Fox's state.
*
* Verifies Fox's state and sets stars' animation depending of the quantity of
* stars collected.
*
* @param game_object Object for observe game's situation,
* in this case, the Fox.
* @return void.
*/
void HudFox::notify(engine::Observable* game_object) {
Fox* fox = dynamic_cast<Fox *>(game_object);
if(fox) {
bool give_hp = fox->get_animation_hud_fading();
int count = fox->get_star_count();
engine::Animation* actual = get_actual_animation();
if(actual == animations["three_star_fading"]) {
if(actual->is_finished) {
give_hp = false;
fox->set_star_count(0);
set_actual_animation(animations["zero_star"]);
}
}
else {
if(count == 0) {
if(!(get_actual_animation() == animations["zero_star"])) {
set_actual_animation(animations["zero_star"]);
}
}
else if(count == 1) {
if(!(get_actual_animation() == animations["one_star"])){
set_actual_animation(animations["one_star"]);
}
}
else if(count == 2) {
if(!(get_actual_animation() == animations["two_star"])) {
set_actual_animation(animations["two_star"]);
}
}
else if(count == 3 && !give_hp) {
if(!(get_actual_animation() == animations["three_star"])) {
set_actual_animation(animations["three_star"]);
}
}
else if(count == 3 && give_hp) {
fox->set_animation_hud_fading(false);
set_actual_animation(animations["three_star_fading"]);
play_song("heart");
}
}
}
}
/**
* @brief Initiates Hud Fox's animation.
*
* Initiates all Hud Fox's sprites(images).
*
* @return void.
*/
void HudFox::initialize_animations() {
engine::Animation* fox_zero_star = create_animation(
"../assets/images/sprites/hud/hud_fox_0.png",
1,1,0.9, "RIGHT"
);
engine::Animation* fox_one_star = create_animation(
"../assets/images/sprites/hud/hud_fox_1.png",
1,1,0.9, "RIGHT"
);
engine::Animation* fox_two_star = create_animation(
"../assets/images/sprites/hud/hud_fox_2.png",
1,1,0.9, "RIGHT"
);
engine::Animation* fox_three_star = create_animation(
"../assets/images/sprites/hud/hud_fox_3.png",
1,1,0.9, "RIGHT"
);
engine::Animation* fox_three_star_fading = create_animation(
"../assets/images/sprites/hud/hud_fox_3_animation.png",
1,4,1.0, "RIGHT"
);
fox_three_star_fading->in_loop = false;
add_animation("zero_star", fox_zero_star);
add_animation("one_star", fox_one_star);
add_animation("two_star", fox_two_star);
add_animation("three_star", fox_three_star);
add_animation("three_star_fading", fox_three_star_fading);
fox_zero_star->activate();
set_actual_animation(fox_zero_star);
}
/**
* @brief Creates Hud Fox's animation.
*
* Creates all Hud Fox's animation based on Hud Fox's sprites.
*
* @param image_path Path of the Hud Fox's sprite.
* @param sprite_lines Line of the Hud Fox's sprite.
* @warning Limitations of sprite_lines and sprite_columns are
* 1 to the quantity of lines/columns in the image.
* @param sprite_columns Column of the Fox's sprite needed.
* @param duration Duration of the Hud Fox's image to show up.
* @param direction Direction of the Hud Fox's image.
* @return engine::Animation* The animation constructed.
*/
engine::Animation* HudFox::create_animation(
std::string path,
int sprite_lines,
int sprite_columns,
double duration,
std::string direction) {
engine::Game& game = engine::Game::get_instance();
engine::Animation* animation = new engine::Animation(
game.get_renderer(),
path,
// is_active
false,
std::make_pair(0, 0),
// priority
1,
sprite_lines,
sprite_columns,
duration,
// in_loop
true,
direction
);
animation->set_values(
std::make_pair(170, 78),
std::make_pair(170, 78),
std::make_pair(0, 0)
);
return animation;
}
<commit_msg>[INITIALIZATION] Applies initialization in Hud_Fox.cpp variables<commit_after>/**
* @file hud_fox.cpp
* @brief Purpose: Contains methods to game class' management.
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*/
#include "../include/hud_fox.hpp"
using namespace mindscape;
/**
* @brief Class Contructor.
*
* Sets Hud Fox's firsts informations (attributes' values).
* (Hud Fox: Fox's health bar).
*
* @param name Hud Fox's name(name of the object).
* @param position Hud Fox's coordinates in the game's map.
* @param priority Hud Fox's priority in game's execution.
* @return void.
*/
HudFox::HudFox(
std::string name,
std::pair<int, int> position,
int priority)
:engine::GameObject(
name,
position,
priority,
{
//No engine Keyboard Event needed.
}
) {
initialize_animations();
initialize_audio_effects();
};
/**
* @brief Initiates Hud Fox's sound effect.
*
* Sets sound effect of heart.
* @return void.
*/
void HudFox::initialize_audio_effects() {
engine::Audio * take_this_hp = nullptr;
take_this_hp = new engine::Audio(
"heart", "../assets/audios/effects_songs/mindscape_heart.wav",
engine::Audio::CHUNK);
take_this_hp->set_duration(1);
add_component(take_this_hp);
}
/**
* @brief Notifies Hud Fox of Fox's state.
*
* Verifies Fox's state and sets stars' animation depending of the quantity of
* stars collected.
*
* @param game_object Object for observe game's situation,
* in this case, the Fox.
* @return void.
*/
void HudFox::notify(engine::Observable* game_object) {
Fox* fox = nullptr;
fox = dynamic_cast<Fox *>(game_object);
if(fox) {
bool give_hp = false;
give_hp = fox->get_animation_hud_fading();
engine::Animation* actual = NULL;
actual = get_actual_animation();
if(actual == animations["three_star_fading"]) {
if(actual->is_finished) {
give_hp = false;
fox->set_star_count(0);
set_actual_animation(animations["zero_star"]);
}
}
else {
int count = 0;
count = fox->get_star_count();
if(count == 0) {
if(!(get_actual_animation() == animations["zero_star"])) {
set_actual_animation(animations["zero_star"]);
}
}
else if(count == 1) {
if(!(get_actual_animation() == animations["one_star"])){
set_actual_animation(animations["one_star"]);
}
}
else if(count == 2) {
if(!(get_actual_animation() == animations["two_star"])) {
set_actual_animation(animations["two_star"]);
}
}
else if(count == 3 && !give_hp) {
if(!(get_actual_animation() == animations["three_star"])) {
set_actual_animation(animations["three_star"]);
}
}
else if(count == 3 && give_hp) {
fox->set_animation_hud_fading(false);
set_actual_animation(animations["three_star_fading"]);
play_song("heart");
}
}
}
}
/**
* @brief Initiates Hud Fox's animation.
*
* Initiates all Hud Fox's sprites(images).
*
* @return void.
*/
void HudFox::initialize_animations() {
engine::Animation* fox_zero_star = nullptr;
fox_zero_star = create_animation(
"../assets/images/sprites/hud/hud_fox_0.png",
1,1,0.9, "RIGHT"
);
add_animation("zero_star", fox_zero_star);
engine::Animation* fox_one_star = nullptr;
fox_one_star = create_animation(
"../assets/images/sprites/hud/hud_fox_1.png",
1,1,0.9, "RIGHT"
);
add_animation("one_star", fox_one_star);
engine::Animation* fox_two_star = nullptr;
fox_two_star = create_animation(
"../assets/images/sprites/hud/hud_fox_2.png",
1,1,0.9, "RIGHT"
);
add_animation("two_star", fox_two_star);
engine::Animation* fox_three_star = nullptr;
fox_three_star = create_animation(
"../assets/images/sprites/hud/hud_fox_3.png",
1,1,0.9, "RIGHT"
);
add_animation("three_star", fox_three_star);
engine::Animation* fox_three_star_fading = nullptr;
fox_three_star_fading = create_animation(
"../assets/images/sprites/hud/hud_fox_3_animation.png",
1,4,1.0, "RIGHT"
);
fox_three_star_fading->in_loop = false;
add_animation("three_star_fading", fox_three_star_fading);
fox_zero_star->activate();
set_actual_animation(fox_zero_star);
}
/**
* @brief Creates Hud Fox's animation.
*
* Creates all Hud Fox's animation based on Hud Fox's sprites.
*
* @param image_path Path of the Hud Fox's sprite.
* @param sprite_lines Line of the Hud Fox's sprite.
* @warning Limitations of sprite_lines and sprite_columns are
* 1 to the quantity of lines/columns in the image.
* @param sprite_columns Column of the Fox's sprite needed.
* @param duration Duration of the Hud Fox's image to show up.
* @param direction Direction of the Hud Fox's image.
* @return engine::Animation* The animation constructed.
*/
engine::Animation* HudFox::create_animation(
std::string path,
int sprite_lines,
int sprite_columns,
double duration,
std::string direction) {
engine::Game& game = engine::Game::get_instance();
engine::Animation* animation = nullptr;
animation = new engine::Animation(
game.get_renderer(),
path,
// is_active
false,
std::make_pair(0, 0),
// priority
1,
sprite_lines,
sprite_columns,
duration,
// in_loop
true,
direction
);
animation->set_values(
std::make_pair(170, 78),
std::make_pair(170, 78),
std::make_pair(0, 0)
);
return animation;
}
<|endoftext|>
|
<commit_before>//
// TextStimulus.cpp
// TextStimulus
//
// Created by Christopher Stawarz on 9/13/16.
// Copyright © 2016 The MWorks Project. All rights reserved.
//
#include "TextStimulus.hpp"
BEGIN_NAMESPACE_MW
BEGIN_NAMESPACE()
inline cf::StringPtr createCFString(const std::string &bytesUTF8) {
return cf::StringPtr::created(CFStringCreateWithBytes(kCFAllocatorDefault,
reinterpret_cast<const UInt8 *>(bytesUTF8.data()),
bytesUTF8.size(),
kCFStringEncodingUTF8,
false));
}
CTTextAlignment textAlignmentFromName(const std::string &name) {
if (name == "left") {
return kCTTextAlignmentLeft;
} else if (name == "right") {
return kCTTextAlignmentRight;
} else if (name == "center") {
return kCTTextAlignmentCenter;
}
merror(M_DISPLAY_MESSAGE_DOMAIN, "Invalid text alignment: \"%s\"", name.c_str());
return kCTTextAlignmentLeft;
}
END_NAMESPACE()
const std::string TextStimulus::TEXT("text");
const std::string TextStimulus::FONT_NAME("font_name");
const std::string TextStimulus::FONT_SIZE("font_size");
const std::string TextStimulus::TEXT_ALIGNMENT("text_alignment");
const std::string TextStimulus::MAX_SIZE_X("max_size_x");
const std::string TextStimulus::MAX_SIZE_Y("max_size_y");
void TextStimulus::describeComponent(ComponentInfo &info) {
ColoredTransformStimulus::describeComponent(info);
info.setSignature("stimulus/text");
info.addParameter(TEXT);
info.addParameter(FONT_NAME);
info.addParameter(FONT_SIZE);
info.addParameter(TEXT_ALIGNMENT, "left");
info.addParameter(MAX_SIZE_X, false);
info.addParameter(MAX_SIZE_Y, false);
}
TextStimulus::TextStimulus(const ParameterValueMap ¶meters) :
ColoredTransformStimulus(parameters),
text(registerVariable(variableOrText(parameters[TEXT]))),
fontName(registerVariable(variableOrText(parameters[FONT_NAME]))),
fontSize(registerVariable(parameters[FONT_SIZE])),
textAlignment(registerVariable(variableOrText(parameters[TEXT_ALIGNMENT]))),
maxSizeX(optionalVariable(parameters[MAX_SIZE_X])),
maxSizeY(optionalVariable(parameters[MAX_SIZE_Y])),
texturePool(nil),
currentTexture(nil)
{ }
TextStimulus::~TextStimulus() {
@autoreleasepool {
currentTexture = nil;
texturePool = nil;
}
}
Datum TextStimulus::getCurrentAnnounceDrawData() {
auto announceData = ColoredTransformStimulus::getCurrentAnnounceDrawData();
announceData.addElement(STIM_TYPE, "text");
announceData.addElement(TEXT, currentText);
announceData.addElement(FONT_NAME, currentFontName);
announceData.addElement(FONT_SIZE, currentFontSize);
announceData.addElement(TEXT_ALIGNMENT, currentTextAlignment);
return announceData;
}
void TextStimulus::loadMetal(MetalDisplay &display) {
ColoredTransformStimulus::loadMetal(display);
//
// Determine maximum size
//
if (!fullscreen) {
float defaultMaxSizeX = 0.0;
float defaultMaxSizeY = 0.0;
// Don't evaluate x_size and y_size unless we need them
if (!(maxSizeX && maxSizeY)) {
getCurrentSize(defaultMaxSizeX, defaultMaxSizeY);
}
if (maxSizeX) {
currentMaxSizeX = maxSizeX->getValue().getFloat();
} else {
currentMaxSizeX = defaultMaxSizeX;
}
if (currentMaxSizeX <= 0.0) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Maximum horizontal size must be greater than zero");
}
if (maxSizeY) {
currentMaxSizeY = maxSizeY->getValue().getFloat();
} else {
currentMaxSizeY = defaultMaxSizeY;
}
if (currentMaxSizeY <= 0.0) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Maximum vertical size must be greater than zero");
}
}
//
// Determine viewport size and compute conversions from degrees to pixels
// and points to pixels
//
{
__block CGSize displaySizeInPoints;
__block CGSize displaySizeInPixels;
dispatch_sync(dispatch_get_main_queue(), ^{
// If there's only a mirror window, getMainView will return its view,
// so there's no need to call getMirrorView
auto displayView = display.getMainView();
displaySizeInPoints = displayView.frame.size;
displaySizeInPixels = displayView.drawableSize;
});
viewportWidth = displaySizeInPixels.width;
viewportHeight = displaySizeInPixels.height;
double xMin, xMax, yMin, yMax;
display.getDisplayBounds(xMin, xMax, yMin, yMax);
pixelsPerDegree = double(viewportWidth) / (xMax - xMin);
pixelsPerPoint = double(viewportWidth) / displaySizeInPoints.width;
}
//
// Determine texture dimensions and allocate CPU-side texture data
//
computeTextureDimensions(currentMaxSizeX, currentMaxSizeY, textureWidth, textureHeight);
textureBytesPerRow = textureWidth; // Texture contains only alpha values
textureData.reset(new std::uint8_t[textureBytesPerRow * textureHeight]);
//
// Create bitmap context
//
context = cf::ObjectPtr<CGContextRef>::created(CGBitmapContextCreate(textureData.get(),
textureWidth,
textureHeight,
8,
textureBytesPerRow,
nullptr, // OK for alpha-only bitmap
kCGImageAlphaOnly));
// Enable antialiasing
CGContextSetAllowsAntialiasing(context.get(), true);
CGContextSetShouldAntialias(context.get(), true);
// Set the text matrix
CGContextSetTextMatrix(context.get(), CGAffineTransformIdentity);
//
// Create texture pool
//
{
auto textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR8Unorm
width:textureWidth
height:textureHeight
mipmapped:NO];
// Keep the default value of storageMode: MTLStorageModeManaged on macOS, MTLStorageModeShared on iOS
texturePool = [MWKTripleBufferedMTLResource textureWithDevice:display.getMetalDevice()
descriptor:textureDescriptor];
}
//
// Create render pipeline state
//
{
auto library = loadDefaultLibrary(display, MWORKS_GET_CURRENT_BUNDLE());
auto vertexFunction = loadShaderFunction(library, "vertexShader");
auto fragmentFunction = loadShaderFunction(library, "fragmentShader");
auto renderPipelineDescriptor = createRenderPipelineDescriptor(display, vertexFunction, fragmentFunction);
renderPipelineState = createRenderPipelineState(display, renderPipelineDescriptor);
}
}
void TextStimulus::unloadMetal(MetalDisplay &display) {
currentTexture = nil;
texturePool = nil;
context.reset();
textureData.reset();
ColoredTransformStimulus::unloadMetal(display);
}
void TextStimulus::drawMetal(MetalDisplay &display) {
ColoredTransformStimulus::drawMetal(display);
if (current_sizex > currentMaxSizeX) {
merror(M_DISPLAY_MESSAGE_DOMAIN,
"Current horizontal size of stimulus \"%s\" (%g) exceeds maximum (%g). To resolve this issue, "
"set %s to an appropriate value.",
getTag().c_str(),
current_sizex,
currentMaxSizeX,
MAX_SIZE_X.c_str());
return;
}
if (current_sizey > currentMaxSizeY) {
merror(M_DISPLAY_MESSAGE_DOMAIN,
"Current vertical size of stimulus \"%s\" (%g) exceeds maximum (%g). To resolve this issue, "
"set %s to an appropriate value.",
getTag().c_str(),
current_sizey,
currentMaxSizeY,
MAX_SIZE_Y.c_str());
return;
}
computeTextureDimensions(current_sizex, current_sizey, currentWidthPixels, currentHeightPixels);
currentText = text->getValue().getString();
currentFontName = fontName->getValue().getString();
currentFontSize = fontSize->getValue().getFloat();
currentTextAlignment = textAlignment->getValue().getString();
updateTexture(display);
auto renderCommandEncoder = createRenderCommandEncoder(display);
[renderCommandEncoder setRenderPipelineState:renderPipelineState];
setCurrentMVPMatrix(display, renderCommandEncoder, 0);
{
auto texCoordScale = simd::make_float2(currentWidthPixels - 1, currentHeightPixels - 1);
setVertexBytes(renderCommandEncoder, texCoordScale, 1);
}
[renderCommandEncoder setFragmentTexture:currentTexture atIndex:0];
setCurrentColor(renderCommandEncoder, 0);
[renderCommandEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];
[renderCommandEncoder endEncoding];
lastWidthPixels = currentWidthPixels;
lastHeightPixels = currentHeightPixels;
lastText = currentText;
lastFontName = currentFontName;
lastFontSize = currentFontSize;
lastTextAlignment = currentTextAlignment;
}
void TextStimulus::computeTextureDimensions(double widthDegrees,
double heightDegrees,
std::size_t &widthPixels,
std::size_t &heightPixels) const
{
if (fullscreen) {
widthPixels = viewportWidth;
heightPixels = viewportHeight;
} else {
// Replace negative width or height with 0, and ensure that the texture
// contains at least one pixel
widthPixels = std::max(1.0, pixelsPerDegree * std::max(0.0, widthDegrees));
heightPixels = std::max(1.0, pixelsPerDegree * std::max(0.0, heightDegrees));
}
}
void TextStimulus::updateTexture(MetalDisplay &display) {
if (currentTexture &&
currentWidthPixels == lastWidthPixels &&
currentHeightPixels == lastHeightPixels &&
currentText == lastText &&
currentFontName == lastFontName &&
currentFontSize == lastFontSize &&
currentTextAlignment == lastTextAlignment)
{
// No relevant parameters have changed since we last generated the texture, so use
// the existing one
return;
}
//
// Clear the relevant portion of the context
//
// NOTE: By default, Core Graphics contexts place the origin in the lower left corner, whereas
// the origin for Metal textures is in the upper left. To simplify the texture coordinates used
// by Metal, we want to draw in the upper-left corner of the texture. This would be easier to
// do if we just flipped the coordinate system of the CGBitmapContext. Unfortunately, Core Text
// resists such flips and insists on making "up" be the direction of increasing y, meaning that
// text rendered into a y-flipped context is drawn with y flipped. Therefore, we just live with
// the slight annoyance of defining our drawing rectangle relative to Core Graphics' default,
// origin-at-lower-left coordinate system.
//
const auto rect = CGRectMake(0,
textureHeight - currentHeightPixels,
currentWidthPixels,
currentHeightPixels);
CGContextClearRect(context.get(), rect);
// Create the text string
auto attrString = cf::ObjectPtr<CFMutableAttributedStringRef>::created(CFAttributedStringCreateMutable(kCFAllocatorDefault, 0));
CFAttributedStringReplaceString(attrString.get(), CFRangeMake(0, 0), createCFString(currentText).get());
const auto fullRange = CFRangeMake(0, CFAttributedStringGetLength(attrString.get()));
// Set the font, converting size from points to pixels
auto font = cf::ObjectPtr<CTFontRef>::created(CTFontCreateWithName(createCFString(currentFontName).get(),
currentFontSize * pixelsPerPoint,
nullptr));
CFAttributedStringSetAttribute(attrString.get(), fullRange, kCTFontAttributeName, font.get());
// Set the text alignment
const CTTextAlignment alignment = textAlignmentFromName(currentTextAlignment);
const std::array<CTParagraphStyleSetting, 1> paragraphStyleSettings {
{ kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment }
};
auto paragraphStyle = cf::ObjectPtr<CTParagraphStyleRef>::created(CTParagraphStyleCreate(paragraphStyleSettings.data(),
paragraphStyleSettings.size()));
CFAttributedStringSetAttribute(attrString.get(), fullRange, kCTParagraphStyleAttributeName, paragraphStyle.get());
// Generate a Core Text frame
auto framesetter = cf::ObjectPtr<CTFramesetterRef>::created(CTFramesetterCreateWithAttributedString(attrString.get()));
auto path = cf::ObjectPtr<CGPathRef>::created(CGPathCreateWithRect(rect, nullptr));
auto frame = cf::ObjectPtr<CTFrameRef>::created(CTFramesetterCreateFrame(framesetter.get(),
CFRangeMake(0, 0),
path.get(),
nullptr));
// Draw the frame in the context
CTFrameDraw(frame.get(), context.get());
if (CTFrameGetVisibleStringRange(frame.get()).length != fullRange.length) {
mwarning(M_DISPLAY_MESSAGE_DOMAIN,
"Text for stimulus \"%s\" does not fit within the specified region and will be truncated",
getTag().c_str());
}
// Copy the texture data to the next-available texture from the pool
currentTexture = [texturePool acquireWithCommandBuffer:display.getCurrentMetalCommandBuffer()];
[currentTexture replaceRegion:MTLRegionMake2D(0, 0, currentWidthPixels, currentHeightPixels)
mipmapLevel:0
withBytes:textureData.get()
bytesPerRow:textureBytesPerRow];
}
END_NAMESPACE_MW
<commit_msg>Don't check TextStimulus size parameters when drawing fullscreen, as they don't contain valid values and aren't needed<commit_after>//
// TextStimulus.cpp
// TextStimulus
//
// Created by Christopher Stawarz on 9/13/16.
// Copyright © 2016 The MWorks Project. All rights reserved.
//
#include "TextStimulus.hpp"
BEGIN_NAMESPACE_MW
BEGIN_NAMESPACE()
inline cf::StringPtr createCFString(const std::string &bytesUTF8) {
return cf::StringPtr::created(CFStringCreateWithBytes(kCFAllocatorDefault,
reinterpret_cast<const UInt8 *>(bytesUTF8.data()),
bytesUTF8.size(),
kCFStringEncodingUTF8,
false));
}
CTTextAlignment textAlignmentFromName(const std::string &name) {
if (name == "left") {
return kCTTextAlignmentLeft;
} else if (name == "right") {
return kCTTextAlignmentRight;
} else if (name == "center") {
return kCTTextAlignmentCenter;
}
merror(M_DISPLAY_MESSAGE_DOMAIN, "Invalid text alignment: \"%s\"", name.c_str());
return kCTTextAlignmentLeft;
}
END_NAMESPACE()
const std::string TextStimulus::TEXT("text");
const std::string TextStimulus::FONT_NAME("font_name");
const std::string TextStimulus::FONT_SIZE("font_size");
const std::string TextStimulus::TEXT_ALIGNMENT("text_alignment");
const std::string TextStimulus::MAX_SIZE_X("max_size_x");
const std::string TextStimulus::MAX_SIZE_Y("max_size_y");
void TextStimulus::describeComponent(ComponentInfo &info) {
ColoredTransformStimulus::describeComponent(info);
info.setSignature("stimulus/text");
info.addParameter(TEXT);
info.addParameter(FONT_NAME);
info.addParameter(FONT_SIZE);
info.addParameter(TEXT_ALIGNMENT, "left");
info.addParameter(MAX_SIZE_X, false);
info.addParameter(MAX_SIZE_Y, false);
}
TextStimulus::TextStimulus(const ParameterValueMap ¶meters) :
ColoredTransformStimulus(parameters),
text(registerVariable(variableOrText(parameters[TEXT]))),
fontName(registerVariable(variableOrText(parameters[FONT_NAME]))),
fontSize(registerVariable(parameters[FONT_SIZE])),
textAlignment(registerVariable(variableOrText(parameters[TEXT_ALIGNMENT]))),
maxSizeX(optionalVariable(parameters[MAX_SIZE_X])),
maxSizeY(optionalVariable(parameters[MAX_SIZE_Y])),
texturePool(nil),
currentTexture(nil)
{ }
TextStimulus::~TextStimulus() {
@autoreleasepool {
currentTexture = nil;
texturePool = nil;
}
}
Datum TextStimulus::getCurrentAnnounceDrawData() {
auto announceData = ColoredTransformStimulus::getCurrentAnnounceDrawData();
announceData.addElement(STIM_TYPE, "text");
announceData.addElement(TEXT, currentText);
announceData.addElement(FONT_NAME, currentFontName);
announceData.addElement(FONT_SIZE, currentFontSize);
announceData.addElement(TEXT_ALIGNMENT, currentTextAlignment);
return announceData;
}
void TextStimulus::loadMetal(MetalDisplay &display) {
ColoredTransformStimulus::loadMetal(display);
//
// Determine maximum size
//
if (!fullscreen) {
float defaultMaxSizeX = 0.0;
float defaultMaxSizeY = 0.0;
// Don't evaluate x_size and y_size unless we need them
if (!(maxSizeX && maxSizeY)) {
getCurrentSize(defaultMaxSizeX, defaultMaxSizeY);
}
if (maxSizeX) {
currentMaxSizeX = maxSizeX->getValue().getFloat();
} else {
currentMaxSizeX = defaultMaxSizeX;
}
if (currentMaxSizeX <= 0.0) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Maximum horizontal size must be greater than zero");
}
if (maxSizeY) {
currentMaxSizeY = maxSizeY->getValue().getFloat();
} else {
currentMaxSizeY = defaultMaxSizeY;
}
if (currentMaxSizeY <= 0.0) {
throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, "Maximum vertical size must be greater than zero");
}
}
//
// Determine viewport size and compute conversions from degrees to pixels
// and points to pixels
//
{
__block CGSize displaySizeInPoints;
__block CGSize displaySizeInPixels;
dispatch_sync(dispatch_get_main_queue(), ^{
// If there's only a mirror window, getMainView will return its view,
// so there's no need to call getMirrorView
auto displayView = display.getMainView();
displaySizeInPoints = displayView.frame.size;
displaySizeInPixels = displayView.drawableSize;
});
viewportWidth = displaySizeInPixels.width;
viewportHeight = displaySizeInPixels.height;
double xMin, xMax, yMin, yMax;
display.getDisplayBounds(xMin, xMax, yMin, yMax);
pixelsPerDegree = double(viewportWidth) / (xMax - xMin);
pixelsPerPoint = double(viewportWidth) / displaySizeInPoints.width;
}
//
// Determine texture dimensions and allocate CPU-side texture data
//
computeTextureDimensions(currentMaxSizeX, currentMaxSizeY, textureWidth, textureHeight);
textureBytesPerRow = textureWidth; // Texture contains only alpha values
textureData.reset(new std::uint8_t[textureBytesPerRow * textureHeight]);
//
// Create bitmap context
//
context = cf::ObjectPtr<CGContextRef>::created(CGBitmapContextCreate(textureData.get(),
textureWidth,
textureHeight,
8,
textureBytesPerRow,
nullptr, // OK for alpha-only bitmap
kCGImageAlphaOnly));
// Enable antialiasing
CGContextSetAllowsAntialiasing(context.get(), true);
CGContextSetShouldAntialias(context.get(), true);
// Set the text matrix
CGContextSetTextMatrix(context.get(), CGAffineTransformIdentity);
//
// Create texture pool
//
{
auto textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR8Unorm
width:textureWidth
height:textureHeight
mipmapped:NO];
// Keep the default value of storageMode: MTLStorageModeManaged on macOS, MTLStorageModeShared on iOS
texturePool = [MWKTripleBufferedMTLResource textureWithDevice:display.getMetalDevice()
descriptor:textureDescriptor];
}
//
// Create render pipeline state
//
{
auto library = loadDefaultLibrary(display, MWORKS_GET_CURRENT_BUNDLE());
auto vertexFunction = loadShaderFunction(library, "vertexShader");
auto fragmentFunction = loadShaderFunction(library, "fragmentShader");
auto renderPipelineDescriptor = createRenderPipelineDescriptor(display, vertexFunction, fragmentFunction);
renderPipelineState = createRenderPipelineState(display, renderPipelineDescriptor);
}
}
void TextStimulus::unloadMetal(MetalDisplay &display) {
currentTexture = nil;
texturePool = nil;
context.reset();
textureData.reset();
ColoredTransformStimulus::unloadMetal(display);
}
void TextStimulus::drawMetal(MetalDisplay &display) {
ColoredTransformStimulus::drawMetal(display);
if (!fullscreen) {
if (current_sizex > currentMaxSizeX) {
merror(M_DISPLAY_MESSAGE_DOMAIN,
"Current horizontal size of stimulus \"%s\" (%g) exceeds maximum (%g). To resolve this issue, "
"set %s to an appropriate value.",
getTag().c_str(),
current_sizex,
currentMaxSizeX,
MAX_SIZE_X.c_str());
return;
}
if (current_sizey > currentMaxSizeY) {
merror(M_DISPLAY_MESSAGE_DOMAIN,
"Current vertical size of stimulus \"%s\" (%g) exceeds maximum (%g). To resolve this issue, "
"set %s to an appropriate value.",
getTag().c_str(),
current_sizey,
currentMaxSizeY,
MAX_SIZE_Y.c_str());
return;
}
}
computeTextureDimensions(current_sizex, current_sizey, currentWidthPixels, currentHeightPixels);
currentText = text->getValue().getString();
currentFontName = fontName->getValue().getString();
currentFontSize = fontSize->getValue().getFloat();
currentTextAlignment = textAlignment->getValue().getString();
updateTexture(display);
auto renderCommandEncoder = createRenderCommandEncoder(display);
[renderCommandEncoder setRenderPipelineState:renderPipelineState];
setCurrentMVPMatrix(display, renderCommandEncoder, 0);
{
auto texCoordScale = simd::make_float2(currentWidthPixels - 1, currentHeightPixels - 1);
setVertexBytes(renderCommandEncoder, texCoordScale, 1);
}
[renderCommandEncoder setFragmentTexture:currentTexture atIndex:0];
setCurrentColor(renderCommandEncoder, 0);
[renderCommandEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];
[renderCommandEncoder endEncoding];
lastWidthPixels = currentWidthPixels;
lastHeightPixels = currentHeightPixels;
lastText = currentText;
lastFontName = currentFontName;
lastFontSize = currentFontSize;
lastTextAlignment = currentTextAlignment;
}
void TextStimulus::computeTextureDimensions(double widthDegrees,
double heightDegrees,
std::size_t &widthPixels,
std::size_t &heightPixels) const
{
if (fullscreen) {
widthPixels = viewportWidth;
heightPixels = viewportHeight;
} else {
// Replace negative width or height with 0, and ensure that the texture
// contains at least one pixel
widthPixels = std::max(1.0, pixelsPerDegree * std::max(0.0, widthDegrees));
heightPixels = std::max(1.0, pixelsPerDegree * std::max(0.0, heightDegrees));
}
}
void TextStimulus::updateTexture(MetalDisplay &display) {
if (currentTexture &&
currentWidthPixels == lastWidthPixels &&
currentHeightPixels == lastHeightPixels &&
currentText == lastText &&
currentFontName == lastFontName &&
currentFontSize == lastFontSize &&
currentTextAlignment == lastTextAlignment)
{
// No relevant parameters have changed since we last generated the texture, so use
// the existing one
return;
}
//
// Clear the relevant portion of the context
//
// NOTE: By default, Core Graphics contexts place the origin in the lower left corner, whereas
// the origin for Metal textures is in the upper left. To simplify the texture coordinates used
// by Metal, we want to draw in the upper-left corner of the texture. This would be easier to
// do if we just flipped the coordinate system of the CGBitmapContext. Unfortunately, Core Text
// resists such flips and insists on making "up" be the direction of increasing y, meaning that
// text rendered into a y-flipped context is drawn with y flipped. Therefore, we just live with
// the slight annoyance of defining our drawing rectangle relative to Core Graphics' default,
// origin-at-lower-left coordinate system.
//
const auto rect = CGRectMake(0,
textureHeight - currentHeightPixels,
currentWidthPixels,
currentHeightPixels);
CGContextClearRect(context.get(), rect);
// Create the text string
auto attrString = cf::ObjectPtr<CFMutableAttributedStringRef>::created(CFAttributedStringCreateMutable(kCFAllocatorDefault, 0));
CFAttributedStringReplaceString(attrString.get(), CFRangeMake(0, 0), createCFString(currentText).get());
const auto fullRange = CFRangeMake(0, CFAttributedStringGetLength(attrString.get()));
// Set the font, converting size from points to pixels
auto font = cf::ObjectPtr<CTFontRef>::created(CTFontCreateWithName(createCFString(currentFontName).get(),
currentFontSize * pixelsPerPoint,
nullptr));
CFAttributedStringSetAttribute(attrString.get(), fullRange, kCTFontAttributeName, font.get());
// Set the text alignment
const CTTextAlignment alignment = textAlignmentFromName(currentTextAlignment);
const std::array<CTParagraphStyleSetting, 1> paragraphStyleSettings {
{ kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment }
};
auto paragraphStyle = cf::ObjectPtr<CTParagraphStyleRef>::created(CTParagraphStyleCreate(paragraphStyleSettings.data(),
paragraphStyleSettings.size()));
CFAttributedStringSetAttribute(attrString.get(), fullRange, kCTParagraphStyleAttributeName, paragraphStyle.get());
// Generate a Core Text frame
auto framesetter = cf::ObjectPtr<CTFramesetterRef>::created(CTFramesetterCreateWithAttributedString(attrString.get()));
auto path = cf::ObjectPtr<CGPathRef>::created(CGPathCreateWithRect(rect, nullptr));
auto frame = cf::ObjectPtr<CTFrameRef>::created(CTFramesetterCreateFrame(framesetter.get(),
CFRangeMake(0, 0),
path.get(),
nullptr));
// Draw the frame in the context
CTFrameDraw(frame.get(), context.get());
if (CTFrameGetVisibleStringRange(frame.get()).length != fullRange.length) {
mwarning(M_DISPLAY_MESSAGE_DOMAIN,
"Text for stimulus \"%s\" does not fit within the specified region and will be truncated",
getTag().c_str());
}
// Copy the texture data to the next-available texture from the pool
currentTexture = [texturePool acquireWithCommandBuffer:display.getCurrentMetalCommandBuffer()];
[currentTexture replaceRegion:MTLRegionMake2D(0, 0, currentWidthPixels, currentHeightPixels)
mipmapLevel:0
withBytes:textureData.get()
bytesPerRow:textureBytesPerRow];
}
END_NAMESPACE_MW
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop_proxy.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
#include "chrome/service/cloud_print/cloud_print_url_fetcher.h"
#include "chrome/service/service_process.h"
#include "googleurl/src/gurl.h"
#include "net/test/test_server.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"
#include "net/url_request/url_request_test_util.h"
#include "net/url_request/url_request_throttler_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
namespace {
const FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL("chrome/test/data");
int g_request_context_getter_instances = 0;
class TestURLRequestContextGetter : public net::URLRequestContextGetter {
public:
explicit TestURLRequestContextGetter(
base::MessageLoopProxy* io_message_loop_proxy)
: io_message_loop_proxy_(io_message_loop_proxy) {
g_request_context_getter_instances++;
}
virtual net::URLRequestContext* GetURLRequestContext() {
if (!context_)
context_ = new TestURLRequestContext();
return context_;
}
virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy() const {
return io_message_loop_proxy_;
}
protected:
scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
private:
~TestURLRequestContextGetter() {
g_request_context_getter_instances--;
}
scoped_refptr<net::URLRequestContext> context_;
};
class TestCloudPrintURLFetcher : public CloudPrintURLFetcher {
public:
explicit TestCloudPrintURLFetcher(
base::MessageLoopProxy* io_message_loop_proxy)
: io_message_loop_proxy_(io_message_loop_proxy) {
}
virtual net::URLRequestContextGetter* GetRequestContextGetter() {
return new TestURLRequestContextGetter(io_message_loop_proxy_.get());
}
private:
scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
};
class CloudPrintURLFetcherTest : public testing::Test,
public CloudPrintURLFetcherDelegate {
public:
CloudPrintURLFetcherTest() : max_retries_(0), fetcher_(NULL) { }
// Creates a URLFetcher, using the program's main thread to do IO.
virtual void CreateFetcher(const GURL& url, int max_retries);
// CloudPrintURLFetcher::Delegate
virtual CloudPrintURLFetcher::ResponseAction HandleRawResponse(
const URLFetcher* source,
const GURL& url,
const net::URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data);
virtual void OnRequestAuthError() {
ADD_FAILURE();
}
scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy() {
return io_message_loop_proxy_;
}
protected:
virtual void SetUp() {
testing::Test::SetUp();
io_message_loop_proxy_ = base::MessageLoopProxy::CreateForCurrentThread();
}
virtual void TearDown() {
fetcher_ = NULL;
// Deleting the fetcher causes a task to be posted to the IO thread to
// release references to the URLRequestContextGetter. We need to run all
// pending tasks to execute that (this is the IO thread).
MessageLoop::current()->RunAllPending();
EXPECT_EQ(0, g_request_context_getter_instances);
}
// URLFetcher is designed to run on the main UI thread, but in our tests
// we assume that the current thread is the IO thread where the URLFetcher
// dispatches its requests to. When we wish to simulate being used from
// a UI thread, we dispatch a worker thread to do so.
MessageLoopForIO io_loop_;
scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
int max_retries_;
Time start_time_;
scoped_refptr<CloudPrintURLFetcher> fetcher_;
};
class CloudPrintURLFetcherBasicTest : public CloudPrintURLFetcherTest {
public:
CloudPrintURLFetcherBasicTest()
: handle_raw_response_(false), handle_raw_data_(false) { }
// CloudPrintURLFetcher::Delegate
virtual CloudPrintURLFetcher::ResponseAction HandleRawResponse(
const URLFetcher* source,
const GURL& url,
const net::URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data);
virtual CloudPrintURLFetcher::ResponseAction HandleRawData(
const URLFetcher* source,
const GURL& url,
const std::string& data);
virtual CloudPrintURLFetcher::ResponseAction HandleJSONData(
const URLFetcher* source,
const GURL& url,
DictionaryValue* json_data,
bool succeeded);
void SetHandleRawResponse(bool handle_raw_response) {
handle_raw_response_ = handle_raw_response;
}
void SetHandleRawData(bool handle_raw_data) {
handle_raw_data_ = handle_raw_data;
}
private:
bool handle_raw_response_;
bool handle_raw_data_;
};
// Version of CloudPrintURLFetcherTest that tests overload protection.
class CloudPrintURLFetcherOverloadTest : public CloudPrintURLFetcherTest {
public:
CloudPrintURLFetcherOverloadTest() : response_count_(0) {
}
// CloudPrintURLFetcher::Delegate
virtual CloudPrintURLFetcher::ResponseAction HandleRawData(
const URLFetcher* source,
const GURL& url,
const std::string& data);
private:
int response_count_;
};
// Version of CloudPrintURLFetcherTest that tests backoff protection.
class CloudPrintURLFetcherRetryBackoffTest : public CloudPrintURLFetcherTest {
public:
CloudPrintURLFetcherRetryBackoffTest() : response_count_(0) {
}
// CloudPrintURLFetcher::Delegate
virtual CloudPrintURLFetcher::ResponseAction HandleRawData(
const URLFetcher* source,
const GURL& url,
const std::string& data);
virtual void OnRequestGiveUp();
private:
int response_count_;
};
void CloudPrintURLFetcherTest::CreateFetcher(const GURL& url, int max_retries) {
fetcher_ = new TestCloudPrintURLFetcher(io_message_loop_proxy());
max_retries_ = max_retries;
start_time_ = Time::Now();
fetcher_->StartGetRequest(url, this, "", max_retries_, std::string());
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherTest::HandleRawResponse(
const URLFetcher* source,
const GURL& url,
const net::URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data) {
EXPECT_TRUE(status.is_success());
EXPECT_EQ(200, response_code); // HTTP OK
EXPECT_FALSE(data.empty());
return CloudPrintURLFetcher::CONTINUE_PROCESSING;
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherBasicTest::HandleRawResponse(
const URLFetcher* source,
const GURL& url,
const net::URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data) {
EXPECT_TRUE(status.is_success());
EXPECT_EQ(200, response_code); // HTTP OK
EXPECT_FALSE(data.empty());
if (handle_raw_response_) {
// If the current message loop is not the IO loop, it will be shut down when
// the main loop returns and this thread subsequently goes out of scope.
io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
return CloudPrintURLFetcher::STOP_PROCESSING;
}
return CloudPrintURLFetcher::CONTINUE_PROCESSING;
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherBasicTest::HandleRawData(
const URLFetcher* source,
const GURL& url,
const std::string& data) {
// We should never get here if we returned true in HandleRawResponse
EXPECT_FALSE(handle_raw_response_);
if (handle_raw_data_) {
io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
return CloudPrintURLFetcher::STOP_PROCESSING;
}
return CloudPrintURLFetcher::CONTINUE_PROCESSING;
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherBasicTest::HandleJSONData(
const URLFetcher* source,
const GURL& url,
DictionaryValue* json_data,
bool succeeded) {
// We should never get here if we returned true in one of the above methods.
EXPECT_FALSE(handle_raw_response_);
EXPECT_FALSE(handle_raw_data_);
io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
return CloudPrintURLFetcher::STOP_PROCESSING;
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherOverloadTest::HandleRawData(const URLFetcher* source,
const GURL& url,
const std::string& data) {
const TimeDelta one_second = TimeDelta::FromMilliseconds(1000);
response_count_++;
if (response_count_ < 20) {
fetcher_->StartGetRequest(url, this, "", max_retries_, std::string());
} else {
// We have already sent 20 requests continuously. And we expect that
// it takes more than 1 second due to the overload protection settings.
EXPECT_TRUE(Time::Now() - start_time_ >= one_second);
io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
return CloudPrintURLFetcher::STOP_PROCESSING;
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherRetryBackoffTest::HandleRawData(const URLFetcher* source,
const GURL& url,
const std::string& data) {
response_count_++;
// First attempt + 11 retries = 12 total responses.
EXPECT_LE(response_count_, 12);
return CloudPrintURLFetcher::RETRY_REQUEST;
}
void CloudPrintURLFetcherRetryBackoffTest::OnRequestGiveUp() {
// It takes more than 200 ms to finish all 11 requests.
EXPECT_TRUE(Time::Now() - start_time_ >= TimeDelta::FromMilliseconds(200));
io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
// http://code.google.com/p/chromium/issues/detail?id=60426
TEST_F(CloudPrintURLFetcherBasicTest, FLAKY_HandleRawResponse) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
SetHandleRawResponse(true);
CreateFetcher(test_server.GetURL("echo"), 0);
MessageLoop::current()->Run();
}
// http://code.google.com/p/chromium/issues/detail?id=60426
TEST_F(CloudPrintURLFetcherBasicTest, FLAKY_HandleRawData) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
SetHandleRawData(true);
CreateFetcher(test_server.GetURL("echo"), 0);
MessageLoop::current()->Run();
}
TEST_F(CloudPrintURLFetcherOverloadTest, Protect) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
GURL url(test_server.GetURL("defaultresponse"));
// Registers an entry for test url. It only allows 3 requests to be sent
// in 200 milliseconds.
net::URLRequestThrottlerManager* manager =
net::URLRequestThrottlerManager::GetInstance();
scoped_refptr<net::URLRequestThrottlerEntry> entry(
new net::URLRequestThrottlerEntry(manager, 200, 3, 1, 2.0, 0.0, 256));
manager->OverrideEntryForTests(url, entry);
CreateFetcher(url, 11);
MessageLoop::current()->Run();
net::URLRequestThrottlerManager::GetInstance()->EraseEntryForTests(url);
}
// http://code.google.com/p/chromium/issues/detail?id=60426
TEST_F(CloudPrintURLFetcherRetryBackoffTest, FLAKY_GiveUp) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
GURL url(test_server.GetURL("defaultresponse"));
// Registers an entry for test url. The backoff time is calculated by:
// new_backoff = 2.0 * old_backoff + 0
// and maximum backoff time is 256 milliseconds.
// Maximum retries allowed is set to 11.
net::URLRequestThrottlerManager* manager =
net::URLRequestThrottlerManager::GetInstance();
scoped_refptr<net::URLRequestThrottlerEntry> entry(
new net::URLRequestThrottlerEntry(manager, 200, 3, 1, 2.0, 0.0, 256));
manager->OverrideEntryForTests(url, entry);
CreateFetcher(url, 11);
MessageLoop::current()->Run();
net::URLRequestThrottlerManager::GetInstance()->EraseEntryForTests(url);
}
} // namespace.
<commit_msg>Mark CloudPrintURLFetcherOverloadTest.Protect as flaky.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop_proxy.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
#include "chrome/service/cloud_print/cloud_print_url_fetcher.h"
#include "chrome/service/service_process.h"
#include "googleurl/src/gurl.h"
#include "net/test/test_server.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"
#include "net/url_request/url_request_test_util.h"
#include "net/url_request/url_request_throttler_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
namespace {
const FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL("chrome/test/data");
int g_request_context_getter_instances = 0;
class TestURLRequestContextGetter : public net::URLRequestContextGetter {
public:
explicit TestURLRequestContextGetter(
base::MessageLoopProxy* io_message_loop_proxy)
: io_message_loop_proxy_(io_message_loop_proxy) {
g_request_context_getter_instances++;
}
virtual net::URLRequestContext* GetURLRequestContext() {
if (!context_)
context_ = new TestURLRequestContext();
return context_;
}
virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy() const {
return io_message_loop_proxy_;
}
protected:
scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
private:
~TestURLRequestContextGetter() {
g_request_context_getter_instances--;
}
scoped_refptr<net::URLRequestContext> context_;
};
class TestCloudPrintURLFetcher : public CloudPrintURLFetcher {
public:
explicit TestCloudPrintURLFetcher(
base::MessageLoopProxy* io_message_loop_proxy)
: io_message_loop_proxy_(io_message_loop_proxy) {
}
virtual net::URLRequestContextGetter* GetRequestContextGetter() {
return new TestURLRequestContextGetter(io_message_loop_proxy_.get());
}
private:
scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
};
class CloudPrintURLFetcherTest : public testing::Test,
public CloudPrintURLFetcherDelegate {
public:
CloudPrintURLFetcherTest() : max_retries_(0), fetcher_(NULL) { }
// Creates a URLFetcher, using the program's main thread to do IO.
virtual void CreateFetcher(const GURL& url, int max_retries);
// CloudPrintURLFetcher::Delegate
virtual CloudPrintURLFetcher::ResponseAction HandleRawResponse(
const URLFetcher* source,
const GURL& url,
const net::URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data);
virtual void OnRequestAuthError() {
ADD_FAILURE();
}
scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy() {
return io_message_loop_proxy_;
}
protected:
virtual void SetUp() {
testing::Test::SetUp();
io_message_loop_proxy_ = base::MessageLoopProxy::CreateForCurrentThread();
}
virtual void TearDown() {
fetcher_ = NULL;
// Deleting the fetcher causes a task to be posted to the IO thread to
// release references to the URLRequestContextGetter. We need to run all
// pending tasks to execute that (this is the IO thread).
MessageLoop::current()->RunAllPending();
EXPECT_EQ(0, g_request_context_getter_instances);
}
// URLFetcher is designed to run on the main UI thread, but in our tests
// we assume that the current thread is the IO thread where the URLFetcher
// dispatches its requests to. When we wish to simulate being used from
// a UI thread, we dispatch a worker thread to do so.
MessageLoopForIO io_loop_;
scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
int max_retries_;
Time start_time_;
scoped_refptr<CloudPrintURLFetcher> fetcher_;
};
class CloudPrintURLFetcherBasicTest : public CloudPrintURLFetcherTest {
public:
CloudPrintURLFetcherBasicTest()
: handle_raw_response_(false), handle_raw_data_(false) { }
// CloudPrintURLFetcher::Delegate
virtual CloudPrintURLFetcher::ResponseAction HandleRawResponse(
const URLFetcher* source,
const GURL& url,
const net::URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data);
virtual CloudPrintURLFetcher::ResponseAction HandleRawData(
const URLFetcher* source,
const GURL& url,
const std::string& data);
virtual CloudPrintURLFetcher::ResponseAction HandleJSONData(
const URLFetcher* source,
const GURL& url,
DictionaryValue* json_data,
bool succeeded);
void SetHandleRawResponse(bool handle_raw_response) {
handle_raw_response_ = handle_raw_response;
}
void SetHandleRawData(bool handle_raw_data) {
handle_raw_data_ = handle_raw_data;
}
private:
bool handle_raw_response_;
bool handle_raw_data_;
};
// Version of CloudPrintURLFetcherTest that tests overload protection.
class CloudPrintURLFetcherOverloadTest : public CloudPrintURLFetcherTest {
public:
CloudPrintURLFetcherOverloadTest() : response_count_(0) {
}
// CloudPrintURLFetcher::Delegate
virtual CloudPrintURLFetcher::ResponseAction HandleRawData(
const URLFetcher* source,
const GURL& url,
const std::string& data);
private:
int response_count_;
};
// Version of CloudPrintURLFetcherTest that tests backoff protection.
class CloudPrintURLFetcherRetryBackoffTest : public CloudPrintURLFetcherTest {
public:
CloudPrintURLFetcherRetryBackoffTest() : response_count_(0) {
}
// CloudPrintURLFetcher::Delegate
virtual CloudPrintURLFetcher::ResponseAction HandleRawData(
const URLFetcher* source,
const GURL& url,
const std::string& data);
virtual void OnRequestGiveUp();
private:
int response_count_;
};
void CloudPrintURLFetcherTest::CreateFetcher(const GURL& url, int max_retries) {
fetcher_ = new TestCloudPrintURLFetcher(io_message_loop_proxy());
max_retries_ = max_retries;
start_time_ = Time::Now();
fetcher_->StartGetRequest(url, this, "", max_retries_, std::string());
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherTest::HandleRawResponse(
const URLFetcher* source,
const GURL& url,
const net::URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data) {
EXPECT_TRUE(status.is_success());
EXPECT_EQ(200, response_code); // HTTP OK
EXPECT_FALSE(data.empty());
return CloudPrintURLFetcher::CONTINUE_PROCESSING;
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherBasicTest::HandleRawResponse(
const URLFetcher* source,
const GURL& url,
const net::URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data) {
EXPECT_TRUE(status.is_success());
EXPECT_EQ(200, response_code); // HTTP OK
EXPECT_FALSE(data.empty());
if (handle_raw_response_) {
// If the current message loop is not the IO loop, it will be shut down when
// the main loop returns and this thread subsequently goes out of scope.
io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
return CloudPrintURLFetcher::STOP_PROCESSING;
}
return CloudPrintURLFetcher::CONTINUE_PROCESSING;
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherBasicTest::HandleRawData(
const URLFetcher* source,
const GURL& url,
const std::string& data) {
// We should never get here if we returned true in HandleRawResponse
EXPECT_FALSE(handle_raw_response_);
if (handle_raw_data_) {
io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
return CloudPrintURLFetcher::STOP_PROCESSING;
}
return CloudPrintURLFetcher::CONTINUE_PROCESSING;
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherBasicTest::HandleJSONData(
const URLFetcher* source,
const GURL& url,
DictionaryValue* json_data,
bool succeeded) {
// We should never get here if we returned true in one of the above methods.
EXPECT_FALSE(handle_raw_response_);
EXPECT_FALSE(handle_raw_data_);
io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
return CloudPrintURLFetcher::STOP_PROCESSING;
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherOverloadTest::HandleRawData(const URLFetcher* source,
const GURL& url,
const std::string& data) {
const TimeDelta one_second = TimeDelta::FromMilliseconds(1000);
response_count_++;
if (response_count_ < 20) {
fetcher_->StartGetRequest(url, this, "", max_retries_, std::string());
} else {
// We have already sent 20 requests continuously. And we expect that
// it takes more than 1 second due to the overload protection settings.
EXPECT_TRUE(Time::Now() - start_time_ >= one_second);
io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
return CloudPrintURLFetcher::STOP_PROCESSING;
}
CloudPrintURLFetcher::ResponseAction
CloudPrintURLFetcherRetryBackoffTest::HandleRawData(const URLFetcher* source,
const GURL& url,
const std::string& data) {
response_count_++;
// First attempt + 11 retries = 12 total responses.
EXPECT_LE(response_count_, 12);
return CloudPrintURLFetcher::RETRY_REQUEST;
}
void CloudPrintURLFetcherRetryBackoffTest::OnRequestGiveUp() {
// It takes more than 200 ms to finish all 11 requests.
EXPECT_TRUE(Time::Now() - start_time_ >= TimeDelta::FromMilliseconds(200));
io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
// http://code.google.com/p/chromium/issues/detail?id=60426
TEST_F(CloudPrintURLFetcherBasicTest, FLAKY_HandleRawResponse) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
SetHandleRawResponse(true);
CreateFetcher(test_server.GetURL("echo"), 0);
MessageLoop::current()->Run();
}
// http://code.google.com/p/chromium/issues/detail?id=60426
TEST_F(CloudPrintURLFetcherBasicTest, FLAKY_HandleRawData) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
SetHandleRawData(true);
CreateFetcher(test_server.GetURL("echo"), 0);
MessageLoop::current()->Run();
}
// http://code.google.com/p/chromium/issues/detail?id=78440
TEST_F(CloudPrintURLFetcherOverloadTest, FLAKY_Protect) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
GURL url(test_server.GetURL("defaultresponse"));
// Registers an entry for test url. It only allows 3 requests to be sent
// in 200 milliseconds.
net::URLRequestThrottlerManager* manager =
net::URLRequestThrottlerManager::GetInstance();
scoped_refptr<net::URLRequestThrottlerEntry> entry(
new net::URLRequestThrottlerEntry(manager, 200, 3, 1, 2.0, 0.0, 256));
manager->OverrideEntryForTests(url, entry);
CreateFetcher(url, 11);
MessageLoop::current()->Run();
net::URLRequestThrottlerManager::GetInstance()->EraseEntryForTests(url);
}
// http://code.google.com/p/chromium/issues/detail?id=60426
TEST_F(CloudPrintURLFetcherRetryBackoffTest, FLAKY_GiveUp) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
GURL url(test_server.GetURL("defaultresponse"));
// Registers an entry for test url. The backoff time is calculated by:
// new_backoff = 2.0 * old_backoff + 0
// and maximum backoff time is 256 milliseconds.
// Maximum retries allowed is set to 11.
net::URLRequestThrottlerManager* manager =
net::URLRequestThrottlerManager::GetInstance();
scoped_refptr<net::URLRequestThrottlerEntry> entry(
new net::URLRequestThrottlerEntry(manager, 200, 3, 1, 2.0, 0.0, 256));
manager->OverrideEntryForTests(url, entry);
CreateFetcher(url, 11);
MessageLoop::current()->Run();
net::URLRequestThrottlerManager::GetInstance()->EraseEntryForTests(url);
}
} // namespace.
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file Port object definitions.
*/
#include "base/chunk_generator.hh"
#include "mem/port.hh"
void
Port::blobHelper(Addr addr, uint8_t *p, int size, Command cmd)
{
Request req;
Packet pkt;
pkt.req = &req;
pkt.cmd = cmd;
for (ChunkGenerator gen(addr, size, peerBlockSize());
!gen.done(); gen.next()) {
pkt.addr = req.paddr = gen.addr();
pkt.size = req.size = gen.size();
pkt.data = p;
sendFunctional(pkt);
p += gen.size();
}
}
void
Port::writeBlobFunctional(Addr addr, uint8_t *p, int size)
{
blobHelper(addr, p, size, Write);
}
void
Port::readBlobFunctional(Addr addr, uint8_t *p, int size)
{
blobHelper(addr, p, size, Read);
}
void
Port::memsetBlobFunctional(Addr addr, uint8_t val, int size)
{
// quick and dirty...
uint8_t *buf = new uint8_t[size];
memset(buf, val, size);
blobHelper(addr, buf, size, Write);
}
<commit_msg>Fix memory allocation error in Port::memsetBlobFunctional.<commit_after>/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file Port object definitions.
*/
#include "base/chunk_generator.hh"
#include "mem/port.hh"
void
Port::blobHelper(Addr addr, uint8_t *p, int size, Command cmd)
{
Request req;
Packet pkt;
pkt.req = &req;
pkt.cmd = cmd;
for (ChunkGenerator gen(addr, size, peerBlockSize());
!gen.done(); gen.next()) {
pkt.addr = req.paddr = gen.addr();
pkt.size = req.size = gen.size();
pkt.data = p;
sendFunctional(pkt);
p += gen.size();
}
}
void
Port::writeBlobFunctional(Addr addr, uint8_t *p, int size)
{
blobHelper(addr, p, size, Write);
}
void
Port::readBlobFunctional(Addr addr, uint8_t *p, int size)
{
blobHelper(addr, p, size, Read);
}
void
Port::memsetBlobFunctional(Addr addr, uint8_t val, int size)
{
// quick and dirty...
uint8_t *buf = new uint8_t[size];
memset(buf, val, size);
blobHelper(addr, buf, size, Write);
delete buf;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 "src/clients/c++/request.h"
#include <unistd.h>
#include <iostream>
#include <string>
#include <vector>
namespace ni = nvidia::inferenceserver;
namespace nic = nvidia::inferenceserver::client;
#define FAIL_IF_ERR(X, MSG) \
{ \
nic::Error err = (X); \
if (!err.IsOk()) { \
std::cerr << "error: " << (MSG) << ": " << err << std::endl; \
exit(1); \
} \
}
namespace {
void
Usage(char** argv, const std::string& msg = std::string())
{
if (!msg.empty()) {
std::cerr << "error: " << msg << std::endl;
}
std::cerr << "Usage: " << argv[0] << " [options]" << std::endl;
std::cerr << "\t-v" << std::endl;
std::cerr << "\t-r" << std::endl;
std::cerr << "\t-a" << std::endl;
std::cerr << "\t-u <URL for inference service and its gRPC port>"
<< std::endl;
std::cerr << std::endl;
std::cerr << "For -r, the client will run non-streaming context first."
<< std::endl;
std::cerr << "For -a, the client will send asynchronous requests."
<< std::endl;
exit(1);
}
int32_t
Send(
const std::unique_ptr<nic::InferContext>& ctx, int32_t value,
bool start_of_sequence = false, bool end_of_sequence = false)
{
// Set the context options to do batch-size 1 requests. Also request
// that all output tensors be returned.
std::unique_ptr<nic::InferContext::Options> options;
FAIL_IF_ERR(
nic::InferContext::Options::Create(&options),
"unable to create inference options");
options->SetFlags(0);
if (start_of_sequence) {
options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_START, true);
}
if (end_of_sequence) {
options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_END, true);
}
options->SetBatchSize(1);
for (const auto& output : ctx->Outputs()) {
options->AddRawResult(output);
}
FAIL_IF_ERR(ctx->SetRunOptions(*options), "unable to set context 0 options");
// Initialize the inputs with the data.
std::shared_ptr<nic::InferContext::Input> ivalue;
FAIL_IF_ERR(ctx->GetInput("INPUT", &ivalue), "unable to get INPUT");
FAIL_IF_ERR(ivalue->Reset(), "unable to reset INPUT");
FAIL_IF_ERR(
ivalue->SetRaw(reinterpret_cast<uint8_t*>(&value), sizeof(int32_t)),
"unable to set data for INPUT");
// Send inference request to the inference server.
std::map<std::string, std::unique_ptr<nic::InferContext::Result>> results;
FAIL_IF_ERR(ctx->Run(&results), "unable to run model");
// We expect there to be 1 result value, return it...
if (results.size() != 1) {
std::cerr << "error: expected 1 result, got " << results.size()
<< std::endl;
}
int32_t r = 0;
FAIL_IF_ERR(
results["OUTPUT"]->GetRawAtCursor(0 /* batch idx */, &r),
"unable to get OUTPUT result");
return r;
}
std::shared_ptr<nic::InferContext::Request>
AsyncSend(
const std::unique_ptr<nic::InferContext>& ctx, int32_t value,
bool start_of_sequence = false, bool end_of_sequence = false)
{
std::shared_ptr<nic::InferContext::Request> request;
// Set the context options to do batch-size 1 requests. Also request
// that all output tensors be returned.
std::unique_ptr<nic::InferContext::Options> options;
FAIL_IF_ERR(
nic::InferContext::Options::Create(&options),
"unable to create inference options");
options->SetFlags(0);
if (start_of_sequence) {
options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_START, true);
}
if (end_of_sequence) {
options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_END, true);
}
options->SetBatchSize(1);
for (const auto& output : ctx->Outputs()) {
options->AddRawResult(output);
}
FAIL_IF_ERR(ctx->SetRunOptions(*options), "unable to set context 0 options");
// Initialize the inputs with the data.
std::shared_ptr<nic::InferContext::Input> ivalue;
FAIL_IF_ERR(ctx->GetInput("INPUT", &ivalue), "unable to get INPUT");
FAIL_IF_ERR(ivalue->Reset(), "unable to reset INPUT");
FAIL_IF_ERR(
ivalue->SetRaw(reinterpret_cast<uint8_t*>(&value), sizeof(int32_t)),
"unable to set data for INPUT");
// Send inference request to the inference server.
FAIL_IF_ERR(ctx->AsyncRun(&request), "unable to run model");
return std::move(request);
}
int32_t
AsyncReceive(
const std::unique_ptr<nic::InferContext>& ctx,
std::shared_ptr<nic::InferContext::Request> request)
{
// Retrieve result of the inference request from the inference server.
std::map<std::string, std::unique_ptr<nic::InferContext::Result>> results;
FAIL_IF_ERR(
ctx->GetAsyncRunResults(&results, request, true),
"unable to get results");
// We expect there to be 1 result value, return it...
if (results.size() != 1) {
std::cerr << "error: expected 1 result, got " << results.size()
<< std::endl;
}
int32_t r = 0;
FAIL_IF_ERR(
results["OUTPUT"]->GetRawAtCursor(0 /* batch idx */, &r),
"unable to get OUTPUT result");
return r;
}
} // namespace
int
main(int argc, char** argv)
{
bool verbose = false;
bool async = false;
bool reverse = false;
std::string url("localhost:8001");
std::string protocol = "grpc";
// Parse commandline...
int opt;
while ((opt = getopt(argc, argv, "vrau:")) != -1) {
switch (opt) {
case 'v':
verbose = true;
break;
case 'r':
reverse = true;
break;
case 'a':
async = true;
break;
case 'u':
url = optarg;
break;
case '?':
Usage(argv);
break;
}
}
nic::Error err;
// We use the custom "sequence" model which takes 1 input value. The
// output is the accumulated value of the inputs. See
// src/custom/sequence.
std::string model_name = "simple_sequence";
// Create 2 inference context with different correlation ID. We will
// use these to send to sequences of inference requests. Must use a
// non-zero correlation ID since zero indicates no correlation ID.
std::unique_ptr<nic::InferContext> ctx0, ctx1;
const ni::CorrelationID correlation_id0 = 1;
const ni::CorrelationID correlation_id1 = 2;
// Create two different contexts, one is using streaming while the other
// isn't. Then we can compare their difference in sync/async runs
err = nic::InferGrpcStreamContext::Create(
&ctx0, correlation_id0, url, model_name, -1 /* model_version */, verbose);
if (err.IsOk()) {
err = nic::InferGrpcContext::Create(
&ctx1, correlation_id1, url, model_name, -1 /* model_version */,
verbose);
}
if (!err.IsOk()) {
std::cerr << "error: unable to create inference contexts: " << err
<< std::endl;
exit(1);
}
// Now send the inference sequences..
//
std::vector<int32_t> values{11, 7, 5, 3, 2, 0, 1};
std::vector<int32_t> result0_list;
std::vector<int32_t> result1_list;
std::vector<std::unique_ptr<nic::InferContext>> ctxs;
if (!reverse) {
ctxs.emplace_back(std::move(ctx0));
ctxs.emplace_back(std::move(ctx1));
} else {
ctxs.emplace_back(std::move(ctx1));
ctxs.emplace_back(std::move(ctx0));
}
if (async) {
std::vector<std::shared_ptr<nic::InferContext::Request>> request0_list;
std::vector<std::shared_ptr<nic::InferContext::Request>> request1_list;
// Send requests, first reset accumulator for the sequence.
request0_list.emplace_back(
AsyncSend(ctxs[0], 0, true /* start-of-sequence */));
request1_list.emplace_back(
AsyncSend(ctxs[1], 100, true /* start-of-sequence */));
// Now send a sequence of values...
for (int32_t v : values) {
request0_list.emplace_back(AsyncSend(
ctxs[0], v, false /* start-of-sequence */,
(v == 1) /* end-of-sequence */));
request1_list.emplace_back(AsyncSend(
ctxs[1], -v, false /* start-of-sequence */,
(v == 1) /* end-of-sequence */));
}
// Get results
for (size_t i = 0; i < request0_list.size(); i++) {
result0_list.push_back(AsyncReceive(ctxs[0], request0_list[i]));
}
for (size_t i = 0; i < request1_list.size(); i++) {
result1_list.push_back(AsyncReceive(ctxs[1], request1_list[i]));
}
} else {
// Send requests, first reset accumulator for the sequence.
result0_list.push_back(Send(ctxs[0], 0, true /* start-of-sequence */));
result1_list.push_back(Send(ctxs[1], 100, true /* start-of-sequence */));
// Now send a sequence of values...
for (int32_t v : values) {
result0_list.push_back(Send(
ctxs[0], v, false /* start-of-sequence */,
(v == 1) /* end-of-sequence */));
result1_list.push_back(Send(
ctxs[1], -v, false /* start-of-sequence */,
(v == 1) /* end-of-sequence */));
}
}
if (!reverse) {
std::cout << "streaming : non-streaming" << std::endl;
} else {
std::cout << "non-streaming : streaming" << std::endl;
}
int32_t seq0_expected = 0;
int32_t seq1_expected = 100;
for (size_t i = 0; i < result0_list.size(); i++) {
std::cout << "[" << i << "] " << result0_list[i] << " : " << result1_list[i]
<< std::endl;
if ((seq0_expected != result0_list[i]) ||
(seq0_expected != result0_list[i])) {
std::cout << "[ expected ] " << seq0_expected << " : " << seq1_expected
<< std::endl;
return 1;
}
if (i < values.size()) {
seq0_expected += values[i];
seq1_expected -= values[i];
}
}
return 0;
}
<commit_msg>Fix typo in example sequence client<commit_after>// Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 "src/clients/c++/request.h"
#include <unistd.h>
#include <iostream>
#include <string>
#include <vector>
namespace ni = nvidia::inferenceserver;
namespace nic = nvidia::inferenceserver::client;
#define FAIL_IF_ERR(X, MSG) \
{ \
nic::Error err = (X); \
if (!err.IsOk()) { \
std::cerr << "error: " << (MSG) << ": " << err << std::endl; \
exit(1); \
} \
}
namespace {
void
Usage(char** argv, const std::string& msg = std::string())
{
if (!msg.empty()) {
std::cerr << "error: " << msg << std::endl;
}
std::cerr << "Usage: " << argv[0] << " [options]" << std::endl;
std::cerr << "\t-v" << std::endl;
std::cerr << "\t-r" << std::endl;
std::cerr << "\t-a" << std::endl;
std::cerr << "\t-u <URL for inference service and its gRPC port>"
<< std::endl;
std::cerr << std::endl;
std::cerr << "For -r, the client will run non-streaming context first."
<< std::endl;
std::cerr << "For -a, the client will send asynchronous requests."
<< std::endl;
exit(1);
}
int32_t
Send(
const std::unique_ptr<nic::InferContext>& ctx, int32_t value,
bool start_of_sequence = false, bool end_of_sequence = false)
{
// Set the context options to do batch-size 1 requests. Also request
// that all output tensors be returned.
std::unique_ptr<nic::InferContext::Options> options;
FAIL_IF_ERR(
nic::InferContext::Options::Create(&options),
"unable to create inference options");
options->SetFlags(0);
if (start_of_sequence) {
options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_START, true);
}
if (end_of_sequence) {
options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_END, true);
}
options->SetBatchSize(1);
for (const auto& output : ctx->Outputs()) {
options->AddRawResult(output);
}
FAIL_IF_ERR(ctx->SetRunOptions(*options), "unable to set context 0 options");
// Initialize the inputs with the data.
std::shared_ptr<nic::InferContext::Input> ivalue;
FAIL_IF_ERR(ctx->GetInput("INPUT", &ivalue), "unable to get INPUT");
FAIL_IF_ERR(ivalue->Reset(), "unable to reset INPUT");
FAIL_IF_ERR(
ivalue->SetRaw(reinterpret_cast<uint8_t*>(&value), sizeof(int32_t)),
"unable to set data for INPUT");
// Send inference request to the inference server.
std::map<std::string, std::unique_ptr<nic::InferContext::Result>> results;
FAIL_IF_ERR(ctx->Run(&results), "unable to run model");
// We expect there to be 1 result value, return it...
if (results.size() != 1) {
std::cerr << "error: expected 1 result, got " << results.size()
<< std::endl;
}
int32_t r = 0;
FAIL_IF_ERR(
results["OUTPUT"]->GetRawAtCursor(0 /* batch idx */, &r),
"unable to get OUTPUT result");
return r;
}
std::shared_ptr<nic::InferContext::Request>
AsyncSend(
const std::unique_ptr<nic::InferContext>& ctx, int32_t value,
bool start_of_sequence = false, bool end_of_sequence = false)
{
std::shared_ptr<nic::InferContext::Request> request;
// Set the context options to do batch-size 1 requests. Also request
// that all output tensors be returned.
std::unique_ptr<nic::InferContext::Options> options;
FAIL_IF_ERR(
nic::InferContext::Options::Create(&options),
"unable to create inference options");
options->SetFlags(0);
if (start_of_sequence) {
options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_START, true);
}
if (end_of_sequence) {
options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_END, true);
}
options->SetBatchSize(1);
for (const auto& output : ctx->Outputs()) {
options->AddRawResult(output);
}
FAIL_IF_ERR(ctx->SetRunOptions(*options), "unable to set context 0 options");
// Initialize the inputs with the data.
std::shared_ptr<nic::InferContext::Input> ivalue;
FAIL_IF_ERR(ctx->GetInput("INPUT", &ivalue), "unable to get INPUT");
FAIL_IF_ERR(ivalue->Reset(), "unable to reset INPUT");
FAIL_IF_ERR(
ivalue->SetRaw(reinterpret_cast<uint8_t*>(&value), sizeof(int32_t)),
"unable to set data for INPUT");
// Send inference request to the inference server.
FAIL_IF_ERR(ctx->AsyncRun(&request), "unable to run model");
return std::move(request);
}
int32_t
AsyncReceive(
const std::unique_ptr<nic::InferContext>& ctx,
std::shared_ptr<nic::InferContext::Request> request)
{
// Retrieve result of the inference request from the inference server.
std::map<std::string, std::unique_ptr<nic::InferContext::Result>> results;
FAIL_IF_ERR(
ctx->GetAsyncRunResults(&results, request, true),
"unable to get results");
// We expect there to be 1 result value, return it...
if (results.size() != 1) {
std::cerr << "error: expected 1 result, got " << results.size()
<< std::endl;
}
int32_t r = 0;
FAIL_IF_ERR(
results["OUTPUT"]->GetRawAtCursor(0 /* batch idx */, &r),
"unable to get OUTPUT result");
return r;
}
} // namespace
int
main(int argc, char** argv)
{
bool verbose = false;
bool async = false;
bool reverse = false;
std::string url("localhost:8001");
std::string protocol = "grpc";
// Parse commandline...
int opt;
while ((opt = getopt(argc, argv, "vrau:")) != -1) {
switch (opt) {
case 'v':
verbose = true;
break;
case 'r':
reverse = true;
break;
case 'a':
async = true;
break;
case 'u':
url = optarg;
break;
case '?':
Usage(argv);
break;
}
}
nic::Error err;
// We use the custom "sequence" model which takes 1 input value. The
// output is the accumulated value of the inputs. See
// src/custom/sequence.
std::string model_name = "simple_sequence";
// Create 2 inference context with different correlation ID. We will
// use these to send to sequences of inference requests. Must use a
// non-zero correlation ID since zero indicates no correlation ID.
std::unique_ptr<nic::InferContext> ctx0, ctx1;
const ni::CorrelationID correlation_id0 = 1;
const ni::CorrelationID correlation_id1 = 2;
// Create two different contexts, one is using streaming while the other
// isn't. Then we can compare their difference in sync/async runs
err = nic::InferGrpcStreamContext::Create(
&ctx0, correlation_id0, url, model_name, -1 /* model_version */, verbose);
if (err.IsOk()) {
err = nic::InferGrpcContext::Create(
&ctx1, correlation_id1, url, model_name, -1 /* model_version */,
verbose);
}
if (!err.IsOk()) {
std::cerr << "error: unable to create inference contexts: " << err
<< std::endl;
exit(1);
}
// Now send the inference sequences..
//
std::vector<int32_t> values{11, 7, 5, 3, 2, 0, 1};
std::vector<int32_t> result0_list;
std::vector<int32_t> result1_list;
std::vector<std::unique_ptr<nic::InferContext>> ctxs;
if (!reverse) {
ctxs.emplace_back(std::move(ctx0));
ctxs.emplace_back(std::move(ctx1));
} else {
ctxs.emplace_back(std::move(ctx1));
ctxs.emplace_back(std::move(ctx0));
}
if (async) {
std::vector<std::shared_ptr<nic::InferContext::Request>> request0_list;
std::vector<std::shared_ptr<nic::InferContext::Request>> request1_list;
// Send requests, first reset accumulator for the sequence.
request0_list.emplace_back(
AsyncSend(ctxs[0], 0, true /* start-of-sequence */));
request1_list.emplace_back(
AsyncSend(ctxs[1], 100, true /* start-of-sequence */));
// Now send a sequence of values...
for (int32_t v : values) {
request0_list.emplace_back(AsyncSend(
ctxs[0], v, false /* start-of-sequence */,
(v == 1) /* end-of-sequence */));
request1_list.emplace_back(AsyncSend(
ctxs[1], -v, false /* start-of-sequence */,
(v == 1) /* end-of-sequence */));
}
// Get results
for (size_t i = 0; i < request0_list.size(); i++) {
result0_list.push_back(AsyncReceive(ctxs[0], request0_list[i]));
}
for (size_t i = 0; i < request1_list.size(); i++) {
result1_list.push_back(AsyncReceive(ctxs[1], request1_list[i]));
}
} else {
// Send requests, first reset accumulator for the sequence.
result0_list.push_back(Send(ctxs[0], 0, true /* start-of-sequence */));
result1_list.push_back(Send(ctxs[1], 100, true /* start-of-sequence */));
// Now send a sequence of values...
for (int32_t v : values) {
result0_list.push_back(Send(
ctxs[0], v, false /* start-of-sequence */,
(v == 1) /* end-of-sequence */));
result1_list.push_back(Send(
ctxs[1], -v, false /* start-of-sequence */,
(v == 1) /* end-of-sequence */));
}
}
if (!reverse) {
std::cout << "streaming : non-streaming" << std::endl;
} else {
std::cout << "non-streaming : streaming" << std::endl;
}
int32_t seq0_expected = 0;
int32_t seq1_expected = 100;
for (size_t i = 0; i < result0_list.size(); i++) {
std::cout << "[" << i << "] " << result0_list[i] << " : " << result1_list[i]
<< std::endl;
if ((seq0_expected != result0_list[i]) ||
(seq1_expected != result1_list[i])) {
std::cout << "[ expected ] " << seq0_expected << " : " << seq1_expected
<< std::endl;
return 1;
}
if (i < values.size()) {
seq0_expected += values[i];
seq1_expected -= values[i];
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "views/session_view.h"
SessionView::SessionView(Session* session, QWidget* parent)
: QWidget(parent),
m_session(session)
{
m_hostBrowser = new HostBrowser;
m_ds3Browser = new DS3Browser(m_session);
m_splitter = new QSplitter;
m_splitter->addWidget(m_hostBrowser);
m_splitter->addWidget(m_ds3Browser);
m_topLayout = new QVBoxLayout(this);
m_topLayout->setContentsMargins(5, 5, 5, 5);
m_topLayout->addWidget(m_splitter);
setLayout(m_topLayout);
}
SessionView::~SessionView()
{
delete m_session;
}
<commit_msg>Don't let users collapse the host or DS3 browsers (by dragging the splitter bar all the one to one side or the other).<commit_after>#include "views/session_view.h"
SessionView::SessionView(Session* session, QWidget* parent)
: QWidget(parent),
m_session(session)
{
m_hostBrowser = new HostBrowser;
m_ds3Browser = new DS3Browser(m_session);
m_splitter = new QSplitter;
m_splitter->addWidget(m_hostBrowser);
m_splitter->addWidget(m_ds3Browser);
m_splitter->setCollapsible(0, false);
m_splitter->setCollapsible(1, false);
m_topLayout = new QVBoxLayout(this);
m_topLayout->setContentsMargins(5, 5, 5, 5);
m_topLayout->addWidget(m_splitter);
setLayout(m_topLayout);
}
SessionView::~SessionView()
{
delete m_session;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 The Gulden developers
// Authored by: Willem de Jonge ([email protected])
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#include "spvscanner.h"
#include "../net_processing.h"
#include "timedata.h"
#include "../validation/validation.h"
#include "wallet.h"
#include <algorithm>
// Maximum number of requests pending. This number should be high enough so that
// the requests can be reasonably distributed over our peers.
const int MAX_PENDING_REQUESTS = 512;
// Duration (seconds) of longest fork that can be handled
const int64_t MAX_FORK_DURATION = 1 * 12 * 3600;
// Persisting wallet db updates are limited as they are very expensive
// and updating at every processed block would give very poor performance.
// Therefore the state is only written to the db when a minimum time interval has passed,
// or a certain of number of blocks have been processed (whichever comes first).
// Note that due to this some blocks might be re-processed in case of abnormal termination,
// this is fine.
// Interval in seconds for writing the scan progress to the wallet db
const int64_t PERSIST_INTERVAL_SEC = 5;
// Blocks count after which scan processing state is written to the db.
const int PERSIST_BLOCK_COUNT = 500;
// limit UI update notifications (except when catched up)
const int UI_UPDATE_LIMIT = 50;
CSPVScanner::CSPVScanner(CWallet& _wallet) :
wallet(_wallet),
startTime(0),
lastProcessed(nullptr),
lastPersistTime(0)
{
LOCK(cs_main);
// init scan starting time to birth of first key
startTime = wallet.nTimeFirstKey;
// forward scan starting time to last block processed if available
CWalletDB walletdb(*wallet.dbw);
CBlockLocator locator;
int64_t lastBlockTime;
if (walletdb.ReadLastSPVBlockProcessed(locator, lastBlockTime))
startTime = lastBlockTime;
// rewind scan starting time by maximum handled fork duration
startTime = std::max(Params().GenesisBlock().GetBlockTime(), startTime - MAX_FORK_DURATION);
}
CSPVScanner::~CSPVScanner()
{
}
bool CSPVScanner::StartScan()
{
return StartPartialHeaders(startTime, std::bind(&CSPVScanner::HeaderTipChanged, this, std::placeholders::_1));
}
const CBlockIndex* CSPVScanner::LastBlockProcessed() const
{
return lastProcessed;
}
void CSPVScanner::RequestBlocks()
{
LOCK2(cs_main, wallet.cs_wallet);
// put lastProcessed and/or requestTip back on chain if forked
while (!partialChain.Contains(requestTip)) {
if (requestTip->nHeight > lastProcessed->nHeight) {
CancelPriorityDownload(requestTip, std::bind(&CSPVScanner::ProcessPriorityRequest, this, std::placeholders::_1, std::placeholders::_2));
requestTip = requestTip->pprev;
}
else { // so here requestTip == lastProcessed
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
if (ReadBlockFromDisk(*pblock, lastProcessed, Params())) {
wallet.BlockDisconnected(pblock);
}
else {
// This block must be on disk, it was processed before.
// So pruning has to keep at least as many blocks back as the longest fork we are willing to handle.
assert(false);
}
UpdateLastProcessed(lastProcessed->pprev);
requestTip = lastProcessed;
}
}
// skip blocks that are before startTime
const CBlockIndex* skip = lastProcessed;
while (skip->GetBlockTime() < startTime && partialChain.Height() > skip->nHeight)
skip = partialChain.Next(skip);
if (skip != lastProcessed) {
LogPrint(BCLog::WALLET, "Skipping %d old blocks for SPV scan, up to height %d\n", skip->nHeight - lastProcessed->nHeight, skip->nHeight);
UpdateLastProcessed(skip);
if (lastProcessed->nHeight > requestTip->nHeight) {
requestTip = lastProcessed;
startHeight = lastProcessed->nHeight;
}
}
std::vector<const CBlockIndex*> blocksToRequest;
// add requests for as long as nMaxPendingRequests is not reached and there are still heigher blocks in headerChain
while (requestTip->nHeight - lastProcessed->nHeight < MAX_PENDING_REQUESTS &&
partialChain.Height() > requestTip->nHeight) {
requestTip = partialChain.Next(requestTip);
blocksToRequest.push_back(requestTip);
}
if (!blocksToRequest.empty()) {
LogPrint(BCLog::WALLET, "Requesting %d blocks for SPV, up to height %d\n", blocksToRequest.size(), requestTip->nHeight);
AddPriorityDownload(blocksToRequest, std::bind(&CSPVScanner::ProcessPriorityRequest, this, std::placeholders::_1, std::placeholders::_2));
}
}
void CSPVScanner::ProcessPriorityRequest(const std::shared_ptr<const CBlock> &block, const CBlockIndex *pindex)
{
LOCK2(cs_main, wallet.cs_wallet);
// if chainActive is up-to-date no SPV blocks need to be requested, we can update SPV to the activeChain
if (chainActive.Tip() == partialChain.Tip()) {
LogPrint(BCLog::WALLET, "chainActive is up-to-date, skipping SPV processing block %d\n", pindex->nHeight);
if (lastProcessed != partialChain.Tip()) {
UpdateLastProcessed(chainActive.Tip());
requestTip = lastProcessed;
}
}
// if this is the block we're waiting for process it and request new block(s)
if (pindex->pprev == lastProcessed) {
LogPrint(BCLog::WALLET, "SPV processing block %d\n", pindex->nHeight);
// TODO handle mempool effects
std::vector<CTransactionRef> vtxConflicted; // dummy for now
wallet.BlockConnected(block, pindex, vtxConflicted);
UpdateLastProcessed(pindex);
RequestBlocks();
if (partialChain.Height() == pindex->nHeight || pindex->nHeight % UI_UPDATE_LIMIT == 0)
uiInterface.NotifySPVProgress(startHeight, pindex->nHeight, partialChain.Height());
blocksSincePersist++;
}
}
void CSPVScanner::HeaderTipChanged(const CBlockIndex* pTip)
{
if (pTip)
{
// initialization on the first header tip notification
if (lastProcessed == nullptr)
{
if (partialChain.Height() >= partialChain.HeightOffset()
&& partialChain[partialChain.HeightOffset()]->GetBlockTime() <= startTime)
{
// use start of partial chain to init lastProcessed
// forks are handled when requesting blocks which will also fast-forward to startTime
// should the headerChain be very early
lastProcessed = partialChain[partialChain.HeightOffset()];
}
else
{
// headerChain not usable, it does not start early enough or has no data. This should not happen.
return;
}
}
requestTip = lastProcessed;
startHeight = lastProcessed->nHeight;
LogPrint(BCLog::WALLET, "SPV init using %s (height = %d) as last processed block\n",
lastProcessed->GetBlockHashPoW2().ToString(), lastProcessed->nHeight);
RequestBlocks();
}
else // pTip == nullptr => partial sync stopped
{
CancelAllPriorityDownloads();
Persist();
}
}
void CSPVScanner::UpdateLastProcessed(const CBlockIndex* pindex)
{
lastProcessed = pindex;
int64_t now = GetAdjustedTime();
if (now - lastPersistTime > PERSIST_INTERVAL_SEC || blocksSincePersist >= PERSIST_BLOCK_COUNT)
Persist();
}
void CSPVScanner::Persist()
{
if (lastProcessed != nullptr)
{
CWalletDB walletdb(*wallet.dbw);
walletdb.WriteLastSPVBlockProcessed(partialChain.GetLocatorPoW2(lastProcessed), lastProcessed->GetBlockTime());
lastPersistTime = GetAdjustedTime();
blocksSincePersist = 0;
}
}
<commit_msg>Properly init spvscanner on first header notification<commit_after>// Copyright (c) 2018 The Gulden developers
// Authored by: Willem de Jonge ([email protected])
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#include "spvscanner.h"
#include "../net_processing.h"
#include "timedata.h"
#include "../validation/validation.h"
#include "wallet.h"
#include <algorithm>
// Maximum number of requests pending. This number should be high enough so that
// the requests can be reasonably distributed over our peers.
const int MAX_PENDING_REQUESTS = 512;
// Duration (seconds) of longest fork that can be handled
const int64_t MAX_FORK_DURATION = 1 * 12 * 3600;
// Persisting wallet db updates are limited as they are very expensive
// and updating at every processed block would give very poor performance.
// Therefore the state is only written to the db when a minimum time interval has passed,
// or a certain of number of blocks have been processed (whichever comes first).
// Note that due to this some blocks might be re-processed in case of abnormal termination,
// this is fine.
// Interval in seconds for writing the scan progress to the wallet db
const int64_t PERSIST_INTERVAL_SEC = 5;
// Blocks count after which scan processing state is written to the db.
const int PERSIST_BLOCK_COUNT = 500;
// limit UI update notifications (except when catched up)
const int UI_UPDATE_LIMIT = 50;
CSPVScanner::CSPVScanner(CWallet& _wallet) :
wallet(_wallet),
startTime(0),
lastProcessed(nullptr),
lastPersistTime(0)
{
LOCK(cs_main);
// init scan starting time to birth of first key
startTime = wallet.nTimeFirstKey;
// forward scan starting time to last block processed if available
CWalletDB walletdb(*wallet.dbw);
CBlockLocator locator;
int64_t lastBlockTime;
if (walletdb.ReadLastSPVBlockProcessed(locator, lastBlockTime))
startTime = lastBlockTime;
// rewind scan starting time by maximum handled fork duration
startTime = std::max(Params().GenesisBlock().GetBlockTime(), startTime - MAX_FORK_DURATION);
}
CSPVScanner::~CSPVScanner()
{
}
bool CSPVScanner::StartScan()
{
return StartPartialHeaders(startTime, std::bind(&CSPVScanner::HeaderTipChanged, this, std::placeholders::_1));
}
const CBlockIndex* CSPVScanner::LastBlockProcessed() const
{
return lastProcessed;
}
void CSPVScanner::RequestBlocks()
{
LOCK2(cs_main, wallet.cs_wallet);
// put lastProcessed and/or requestTip back on chain if forked
while (!partialChain.Contains(requestTip)) {
if (requestTip->nHeight > lastProcessed->nHeight) {
CancelPriorityDownload(requestTip, std::bind(&CSPVScanner::ProcessPriorityRequest, this, std::placeholders::_1, std::placeholders::_2));
requestTip = requestTip->pprev;
}
else { // so here requestTip == lastProcessed
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
if (ReadBlockFromDisk(*pblock, lastProcessed, Params())) {
wallet.BlockDisconnected(pblock);
}
else {
// This block must be on disk, it was processed before.
// So pruning has to keep at least as many blocks back as the longest fork we are willing to handle.
assert(false);
}
UpdateLastProcessed(lastProcessed->pprev);
requestTip = lastProcessed;
}
}
// skip blocks that are before startTime
const CBlockIndex* skip = lastProcessed;
while (skip->GetBlockTime() < startTime && partialChain.Height() > skip->nHeight)
skip = partialChain.Next(skip);
if (skip != lastProcessed) {
LogPrint(BCLog::WALLET, "Skipping %d old blocks for SPV scan, up to height %d\n", skip->nHeight - lastProcessed->nHeight, skip->nHeight);
UpdateLastProcessed(skip);
if (lastProcessed->nHeight > requestTip->nHeight) {
requestTip = lastProcessed;
startHeight = lastProcessed->nHeight;
}
}
std::vector<const CBlockIndex*> blocksToRequest;
// add requests for as long as nMaxPendingRequests is not reached and there are still heigher blocks in headerChain
while (requestTip->nHeight - lastProcessed->nHeight < MAX_PENDING_REQUESTS &&
partialChain.Height() > requestTip->nHeight) {
requestTip = partialChain.Next(requestTip);
blocksToRequest.push_back(requestTip);
}
if (!blocksToRequest.empty()) {
LogPrint(BCLog::WALLET, "Requesting %d blocks for SPV, up to height %d\n", blocksToRequest.size(), requestTip->nHeight);
AddPriorityDownload(blocksToRequest, std::bind(&CSPVScanner::ProcessPriorityRequest, this, std::placeholders::_1, std::placeholders::_2));
}
}
void CSPVScanner::ProcessPriorityRequest(const std::shared_ptr<const CBlock> &block, const CBlockIndex *pindex)
{
LOCK2(cs_main, wallet.cs_wallet);
// if chainActive is up-to-date no SPV blocks need to be requested, we can update SPV to the activeChain
if (chainActive.Tip() == partialChain.Tip()) {
LogPrint(BCLog::WALLET, "chainActive is up-to-date, skipping SPV processing block %d\n", pindex->nHeight);
if (lastProcessed != partialChain.Tip()) {
UpdateLastProcessed(chainActive.Tip());
requestTip = lastProcessed;
}
}
// if this is the block we're waiting for process it and request new block(s)
if (pindex->pprev == lastProcessed) {
LogPrint(BCLog::WALLET, "SPV processing block %d\n", pindex->nHeight);
// TODO handle mempool effects
std::vector<CTransactionRef> vtxConflicted; // dummy for now
wallet.BlockConnected(block, pindex, vtxConflicted);
UpdateLastProcessed(pindex);
RequestBlocks();
if (partialChain.Height() == pindex->nHeight || pindex->nHeight % UI_UPDATE_LIMIT == 0)
uiInterface.NotifySPVProgress(startHeight, pindex->nHeight, partialChain.Height());
blocksSincePersist++;
}
}
void CSPVScanner::HeaderTipChanged(const CBlockIndex* pTip)
{
if (pTip)
{
// initialization on the first header tip notification
if (lastProcessed == nullptr)
{
if (partialChain.Height() >= partialChain.HeightOffset()
&& partialChain[partialChain.HeightOffset()]->GetBlockTime() <= startTime)
{
// use start of partial chain to init lastProcessed
// forks are handled when requesting blocks which will also fast-forward to startTime
// should the headerChain be very early
lastProcessed = partialChain[partialChain.HeightOffset()];
requestTip = lastProcessed;
startHeight = lastProcessed->nHeight;
LogPrint(BCLog::WALLET, "SPV init using %s (height = %d) as last processed block\n",
lastProcessed->GetBlockHashPoW2().ToString(), lastProcessed->nHeight);
}
else
{
// headerChain not usable, it does not start early enough or has no data.
// This should not happen, as StartPartialHeaders was explicitly given the startTime
// so if this occurs it's a bug.
throw std::runtime_error("partialChain not usable, starting late or too little data");
}
}
RequestBlocks();
}
else // pTip == nullptr => partial sync stopped
{
CancelAllPriorityDownloads();
Persist();
}
}
void CSPVScanner::UpdateLastProcessed(const CBlockIndex* pindex)
{
lastProcessed = pindex;
int64_t now = GetAdjustedTime();
if (now - lastPersistTime > PERSIST_INTERVAL_SEC || blocksSincePersist >= PERSIST_BLOCK_COUNT)
Persist();
}
void CSPVScanner::Persist()
{
if (lastProcessed != nullptr)
{
CWalletDB walletdb(*wallet.dbw);
walletdb.WriteLastSPVBlockProcessed(partialChain.GetLocatorPoW2(lastProcessed), lastProcessed->GetBlockTime());
lastPersistTime = GetAdjustedTime();
blocksSincePersist = 0;
}
}
<|endoftext|>
|
<commit_before>#include <boost/lexical_cast.hpp>
#include <qwt_symbol.h>
#include "graphPlot.h"
using namespace std;
using namespace watcher;
INIT_LOGGER(TimeScaleDraw, "TimeScaleDraw");
INIT_LOGGER(GraphCurve, "GraphCurve");
INIT_LOGGER(GraphPlot, "GraphPlot");
TimeScaleDraw::TimeScaleDraw(const QTime &base): baseTime(base)
{
TRACE_ENTER();
TRACE_EXIT();
}
QwtText TimeScaleDraw::label(double v) const
{
TRACE_ENTER();
QTime upTime = baseTime.addSecs((int)v);
return upTime.toString();
TRACE_EXIT();
}
GraphCurve::GraphCurve(const QString &title): QwtPlotCurve(title)
{
TRACE_ENTER();
setRenderHint(QwtPlotItem::RenderAntialiased);
TRACE_EXIT();
}
void GraphCurve::setColor(const QColor &color)
{
TRACE_ENTER();
QColor c = color;
c.setAlpha(150);
setPen(c);
setBrush(c);
TRACE_EXIT();
}
GraphPlot::GraphPlot(QWidget *parent, const QString &title_) :
QwtPlot(parent), title(title_), timeDataSize(60)
{
TRACE_ENTER();
timeData.reserve(timeDataSize);
// Initialize time data to 1, 2, ... sizeof(timeData)-1
for (int i=timeDataSize; i>0; i--)
timeData.push_back(i);
setTitle(title);
setAutoReplot(false);
plotLayout()->setAlignCanvasToScales(true);
QwtLegend *legend = new QwtLegend;
legend->setItemMode(QwtLegend::CheckableItem);
insertLegend(legend, QwtPlot::RightLegend);
setAxisTitle(QwtPlot::xBottom, "Time");
setAxisScaleDraw(QwtPlot::xBottom, new TimeScaleDraw(QTime::currentTime()));
setAxisScale(QwtPlot::xBottom, 0, timeDataSize);
setAxisLabelRotation(QwtPlot::xBottom, -50.0);
setAxisLabelAlignment(QwtPlot::xBottom, Qt::AlignLeft | Qt::AlignBottom);
// add space for right aligned label
QwtScaleWidget *scaleWidget = axisWidget(QwtPlot::xBottom);
const int fmh = QFontMetrics(scaleWidget->font()).height();
scaleWidget->setMinBorderDist(0, fmh / 2);
setAxisTitle(QwtPlot::yLeft, title);
// setAxisScale(QwtPlot::yLeft, 0, 100);
LOG_DEBUG("Starting 1 second timer for graph plot " << title.toStdString());
(void)startTimer(1000); // 1 second
connect(this, SIGNAL(legendChecked(QwtPlotItem *, bool)), SLOT(showCurve(QwtPlotItem *, bool)));
TRACE_EXIT();
}
void GraphPlot::addDataPoint(unsigned int curveId, float dataPoint)
{
TRACE_ENTER();
GraphData::iterator data=graphData.find(curveId);
// Create a new curve, if we've never seen this curveId before.
if (data==graphData.end())
addCurve(curveId);
LOG_DEBUG("Pushing back data point " << dataPoint << " for curve id " << (0xFF & curveId));
graphData[curveId]->data.push_front(dataPoint);
graphData[curveId]->pointSet=true;
// we only want timeDataSize data points, so trim front if longer than that.
if (graphData[curveId]->data.size()>timeDataSize)
graphData[curveId]->data.pop_back();
TRACE_EXIT();
}
void GraphPlot::timerEvent(QTimerEvent * /*event*/)
{
TRACE_ENTER();
for (int i=0;i<timeDataSize;i++)
timeData[i]++;
setAxisScale(QwtPlot::xBottom, timeData[timeDataSize-1], timeData[0]);
for (GraphData::iterator d=graphData.begin(); d!=graphData.end(); d++)
{
if (!d->second->pointSet) // Didn't hear from the node for last second, set data to zero.
{
LOG_DEBUG("Didn't hear from node " << (0xFF & d->first) << " setting this second's data to 0");
d->second->data.push_front(0);
if (d->second->data.size()>timeDataSize)
d->second->data.pop_back();
}
else
d->second->pointSet=false; // reset for next go around.
d->second->curve->setData(timeData, d->second->data);
}
replot();
TRACE_EXIT();
}
void GraphPlot::showCurve(QwtPlotItem *curve, bool on)
{
TRACE_ENTER();
LOG_DEBUG("Setting curve " << (on?"":"in") << "visible.")
curve->setVisible(on);
QWidget *w = legend()->find(curve);
if ( w && w->inherits("QwtLegendItem") )
((QwtLegendItem *)w)->setChecked(on);
TRACE_EXIT();
}
void GraphPlot::showCurve(unsigned int curveId, bool on)
{
TRACE_ENTER();
if (graphData.end()==graphData.find(curveId))
{
LOG_DEBUG("User wants to show curve for a node we've never seen, adding empty curve with id " << (0xFF & curveId));
addCurve(curveId);
}
showCurve(graphData[curveId]->curve.get(), on);
replot();
TRACE_EXIT();
}
void GraphPlot::toggleCurveAndLegendVisible(unsigned int curveId)
{
TRACE_ENTER();
if (graphData.end()==graphData.find(curveId))
{
LOG_DEBUG("User wants to toggle visibility for a curve we've never seen, adding empty curve with id " << (0xFF & curveId));
addCurve(curveId);
}
curveAndLegendVisible(curveId, !graphData[curveId]->curve->isVisible());
TRACE_EXIT();
}
void GraphPlot::curveAndLegendVisible(unsigned int curveId, bool visible)
{
TRACE_ENTER();
if (graphData.end()==graphData.find(curveId))
{
LOG_DEBUG("User wants to set/unset visibility for a curve we've never seen, adding empty curve with id " << (0xFF & curveId));
addCurve(curveId);
}
showCurve(graphData[curveId]->curve.get(), visible);
QWidget *w = legend()->find(graphData[curveId]->curve.get());
if ( w && w->inherits("QwtLegendItem") )
((QwtLegendItem *)w)->setVisible(visible);
TRACE_EXIT();
}
void GraphPlot::addCurve(unsigned int curveId)
{
TRACE_ENTER();
boost::shared_ptr<CurveData> data(new CurveData);
for (unsigned int i=0; i<timeDataSize; i++)
data->data.push_back(0);
graphData[curveId]=data;
string curveTitle=boost::lexical_cast<string>((unsigned int)(0xFF & curveId));
data->curve=boost::shared_ptr<GraphCurve>(new GraphCurve(curveTitle.c_str()));
data->curve->setColor(Qt::red);
data->curve->attach(this);
LOG_DEBUG("Created new curve " << (0xFF & curveId));
TRACE_EXIT();
}
<commit_msg>GraphPlot: set color of new curves to a random color so all curves are not red.<commit_after>#include <boost/lexical_cast.hpp>
#include <qwt_symbol.h>
#include "graphPlot.h"
using namespace std;
using namespace watcher;
INIT_LOGGER(TimeScaleDraw, "TimeScaleDraw");
INIT_LOGGER(GraphCurve, "GraphCurve");
INIT_LOGGER(GraphPlot, "GraphPlot");
TimeScaleDraw::TimeScaleDraw(const QTime &base): baseTime(base)
{
TRACE_ENTER();
TRACE_EXIT();
}
QwtText TimeScaleDraw::label(double v) const
{
TRACE_ENTER();
QTime upTime = baseTime.addSecs((int)v);
return upTime.toString();
TRACE_EXIT();
}
GraphCurve::GraphCurve(const QString &title): QwtPlotCurve(title)
{
TRACE_ENTER();
setRenderHint(QwtPlotItem::RenderAntialiased);
TRACE_EXIT();
}
void GraphCurve::setColor(const QColor &color)
{
TRACE_ENTER();
QColor c = color;
c.setAlpha(150);
setPen(c);
// setBrush(c); // Don't fill below curve.
TRACE_EXIT();
}
GraphPlot::GraphPlot(QWidget *parent, const QString &title_) :
QwtPlot(parent), title(title_), timeDataSize(60)
{
TRACE_ENTER();
timeData.reserve(timeDataSize);
// Initialize time data to 1, 2, ... sizeof(timeData)-1
for (int i=timeDataSize; i>0; i--)
timeData.push_back(i);
setTitle(title);
setAutoReplot(false);
plotLayout()->setAlignCanvasToScales(true);
QwtLegend *legend = new QwtLegend;
legend->setItemMode(QwtLegend::CheckableItem);
insertLegend(legend, QwtPlot::RightLegend);
setAxisTitle(QwtPlot::xBottom, "Time");
setAxisScaleDraw(QwtPlot::xBottom, new TimeScaleDraw(QTime::currentTime()));
setAxisScale(QwtPlot::xBottom, 0, timeDataSize);
setAxisLabelRotation(QwtPlot::xBottom, -50.0);
setAxisLabelAlignment(QwtPlot::xBottom, Qt::AlignLeft | Qt::AlignBottom);
// add space for right aligned label
QwtScaleWidget *scaleWidget = axisWidget(QwtPlot::xBottom);
const int fmh = QFontMetrics(scaleWidget->font()).height();
scaleWidget->setMinBorderDist(0, fmh / 2);
setAxisTitle(QwtPlot::yLeft, title);
// setAxisScale(QwtPlot::yLeft, 0, 100);
LOG_DEBUG("Starting 1 second timer for graph plot " << title.toStdString());
(void)startTimer(1000); // 1 second
connect(this, SIGNAL(legendChecked(QwtPlotItem *, bool)), SLOT(showCurve(QwtPlotItem *, bool)));
TRACE_EXIT();
}
void GraphPlot::addDataPoint(unsigned int curveId, float dataPoint)
{
TRACE_ENTER();
GraphData::iterator data=graphData.find(curveId);
// Create a new curve, if we've never seen this curveId before.
if (data==graphData.end())
addCurve(curveId);
LOG_DEBUG("Pushing back data point " << dataPoint << " for curve id " << (0xFF & curveId));
graphData[curveId]->data.push_front(dataPoint);
graphData[curveId]->pointSet=true;
// we only want timeDataSize data points, so trim front if longer than that.
if (graphData[curveId]->data.size()>timeDataSize)
graphData[curveId]->data.pop_back();
TRACE_EXIT();
}
void GraphPlot::timerEvent(QTimerEvent * /*event*/)
{
TRACE_ENTER();
for (int i=0;i<timeDataSize;i++)
timeData[i]++;
setAxisScale(QwtPlot::xBottom, timeData[timeDataSize-1], timeData[0]);
for (GraphData::iterator d=graphData.begin(); d!=graphData.end(); d++)
{
if (!d->second->pointSet) // Didn't hear from the node for last second, set data to zero.
{
LOG_DEBUG("Didn't hear from node " << (0xFF & d->first) << " setting this second's data to 0");
d->second->data.push_front(0);
if (d->second->data.size()>timeDataSize)
d->second->data.pop_back();
}
else
d->second->pointSet=false; // reset for next go around.
d->second->curve->setData(timeData, d->second->data);
}
replot();
TRACE_EXIT();
}
void GraphPlot::showCurve(QwtPlotItem *curve, bool on)
{
TRACE_ENTER();
LOG_DEBUG("Setting curve " << (on?"":"in") << "visible.")
curve->setVisible(on);
QWidget *w = legend()->find(curve);
if ( w && w->inherits("QwtLegendItem") )
((QwtLegendItem *)w)->setChecked(on);
TRACE_EXIT();
}
void GraphPlot::showCurve(unsigned int curveId, bool on)
{
TRACE_ENTER();
if (graphData.end()==graphData.find(curveId))
{
LOG_DEBUG("User wants to show curve for a node we've never seen, adding empty curve with id " << (0xFF & curveId));
addCurve(curveId);
}
showCurve(graphData[curveId]->curve.get(), on);
replot();
TRACE_EXIT();
}
void GraphPlot::toggleCurveAndLegendVisible(unsigned int curveId)
{
TRACE_ENTER();
if (graphData.end()==graphData.find(curveId))
{
LOG_DEBUG("User wants to toggle visibility for a curve we've never seen, adding empty curve with id " << (0xFF & curveId));
addCurve(curveId);
}
curveAndLegendVisible(curveId, !graphData[curveId]->curve->isVisible());
TRACE_EXIT();
}
void GraphPlot::curveAndLegendVisible(unsigned int curveId, bool visible)
{
TRACE_ENTER();
if (graphData.end()==graphData.find(curveId))
{
LOG_DEBUG("User wants to set/unset visibility for a curve we've never seen, adding empty curve with id " << (0xFF & curveId));
addCurve(curveId);
}
showCurve(graphData[curveId]->curve.get(), visible);
QWidget *w = legend()->find(graphData[curveId]->curve.get());
if ( w && w->inherits("QwtLegendItem") )
((QwtLegendItem *)w)->setVisible(visible);
TRACE_EXIT();
}
void GraphPlot::addCurve(unsigned int curveId)
{
TRACE_ENTER();
boost::shared_ptr<CurveData> data(new CurveData);
for (int i=0; i<timeDataSize; i++)
data->data.push_back(0);
graphData[curveId]=data;
string curveTitle=boost::lexical_cast<string>((unsigned int)(0xFF & curveId));
data->curve=boost::shared_ptr<GraphCurve>(new GraphCurve(curveTitle.c_str()));
// data->curve->setColor(Qt::red);
data->curve->setColor(QColor::fromHsv(qrand() % 256, 255, 190));
data->curve->setStyle(QwtPlotCurve::Lines);
// data->curve->setCurveAttribute(QwtPlotCurve::Fitted);
data->curve->attach(this);
LOG_DEBUG("Created new curve " << (0xFF & curveId));
TRACE_EXIT();
}
<|endoftext|>
|
<commit_before>// -*- mode: C++; c-file-style: "gnu" -*-
// KMail startup and initialize code
// Author: Stefan Taferner <[email protected]>
#include <config.h>
#include <kuniqueapplication.h>
#include <kglobal.h>
#include <knotifyclient.h>
#include <dcopclient.h>
#include "kmkernel.h" //control center
#include "kmail_options.h"
#include <kdebug.h>
#undef Status // stupid X headers
#include "aboutdata.h"
#include "kmstartup.h"
// OLD about text. This is horrbly outdated.
/*const char* aboutText =
"KMail [" KMAIL_VERSION "] by\n\n"
"Stefan Taferner <[email protected]>,\n"
"Markus Wbben <[email protected]>\n\n"
"based on the work of:\n"
"Lynx <[email protected]>,\n"
"Stephan Meyer <[email protected]>,\n"
"and the above authors.\n\n"
"This program is covered by the GPL.\n\n"
"Please send bugreports to [email protected]";
*/
//-----------------------------------------------------------------------------
class KMailApplication : public KUniqueApplication
{
public:
KMailApplication() : KUniqueApplication() { };
virtual int newInstance();
void commitData(QSessionManager& sm);
};
void KMailApplication::commitData(QSessionManager& sm) {
kmkernel->dumpDeadLetters();
kmkernel->setShuttingDown( true ); // Prevent further dumpDeadLetters calls
KApplication::commitData( sm );
}
int KMailApplication::newInstance()
{
kdDebug(5006) << "KMailApplication::newInstance()" << endl;
if (!kmkernel)
return 0;
if (!kmkernel->firstInstance() || !kapp->isRestored())
kmkernel->handleCommandLine( true );
kmkernel->setFirstInstance(FALSE);
return 0;
}
int main(int argc, char *argv[])
{
// WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
// a bit harder: You should pass --nofork as commandline argument when using
// a debugger. In gdb you can do this by typing "set args --nofork" before
// typing "run".
KMail::AboutData about;
KCmdLineArgs::init(argc, argv, &about);
KCmdLineArgs::addCmdLineOptions( kmail_options ); // Add kmail options
if (!KMailApplication::start())
return 0;
KMailApplication app;
// import i18n data and icons from libraries:
KMail::insertLibraryCataloguesAndIcons();
// Make sure that the KNotify Daemon is running (this is necessary for people
// using KMail without KDE)
KNotifyClient::startDaemon();
kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet
KMail::lockOrDie();
//local, do the init
KMKernel kmailKernel;
kmailKernel.init();
kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );
// and session management
kmailKernel.doSessionManagement();
// any dead letters?
kmailKernel.recoverDeadLetters();
kmsetSignalHandler(kmsignalHandler);
kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests.
kmkernel->setStartingUp( false ); // Starting up is finished
// Go!
int ret = kapp->exec();
// clean up
kmailKernel.cleanup();
KMail::cleanup(); // pid file (see kmstartup.cpp)
return ret;
}
<commit_msg>CVS_SILENT cleanup<commit_after>// -*- mode: C++; c-file-style: "gnu" -*-
// KMail startup and initialize code
// Author: Stefan Taferner <[email protected]>
#include <config.h>
#include <kuniqueapplication.h>
#include <kglobal.h>
#include <knotifyclient.h>
#include <dcopclient.h>
#include "kmkernel.h" //control center
#include "kmail_options.h"
#include <kdebug.h>
#undef Status // stupid X headers
#include "aboutdata.h"
#include "kmstartup.h"
//-----------------------------------------------------------------------------
class KMailApplication : public KUniqueApplication
{
public:
KMailApplication() : KUniqueApplication() { };
virtual int newInstance();
void commitData(QSessionManager& sm);
};
void KMailApplication::commitData(QSessionManager& sm) {
kmkernel->dumpDeadLetters();
kmkernel->setShuttingDown( true ); // Prevent further dumpDeadLetters calls
KApplication::commitData( sm );
}
int KMailApplication::newInstance()
{
kdDebug(5006) << "KMailApplication::newInstance()" << endl;
if (!kmkernel)
return 0;
if (!kmkernel->firstInstance() || !kapp->isRestored())
kmkernel->handleCommandLine( true );
kmkernel->setFirstInstance(FALSE);
return 0;
}
int main(int argc, char *argv[])
{
// WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
// a bit harder: You should pass --nofork as commandline argument when using
// a debugger. In gdb you can do this by typing "set args --nofork" before
// typing "run".
KMail::AboutData about;
KCmdLineArgs::init(argc, argv, &about);
KCmdLineArgs::addCmdLineOptions( kmail_options ); // Add kmail options
if (!KMailApplication::start())
return 0;
KMailApplication app;
// import i18n data and icons from libraries:
KMail::insertLibraryCataloguesAndIcons();
// Make sure that the KNotify Daemon is running (this is necessary for people
// using KMail without KDE)
KNotifyClient::startDaemon();
kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet
KMail::lockOrDie();
//local, do the init
KMKernel kmailKernel;
kmailKernel.init();
kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );
// and session management
kmailKernel.doSessionManagement();
// any dead letters?
kmailKernel.recoverDeadLetters();
kmsetSignalHandler(kmsignalHandler);
kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests.
kmkernel->setStartingUp( false ); // Starting up is finished
// Go!
int ret = kapp->exec();
// clean up
kmailKernel.cleanup();
KMail::cleanup(); // pid file (see kmstartup.cpp)
return ret;
}
<|endoftext|>
|
<commit_before>// Project specific
#include <Manager/AudioManager.hpp>
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Audio/Include/AudioModule.hpp>
#include <EntityComponent/EntityHandler.hpp>
#include <EntityComponent/Components/ExampleComponent.hpp>
#include <EntityComponent/Components/Example2Component.hpp>
#include <EntityComponent/Components/AudioActiveComponent.hpp>
#include <EntityComponent/Components/TransformComponent.hpp>
#include <EntityComponent/Components/RigidBodyComponent.hpp>
#include <EventHandler/EventHandler.hpp>
#include <EventHandler/Events/ExampleEvent.hpp>
#include <Doremi/Core/Include/AudioHandler.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <Doremi/Core/Include/InputHandler.hpp>
#include <DirectXMath.h>
// Third party
// Standard
#include <iostream>
using namespace std;
namespace Doremi
{
namespace Core
{
AudioManager::AudioManager(const DoremiEngine::Core::SharedContext& p_sharedContext) : Manager(p_sharedContext)
{
EventHandler::GetInstance()->Subscribe(Events::Example, this);
}
AudioManager::~AudioManager() {}
void AudioManager::Update(double p_dt)
{
// First get the module
DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
// Loop through all entities
size_t length = EntityHandler::GetInstance().GetLastEntityIndex();
bool t_isPlaying = false;
for(size_t i = 0; i < length; i++)
{
// Check that the current entity has the relevant components
if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::AudioActive))
{
// Get component
AudioActiveComponent* t_audio = EntityHandler::GetInstance().GetComponentFromStorage<AudioActiveComponent>(i);
t_isPlaying = t_audioModule.GetChannelPlaying(t_audio->channelID);
if(!t_isPlaying)
{
EntityHandler::GetInstance().RemoveComponent(i, (int)ComponentType::AudioActive);
}
/**
TODOLH Test the functions below
*/
/*if (EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::Transform) && t_isPlaying)
{
TransformComponent* t_trans = EntityHandler::GetInstance().GetComponentFromStorage<TransformComponent>(i);
t_audioModule.SetSoundPositionAndVelocity(t_trans->position.x, t_trans->position.y, t_trans->position.z, 0, 0, 0, t_audio->channelID);
}*/
/*if (EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::Player) && t_isPlaying)
{
TransformComponent* t_trans = EntityHandler::GetInstance().GetComponentFromStorage<TransformComponent>(i);
t_audioModule.SetListenerPos(t_trans->position.x, t_trans->position.y, t_trans->position.z)
}*/
}
if (EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::FrequencyAffected))
{
RigidBodyComponent* t_rigidComp = EntityHandler::GetInstance().GetComponentFromStorage<RigidBodyComponent>(i);
float t_freq = AudioHandler::GetInstance()->GetFrequency();
m_sharedContext.GetPhysicsModule().GetRigidBodyManager().AddForceToBody(t_rigidComp->p_bodyID, XMFLOAT3(0, t_freq*3, 0)); /**Far from complete TODOLH br inte liogga i audio manager heller*/
}
}
//m_dominantFrequency = AudioHandler::GetInstance()->GetFrequency();
m_dominantFrequency = AudioHandler::GetInstance()->GetRepeatableSoundFrequency();
std::cout << "Freq = " << m_dominantFrequency << std::endl; /**TODOLH ta bort nr debugging r klart*/
// Check Input
if(InputHandler::GetInstance()->CheckForOnePress((int)UserCommandPlaying::StartRepeatableAudioRecording) && !m_gunReloadButtonDown)
{
AudioHandler::GetInstance()->StartRepeatableRecording();
m_gunReloadButtonDown = true;
m_timeThatGunButtonIsDown = 0;
}
else if(InputHandler::GetInstance()->CheckBitMaskInputFromGame((int)UserCommandPlaying::StartRepeatableAudioRecording) && m_gunReloadButtonDown)
{
m_timeThatGunButtonIsDown += p_dt;
}
else if(!InputHandler::GetInstance()->CheckBitMaskInputFromGame((int)UserCommandPlaying::StartRepeatableAudioRecording) && m_gunReloadButtonDown)
{
m_gunReloadButtonDown = false;
AudioHandler::GetInstance()->SetGunButtonDownTime(m_timeThatGunButtonIsDown);
}
if(InputHandler::GetInstance()->CheckForOnePress((int)UserCommandPlaying::PlayRepeatableAudioRecording))
{
AudioHandler::GetInstance()->PlayRepeatableRecordedSound();
}
else
{
//Do Nothing
}
t_audioModule.Update();
}
void AudioManager::OnEvent(Event* p_event)
{
// Check to see what event was received and do something with it (Might be changed to callback functions instead)
switch(p_event->eventType)
{
case Events::Example:
// Cast the event to the correct format
ExampleEvent* t_event = (ExampleEvent*)p_event;
int t_intFromEvent = t_event->myInt;
break;
}
}
}
}
<commit_msg>AudioManager: Removed debug cout<commit_after>// Project specific
#include <Manager/AudioManager.hpp>
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Audio/Include/AudioModule.hpp>
#include <EntityComponent/EntityHandler.hpp>
#include <EntityComponent/Components/ExampleComponent.hpp>
#include <EntityComponent/Components/Example2Component.hpp>
#include <EntityComponent/Components/AudioActiveComponent.hpp>
#include <EntityComponent/Components/TransformComponent.hpp>
#include <EntityComponent/Components/RigidBodyComponent.hpp>
#include <EventHandler/EventHandler.hpp>
#include <EventHandler/Events/ExampleEvent.hpp>
#include <Doremi/Core/Include/AudioHandler.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <Doremi/Core/Include/InputHandler.hpp>
#include <DirectXMath.h>
// Third party
// Standard
#include <iostream>
using namespace std;
namespace Doremi
{
namespace Core
{
AudioManager::AudioManager(const DoremiEngine::Core::SharedContext& p_sharedContext) : Manager(p_sharedContext)
{
EventHandler::GetInstance()->Subscribe(Events::Example, this);
}
AudioManager::~AudioManager() {}
void AudioManager::Update(double p_dt)
{
// First get the module
DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule();
// Loop through all entities
size_t length = EntityHandler::GetInstance().GetLastEntityIndex();
bool t_isPlaying = false;
for(size_t i = 0; i < length; i++)
{
// Check that the current entity has the relevant components
if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::AudioActive))
{
// Get component
AudioActiveComponent* t_audio = EntityHandler::GetInstance().GetComponentFromStorage<AudioActiveComponent>(i);
t_isPlaying = t_audioModule.GetChannelPlaying(t_audio->channelID);
if(!t_isPlaying)
{
EntityHandler::GetInstance().RemoveComponent(i, (int)ComponentType::AudioActive);
}
/**
TODOLH Test the functions below
*/
/*if (EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::Transform) && t_isPlaying)
{
TransformComponent* t_trans = EntityHandler::GetInstance().GetComponentFromStorage<TransformComponent>(i);
t_audioModule.SetSoundPositionAndVelocity(t_trans->position.x, t_trans->position.y, t_trans->position.z, 0, 0, 0, t_audio->channelID);
}*/
/*if (EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::Player) && t_isPlaying)
{
TransformComponent* t_trans = EntityHandler::GetInstance().GetComponentFromStorage<TransformComponent>(i);
t_audioModule.SetListenerPos(t_trans->position.x, t_trans->position.y, t_trans->position.z)
}*/
}
if (EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::FrequencyAffected))
{
RigidBodyComponent* t_rigidComp = EntityHandler::GetInstance().GetComponentFromStorage<RigidBodyComponent>(i);
float t_freq = AudioHandler::GetInstance()->GetFrequency();
m_sharedContext.GetPhysicsModule().GetRigidBodyManager().AddForceToBody(t_rigidComp->p_bodyID, XMFLOAT3(0, t_freq*3, 0)); /**Far from complete TODOLH br inte liogga i audio manager heller*/
}
}
//m_dominantFrequency = AudioHandler::GetInstance()->GetFrequency();
m_dominantFrequency = AudioHandler::GetInstance()->GetRepeatableSoundFrequency();
//std::cout << "Freq = " << m_dominantFrequency << std::endl; /**TODOLH ta bort nr debugging r klart*/
// Check Input
if(InputHandler::GetInstance()->CheckForOnePress((int)UserCommandPlaying::StartRepeatableAudioRecording) && !m_gunReloadButtonDown)
{
AudioHandler::GetInstance()->StartRepeatableRecording();
m_gunReloadButtonDown = true;
m_timeThatGunButtonIsDown = 0;
}
else if(InputHandler::GetInstance()->CheckBitMaskInputFromGame((int)UserCommandPlaying::StartRepeatableAudioRecording) && m_gunReloadButtonDown)
{
m_timeThatGunButtonIsDown += p_dt;
}
else if(!InputHandler::GetInstance()->CheckBitMaskInputFromGame((int)UserCommandPlaying::StartRepeatableAudioRecording) && m_gunReloadButtonDown)
{
m_gunReloadButtonDown = false;
AudioHandler::GetInstance()->SetGunButtonDownTime(m_timeThatGunButtonIsDown);
}
if(InputHandler::GetInstance()->CheckForOnePress((int)UserCommandPlaying::PlayRepeatableAudioRecording))
{
AudioHandler::GetInstance()->PlayRepeatableRecordedSound();
}
else
{
//Do Nothing
}
t_audioModule.Update();
}
void AudioManager::OnEvent(Event* p_event)
{
// Check to see what event was received and do something with it (Might be changed to callback functions instead)
switch(p_event->eventType)
{
case Events::Example:
// Cast the event to the correct format
ExampleEvent* t_event = (ExampleEvent*)p_event;
int t_intFromEvent = t_event->myInt;
break;
}
}
}
}
<|endoftext|>
|
<commit_before>#include <chord.h>
#include "merkle_syncer.h"
#include "qhash.h"
#include "async.h"
#include "bigint.h"
#include <id_utils.h>
#include <comm.h>
#include <modlogger.h>
#define warning modlogger ("merkle", modlogger::WARNING)
#define info modlogger ("merkle", modlogger::INFO)
#define trace modlogger ("merkle", modlogger::TRACE)
// ---------------------------------------------------------------------------
// util junk
// Check whether [l1, r1] overlaps [l2, r2] on the circle.
static bool
overlap (const bigint &l1, const bigint &r1, const bigint &l2, const bigint &r2)
{
// There might be a more efficient way to do this..
return (betweenbothincl (l1, r1, l2) || betweenbothincl (l1, r1, r2)
|| betweenbothincl (l2, r2, l1) || betweenbothincl (l2, r2, r1));
}
// ---------------------------------------------------------------------------
// merkle_syncer
merkle_syncer::merkle_syncer (dhash_ctype ctype, merkle_tree *ltree,
rpcfnc_t rpcfnc, missingfnc_t missingfnc)
: ctype (ctype), ltree (ltree), rpcfnc (rpcfnc), missingfnc (missingfnc)
{
fatal_err = NULL;
sync_done = false;
}
void
merkle_syncer::sync (bigint rngmin, bigint rngmax)
{
local_rngmin = rngmin;
local_rngmax = rngmax;
// start at the root of the merkle tree
sendnode (0, 0);
}
void
merkle_syncer::dump ()
{
warn << "THIS: " << (u_int)this << "\n";
warn << " st.size () " << st.size () << "\n";
}
void
merkle_syncer::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)
{
// Must resort to bundling all values into one argument since
// async/callback.h is configured with too few parameters.
struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb,
NULL);
(*rpcfnc) (&args);
}
void
merkle_syncer::setdone ()
{
(*missingfnc) (0, false, true);
sync_done = true;
}
void
merkle_syncer::error (str err)
{
warn << (u_int)this << ": SYNCER ERROR: " << err << "\n";
fatal_err = err;
setdone ();
}
str
merkle_syncer::getsummary ()
{
assert (sync_done);
strbuf sb;
sb << "[" << local_rngmin << "," << local_rngmax << "] ";
if (fatal_err)
sb << fatal_err;
if (0)
sb << "<log " << log << ">\n";
return sb;
}
void
merkle_syncer::next (void)
{
trace << "local range [" << local_rngmin << "," << local_rngmax << "]\n";
assert (!sync_done);
assert (!fatal_err);
// st is queue of pending index nodes
while (st.size ()) {
pair<merkle_rpc_node, int> &p = st.back ();
merkle_rpc_node *rnode = &p.first;
assert (!rnode->isleaf);
merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);
if (!lnode) {
fatal << "lookup_exact didn't match for " << rnode->prefix << " at depth " << rnode->depth << "\n";
}
trace << "starting from slot " << p.second << "\n";
while (p.second < 64) {
u_int i = p.second;
p.second += 1;
trace << "CHECKING: " << i;
bigint remote = tobigint (rnode->child_hash[i]);
bigint local = tobigint (lnode->child (i)->hash);
u_int depth = rnode->depth + 1;
//prefix is the high bits of the first key
// the node is responsible for.
merkle_hash prefix = rnode->prefix;
prefix.write_slot (rnode->depth, i);
bigint slot_rngmin = tobigint (prefix);
bigint slot_width = bigint (1) << (160 - 6*depth);
bigint slot_rngmax = slot_rngmin + slot_width - 1;
bool overlaps = overlap (local_rngmin, local_rngmax, slot_rngmin, slot_rngmax);
strbuf tr;
if (remote != local) {
tr << " differ. local " << local << " != remote " << remote;
if (overlaps) {
tr << " .. sending\n";
sendnode (depth, prefix);
trace << tr;
return;
} else {
tr << " .. not sending\n";
}
} else {
tr << " same. local " << local << " == remote " << remote << "\n";
}
trace << tr;
}
assert (p.second == 64);
st.pop_back ();
}
trace << "DONE .. in NEXT\n";
setdone ();
trace << "OK!\n";
}
void
merkle_syncer::sendnode (u_int depth, const merkle_hash &prefix)
{
ref<sendnode_arg> arg = New refcounted<sendnode_arg> ();
ref<sendnode_res> res = New refcounted<sendnode_res> ();
u_int lnode_depth;
merkle_node *lnode = ltree->lookup (&lnode_depth, depth, prefix);
// OK to assert this: since depth-1 is an index node, we know that
// it created all of its depth children when
// it split. --FED
assert (lnode);
assert (lnode_depth == depth);
format_rpcnode (ltree, depth, prefix, lnode, &arg->node);
arg->ctype = ctype;
arg->rngmin = local_rngmin;
arg->rngmax = local_rngmax;
doRPC (MERKLESYNC_SENDNODE, arg, res,
wrap (this, &merkle_syncer::sendnode_cb, arg, res));
}
void
merkle_syncer::sendnode_cb (ref<sendnode_arg> arg, ref<sendnode_res> res,
clnt_stat err)
{
if (err) {
error (strbuf () << "SENDNODE: rpc error " << err);
return;
} else if (res->status != MERKLE_OK) {
error (strbuf () << "SENDNODE: protocol error " << err2str (res->status));
return;
}
merkle_rpc_node *rnode = &res->resok->node;
merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);
if (!lnode) {
fatal << "lookup failed: " << rnode->prefix << " at " << rnode->depth << "\n";
}
compare_nodes (ltree, local_rngmin, local_rngmax, lnode, rnode,
ctype, missingfnc, rpcfnc);
if (!lnode->isleaf () && !rnode->isleaf) {
trace << "I vs I\n";
st.push_back (pair<merkle_rpc_node, int> (*rnode, 0));
}
next ();
}
// ---------------------------------------------------------------------------
// merkle_getkeyrange
void
merkle_getkeyrange::go ()
{
if (!betweenbothincl (rngmin, rngmax, current)) {
trace << "merkle_getkeyrange::go () ==> DONE\n";
delete this;
return;
}
ref<getkeys_arg> arg = New refcounted<getkeys_arg> ();
arg->ctype = ctype;
arg->rngmin = current;
arg->rngmax = rngmax;
ref<getkeys_res> res = New refcounted<getkeys_res> ();
doRPC (MERKLESYNC_GETKEYS, arg, res,
wrap (this, &merkle_getkeyrange::getkeys_cb, arg, res));
}
void
merkle_getkeyrange::getkeys_cb (ref<getkeys_arg> arg, ref<getkeys_res> res,
clnt_stat err)
{
if (err) {
warn << "GETKEYS: rpc error " << err << "\n";
delete this;
return;
} else if (res->status != MERKLE_OK) {
warn << "GETKEYS: protocol error " << err2str (res->status) << "\n";
delete this;
return;
}
// Assuming keys are sent back in increasing clockwise order
vec<merkle_hash> rkeys;
for (u_int i = 0; i < res->resok->keys.size (); i++) {
const merkle_hash &key = res->resok->keys[i];
rkeys.push_back (key);
}
assert (res->resok->keys.size () > 0);
chordID sentmax = tobigint (res->resok->keys.back ());
compare_keylists (lkeys, rkeys, current, sentmax, missing);
current = incID (sentmax);
if (!res->resok->morekeys)
current = incID (rngmax); // set done
go ();
}
void
merkle_getkeyrange::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)
{
// Must resort to bundling all values into one argument since
// async/callback.h is configured with too few parameters.
struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb,
NULL);
(*rpcfnc) (&args);
}
// ---------------------------------------------------------------------------
void
compare_keylists (vec<merkle_hash> lkeys,
vec<merkle_hash> vrkeys,
chordID rngmin, chordID rngmax,
missingfnc_t missingfnc)
{
// populate a hash table with the remote keys
qhash<merkle_hash, int> rkeys;
for (u_int i = 0; i < vrkeys.size (); i++) {
if (betweenbothincl (rngmin, rngmax, tobigint(vrkeys[i])))
rkeys.insert (vrkeys[i], 1);
}
// do I have something he doesn't have?
for (unsigned int i = 0; i < lkeys.size (); i++) {
if (!rkeys[lkeys[i]] &&
betweenbothincl (rngmin, rngmax, tobigint(lkeys[i]))) {
trace << "remote missing [" << rngmin << ", " << rngmax << "] key=" << lkeys[i] << "\n";
(*missingfnc) (tobigint(lkeys[i]), false, false);
} else {
rkeys.remove (lkeys[i]);
}
}
//anything left: he has and I don't
qhash_slot<merkle_hash, int> *slot = rkeys.first ();
while (slot) {
trace << "local missing [" << rngmin << ", " << rngmax << "] key=" << slot->key << "\n";
(*missingfnc) (tobigint(slot->key), true, false);
slot = rkeys.next (slot);
}
}
void
compare_nodes (merkle_tree *ltree, bigint rngmin, bigint rngmax,
merkle_node *lnode, merkle_rpc_node *rnode,
dhash_ctype ctype,
missingfnc_t missingfnc, rpcfnc_t rpcfnc)
{
trace << (lnode->isleaf () ? "L" : "I")
<< " vs "
<< (rnode->isleaf ? "L" : "I")
<< "\n";
if (rnode->isleaf) {
vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);
vec<merkle_hash> rkeys;
for (u_int i = 0; i < rnode->child_hash.size (); i++)
rkeys.push_back (rnode->child_hash[i]);
compare_keylists (lkeys, rkeys, rngmin, rngmax, missingfnc);
} else if (lnode->isleaf () && !rnode->isleaf) {
bigint tmpmin = tobigint (rnode->prefix);
bigint node_width = bigint (1) << (160 - rnode->depth);
bigint tmpmax = tmpmin + node_width - 1;
// further constrain to be within the host's range of interest
if (between (tmpmin, tmpmax, rngmin))
tmpmin = rngmin;
if (between (tmpmin, tmpmax, rngmax))
tmpmax = rngmax;
vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);
vNew merkle_getkeyrange (ctype, ltree->db, tmpmin, tmpmax, lkeys,
missingfnc, rpcfnc);
}
}
// ---------------------------------------------------------------------------
void
format_rpcnode (merkle_tree *ltree, u_int depth, const merkle_hash &prefix,
const merkle_node *node, merkle_rpc_node *rpcnode)
{
rpcnode->depth = depth;
rpcnode->prefix = prefix;
rpcnode->count = node->count;
rpcnode->hash = node->hash;
rpcnode->isleaf = node->isleaf ();
if (!node->isleaf ()) {
rpcnode->child_hash.setsize (64);
for (int i = 0; i < 64; i++)
rpcnode->child_hash[i] = node->child (i)->hash;
} else {
vec<merkle_hash> keys = database_get_keys (ltree->db, depth, prefix);
if (keys.size () != rpcnode->count) {
warn << "\n\n\n----------------------------------------------------------\n";
warn << "BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\n";
warn << "Send this output to [email protected]\n";
warn << "BUG: " << depth << " " << prefix << "\n";
warn << "BUG: " << keys.size () << " != " << rpcnode->count << "\n";
ltree->check_invariants ();
warn << "BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\n";
panic << "----------------------------------------------------------\n\n\n";
}
rpcnode->child_hash.setsize (keys.size ());
for (u_int i = 0; i < keys.size (); i++) {
rpcnode->child_hash[i] = keys[i];
}
}
}
<commit_msg>Sometimes getkeys will return no keys, even if the hash differs due to restrictions on range. Don't seg fault in this case.<commit_after>#include <chord.h>
#include "merkle_syncer.h"
#include "qhash.h"
#include "async.h"
#include "bigint.h"
#include <id_utils.h>
#include <comm.h>
#include <modlogger.h>
#define warning modlogger ("merkle", modlogger::WARNING)
#define info modlogger ("merkle", modlogger::INFO)
#define trace modlogger ("merkle", modlogger::TRACE)
// ---------------------------------------------------------------------------
// util junk
// Check whether [l1, r1] overlaps [l2, r2] on the circle.
static bool
overlap (const bigint &l1, const bigint &r1, const bigint &l2, const bigint &r2)
{
// There might be a more efficient way to do this..
return (betweenbothincl (l1, r1, l2) || betweenbothincl (l1, r1, r2)
|| betweenbothincl (l2, r2, l1) || betweenbothincl (l2, r2, r1));
}
// ---------------------------------------------------------------------------
// merkle_syncer
merkle_syncer::merkle_syncer (dhash_ctype ctype, merkle_tree *ltree,
rpcfnc_t rpcfnc, missingfnc_t missingfnc)
: ctype (ctype), ltree (ltree), rpcfnc (rpcfnc), missingfnc (missingfnc)
{
fatal_err = NULL;
sync_done = false;
}
void
merkle_syncer::sync (bigint rngmin, bigint rngmax)
{
local_rngmin = rngmin;
local_rngmax = rngmax;
// start at the root of the merkle tree
sendnode (0, 0);
}
void
merkle_syncer::dump ()
{
warn << "THIS: " << (u_int)this << "\n";
warn << " st.size () " << st.size () << "\n";
}
void
merkle_syncer::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)
{
// Must resort to bundling all values into one argument since
// async/callback.h is configured with too few parameters.
struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb,
NULL);
(*rpcfnc) (&args);
}
void
merkle_syncer::setdone ()
{
(*missingfnc) (0, false, true);
sync_done = true;
}
void
merkle_syncer::error (str err)
{
warn << (u_int)this << ": SYNCER ERROR: " << err << "\n";
fatal_err = err;
setdone ();
}
str
merkle_syncer::getsummary ()
{
assert (sync_done);
strbuf sb;
sb << "[" << local_rngmin << "," << local_rngmax << "] ";
if (fatal_err)
sb << fatal_err;
if (0)
sb << "<log " << log << ">\n";
return sb;
}
void
merkle_syncer::next (void)
{
trace << "local range [" << local_rngmin << "," << local_rngmax << "]\n";
assert (!sync_done);
assert (!fatal_err);
// st is queue of pending index nodes
while (st.size ()) {
pair<merkle_rpc_node, int> &p = st.back ();
merkle_rpc_node *rnode = &p.first;
assert (!rnode->isleaf);
merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);
if (!lnode) {
fatal << "lookup_exact didn't match for " << rnode->prefix << " at depth " << rnode->depth << "\n";
}
trace << "starting from slot " << p.second << "\n";
while (p.second < 64) {
u_int i = p.second;
p.second += 1;
trace << "CHECKING: " << i;
bigint remote = tobigint (rnode->child_hash[i]);
bigint local = tobigint (lnode->child (i)->hash);
u_int depth = rnode->depth + 1;
//prefix is the high bits of the first key
// the node is responsible for.
merkle_hash prefix = rnode->prefix;
prefix.write_slot (rnode->depth, i);
bigint slot_rngmin = tobigint (prefix);
bigint slot_width = bigint (1) << (160 - 6*depth);
bigint slot_rngmax = slot_rngmin + slot_width - 1;
bool overlaps = overlap (local_rngmin, local_rngmax, slot_rngmin, slot_rngmax);
strbuf tr;
if (remote != local) {
tr << " differ. local " << local << " != remote " << remote;
if (overlaps) {
tr << " .. sending\n";
sendnode (depth, prefix);
trace << tr;
return;
} else {
tr << " .. not sending\n";
}
} else {
tr << " same. local " << local << " == remote " << remote << "\n";
}
trace << tr;
}
assert (p.second == 64);
st.pop_back ();
}
trace << "DONE .. in NEXT\n";
setdone ();
trace << "OK!\n";
}
void
merkle_syncer::sendnode (u_int depth, const merkle_hash &prefix)
{
ref<sendnode_arg> arg = New refcounted<sendnode_arg> ();
ref<sendnode_res> res = New refcounted<sendnode_res> ();
u_int lnode_depth;
merkle_node *lnode = ltree->lookup (&lnode_depth, depth, prefix);
// OK to assert this: since depth-1 is an index node, we know that
// it created all of its depth children when
// it split. --FED
assert (lnode);
assert (lnode_depth == depth);
format_rpcnode (ltree, depth, prefix, lnode, &arg->node);
arg->ctype = ctype;
arg->rngmin = local_rngmin;
arg->rngmax = local_rngmax;
doRPC (MERKLESYNC_SENDNODE, arg, res,
wrap (this, &merkle_syncer::sendnode_cb, arg, res));
}
void
merkle_syncer::sendnode_cb (ref<sendnode_arg> arg, ref<sendnode_res> res,
clnt_stat err)
{
if (err) {
error (strbuf () << "SENDNODE: rpc error " << err);
return;
} else if (res->status != MERKLE_OK) {
error (strbuf () << "SENDNODE: protocol error " << err2str (res->status));
return;
}
merkle_rpc_node *rnode = &res->resok->node;
merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);
if (!lnode) {
fatal << "lookup failed: " << rnode->prefix << " at " << rnode->depth << "\n";
}
compare_nodes (ltree, local_rngmin, local_rngmax, lnode, rnode,
ctype, missingfnc, rpcfnc);
if (!lnode->isleaf () && !rnode->isleaf) {
trace << "I vs I\n";
st.push_back (pair<merkle_rpc_node, int> (*rnode, 0));
}
next ();
}
// ---------------------------------------------------------------------------
// merkle_getkeyrange
void
merkle_getkeyrange::go ()
{
if (!betweenbothincl (rngmin, rngmax, current)) {
trace << "merkle_getkeyrange::go () ==> DONE\n";
delete this;
return;
}
ref<getkeys_arg> arg = New refcounted<getkeys_arg> ();
arg->ctype = ctype;
arg->rngmin = current;
arg->rngmax = rngmax;
ref<getkeys_res> res = New refcounted<getkeys_res> ();
doRPC (MERKLESYNC_GETKEYS, arg, res,
wrap (this, &merkle_getkeyrange::getkeys_cb, arg, res));
}
void
merkle_getkeyrange::getkeys_cb (ref<getkeys_arg> arg, ref<getkeys_res> res,
clnt_stat err)
{
if (err) {
warn << "GETKEYS: rpc error " << err << "\n";
delete this;
return;
} else if (res->status != MERKLE_OK) {
warn << "GETKEYS: protocol error " << err2str (res->status) << "\n";
delete this;
return;
}
// Assuming keys are sent back in increasing clockwise order
vec<merkle_hash> rkeys;
for (u_int i = 0; i < res->resok->keys.size (); i++) {
const merkle_hash &key = res->resok->keys[i];
rkeys.push_back (key);
}
chordID sentmax = rngmax;
if (res->resok->keys.size () > 0)
sentmax = tobigint (res->resok->keys.back ());
compare_keylists (lkeys, rkeys, current, sentmax, missing);
current = incID (sentmax);
if (!res->resok->morekeys)
current = incID (rngmax); // set done
go ();
}
void
merkle_getkeyrange::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)
{
// Must resort to bundling all values into one argument since
// async/callback.h is configured with too few parameters.
struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb,
NULL);
(*rpcfnc) (&args);
}
// ---------------------------------------------------------------------------
void
compare_keylists (vec<merkle_hash> lkeys,
vec<merkle_hash> vrkeys,
chordID rngmin, chordID rngmax,
missingfnc_t missingfnc)
{
// populate a hash table with the remote keys
qhash<merkle_hash, int> rkeys;
for (u_int i = 0; i < vrkeys.size (); i++) {
if (betweenbothincl (rngmin, rngmax, tobigint(vrkeys[i])))
rkeys.insert (vrkeys[i], 1);
}
// do I have something he doesn't have?
for (unsigned int i = 0; i < lkeys.size (); i++) {
if (!rkeys[lkeys[i]] &&
betweenbothincl (rngmin, rngmax, tobigint(lkeys[i]))) {
trace << "remote missing [" << rngmin << ", " << rngmax << "] key=" << lkeys[i] << "\n";
(*missingfnc) (tobigint(lkeys[i]), false, false);
} else {
rkeys.remove (lkeys[i]);
}
}
//anything left: he has and I don't
qhash_slot<merkle_hash, int> *slot = rkeys.first ();
while (slot) {
trace << "local missing [" << rngmin << ", " << rngmax << "] key=" << slot->key << "\n";
(*missingfnc) (tobigint(slot->key), true, false);
slot = rkeys.next (slot);
}
}
void
compare_nodes (merkle_tree *ltree, bigint rngmin, bigint rngmax,
merkle_node *lnode, merkle_rpc_node *rnode,
dhash_ctype ctype,
missingfnc_t missingfnc, rpcfnc_t rpcfnc)
{
trace << (lnode->isleaf () ? "L" : "I")
<< " vs "
<< (rnode->isleaf ? "L" : "I")
<< "\n";
if (rnode->isleaf) {
vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);
vec<merkle_hash> rkeys;
for (u_int i = 0; i < rnode->child_hash.size (); i++)
rkeys.push_back (rnode->child_hash[i]);
compare_keylists (lkeys, rkeys, rngmin, rngmax, missingfnc);
} else if (lnode->isleaf () && !rnode->isleaf) {
bigint tmpmin = tobigint (rnode->prefix);
bigint node_width = bigint (1) << (160 - rnode->depth);
bigint tmpmax = tmpmin + node_width - 1;
// further constrain to be within the host's range of interest
if (between (tmpmin, tmpmax, rngmin))
tmpmin = rngmin;
if (between (tmpmin, tmpmax, rngmax))
tmpmax = rngmax;
vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);
vNew merkle_getkeyrange (ctype, ltree->db, tmpmin, tmpmax, lkeys,
missingfnc, rpcfnc);
}
}
// ---------------------------------------------------------------------------
void
format_rpcnode (merkle_tree *ltree, u_int depth, const merkle_hash &prefix,
const merkle_node *node, merkle_rpc_node *rpcnode)
{
rpcnode->depth = depth;
rpcnode->prefix = prefix;
rpcnode->count = node->count;
rpcnode->hash = node->hash;
rpcnode->isleaf = node->isleaf ();
if (!node->isleaf ()) {
rpcnode->child_hash.setsize (64);
for (int i = 0; i < 64; i++)
rpcnode->child_hash[i] = node->child (i)->hash;
} else {
vec<merkle_hash> keys = database_get_keys (ltree->db, depth, prefix);
if (keys.size () != rpcnode->count) {
warn << "\n\n\n----------------------------------------------------------\n";
warn << "BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\n";
warn << "Send this output to [email protected]\n";
warn << "BUG: " << depth << " " << prefix << "\n";
warn << "BUG: " << keys.size () << " != " << rpcnode->count << "\n";
ltree->check_invariants ();
warn << "BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\n";
panic << "----------------------------------------------------------\n\n\n";
}
rpcnode->child_hash.setsize (keys.size ());
for (u_int i = 0; i < keys.size (); i++) {
rpcnode->child_hash[i] = keys[i];
}
}
}
<|endoftext|>
|
<commit_before>/*!
@file XYZReader.hpp
@brief definition of a class that reads xyz file.
@author Toru Niina ([email protected])
@date 2017-01-05 17:00
@copyright Toru Niina 2016 on MIT License
*/
#ifndef COFFEE_MILL_XYZ_READER_HPP
#define COFFEE_MILL_XYZ_READER_HPP
#include <mill/common/Trajectory.hpp>
#include <memory>
#include <utility>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <vector>
namespace mill
{
//! read XYZfile and return the data as std::vector<std::vector<position>>.
/*!
* @tparam vectorT type of position
*/
template<typename vectorT>
class XYZReader
{
public:
using vector_type = vectorT;
using trajectory_type = Trajectory<vector_type>;
using snapshot_type = typename trajectory_type::snapshot_type;
using particle_type = typename snapshot_type::particle_type;
public:
XYZReader(const std::string& fname): xyz_(fname)
{
if(!xyz_.good())
{
throw std::runtime_error("XYZReader: file open error: " + fname);
}
}
~XYZReader() = default;
trajectory_type read();
snapshot_type read_frame();
bool is_eof() const noexcept {return xyz_.eof();}
private:
std::ifstream xyz_;
};
template<typename vecT>
typename XYZReader<vecT>::trajectory_type XYZReader<vecT>::read()
{
trajectory_type traj;
while(!this->xyz_.eof())
{
traj.snapshots().push_back(this->read_frame());
this->xyz_.peek();
}
return traj;
}
template<typename vecT>
typename XYZReader<vecT>::snapshot_type XYZReader<vecT>::read_frame()
{
std::string line;
std::getline(this->xyz_, line);
std::size_t N = 0;
try
{
N = std::stoull(line);
}
catch(...)
{
throw std::runtime_error("XYZReader::read_frame: expected number, "
"but got " + line);
}
snapshot_type frame(N);
std::getline(this->xyz_, line);
frame.at("comment") = line;
for(std::size_t i=0; i<N; ++i)
{
std::getline(this->xyz_, line);
std::istringstream iss(line);
std::string atom;
double x, y, z;
iss >> atom >> x >> y >> z;
particle_type p(vector_type(x, y, z), {{"name", atom}});
frame.particles().push_back(std::move(p));
}
return frame;
}
}// mill
#endif //COFFEE_MILL_XYZ_READER
<commit_msg>:bug: fix XYZReader.read<commit_after>/*!
@file XYZReader.hpp
@brief definition of a class that reads xyz file.
@author Toru Niina ([email protected])
@date 2017-01-05 17:00
@copyright Toru Niina 2016 on MIT License
*/
#ifndef COFFEE_MILL_XYZ_READER_HPP
#define COFFEE_MILL_XYZ_READER_HPP
#include <mill/common/Trajectory.hpp>
#include <memory>
#include <utility>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
namespace mill
{
//! read XYZfile and return the data as std::vector<std::vector<position>>.
/*!
* @tparam vectorT type of position
*/
template<typename vectorT>
class XYZReader
{
public:
using vector_type = vectorT;
using trajectory_type = Trajectory<vector_type>;
using snapshot_type = typename trajectory_type::snapshot_type;
using particle_type = typename snapshot_type::particle_type;
public:
XYZReader(const std::string& fname): xyz_(fname)
{
if(!xyz_.good())
{
throw std::runtime_error("XYZReader: file open error: " + fname);
}
}
~XYZReader() = default;
trajectory_type read();
snapshot_type read_frame();
bool is_eof() const noexcept {return xyz_.eof();}
private:
std::ifstream xyz_;
};
template<typename vecT>
typename XYZReader<vecT>::trajectory_type XYZReader<vecT>::read()
{
trajectory_type traj;
while(!this->xyz_.eof())
{
traj.snapshots().push_back(this->read_frame());
this->xyz_.peek();
}
return traj;
}
template<typename vecT>
typename XYZReader<vecT>::snapshot_type XYZReader<vecT>::read_frame()
{
std::string line;
std::getline(this->xyz_, line);
std::size_t N = 0;
try
{
N = std::stoull(line);
}
catch(...)
{
throw std::runtime_error("XYZReader::read_frame: expected number, "
"but got " + line);
}
snapshot_type frame(N);
std::getline(this->xyz_, line);
frame["comment"] = line;
for(std::size_t i=0; i<N; ++i)
{
std::getline(this->xyz_, line);
std::istringstream iss(line);
std::string atom;
double x, y, z;
iss >> atom >> x >> y >> z;
particle_type p(vector_type(x, y, z), {{"name", atom}});
frame.at(i) = std::move(p);
}
return frame;
}
}// mill
#endif //COFFEE_MILL_XYZ_READER
<|endoftext|>
|
<commit_before>/* Gobby - GTK-based collaborative text editor
* Copyright (C) 2008-2011 Armin Burgmeier <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "features.hpp"
#include "window.hpp"
#include "core/iconmanager.hpp"
#include "util/config.hpp"
#include "util/file.hpp"
#include "util/i18n.hpp"
#include <libinfinity/common/inf-init.h>
#include <gtkmm/main.h>
#include <gtkmm/messagedialog.h>
#include <giomm/init.h>
#include <glibmm/optionentry.h>
#include <glibmm/optiongroup.h>
#include <glibmm/optioncontext.h>
#ifdef WITH_UNIQUE
# include <unique/unique.h>
#endif
#include <libintl.h> // bindtextdomain
#include <iostream>
#include <vector>
namespace
{
void handle_exception(const Glib::ustring& message)
{
Gtk::MessageDialog dlg("Unhandled exception", false,
Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
dlg.set_secondary_text(message);
dlg.run();
std::cerr << "Unhandled exception: " << message << std::endl;
}
const char* _(const char* str)
{
return Gobby::_(str);
}
std::string gobby_localedir()
{
#ifdef G_OS_WIN32
gchar* root =
g_win32_get_package_installation_directory_of_module(
NULL);
gchar* temp = g_build_filename(root, "share", "locale", NULL);
g_free(root);
gchar* result = g_win32_locale_filename_from_utf8(temp);
g_free(temp);
std::string cpp_result(result);
g_free(result);
return cpp_result;
#else
return GOBBY_LOCALEDIR;
#endif
}
#ifdef WITH_UNIQUE
int send_message_with_uris(UniqueApp* app,
gint message_id,
const std::vector<Glib::ustring>& uris)
{
std::vector<const gchar*> uri_cstrs(uris.size() + 1);
for(unsigned int i = 0; i < uris.size(); ++i)
uri_cstrs[i] = uris[i].c_str();
UniqueMessageData* message = unique_message_data_new();
unique_message_data_set_uris(
message, const_cast<gchar**>(&uri_cstrs[0]));
UniqueResponse response = unique_app_send_message(
app, message_id, message);
unique_message_data_free(message);
if(response == UNIQUE_RESPONSE_OK)
{
return 0;
}
else
{
std::cerr
<< "error sending URIs to existing gobby "
"instance (libunique): "
<< static_cast<int>(response)
<< std::endl;
return -1;
}
}
int my_unique_activate(UniqueApp* app) {
UniqueResponse response =
unique_app_send_message(app, UNIQUE_ACTIVATE, NULL);
if(response != UNIQUE_RESPONSE_OK)
{
std::cerr
<< "error activating existing gobby "
"instance (libunique): "
<< static_cast<int>(response)
<< std::endl;
return -1;
}
else
{
return 0;
}
}
int my_unique_send_file_args(UniqueApp* app,
int argc,
const char* const* argv)
{
std::vector<Glib::ustring> uris(argc);
for(int i = 0; i < argc; ++i)
{
uris[i] = Gio::File::create_for_commandline_arg(
argv[i])->get_uri();
}
return send_message_with_uris(app, UNIQUE_OPEN, uris);
}
int my_unique_send_hostname_args(
UniqueApp* app,
const std::vector<Glib::ustring>& hostnames)
{
std::vector<Glib::ustring> uris(hostnames);
for(unsigned int i = 0; i < uris.size(); ++i)
{
uris[i].insert(0, "infinote://");
}
return send_message_with_uris(
app, Gobby::UNIQUE_GOBBY_CONNECT, uris);
}
int my_unique_check_other(UniqueApp* app,
int argc, const char* const* argv,
const std::vector<Glib::ustring>& hostnames)
{
if(argc == 0 && hostnames.empty())
{
return my_unique_activate(app);
}
if(argc) {
if(my_unique_send_file_args(app, argc, argv) != 0)
return -1;
}
if(!hostnames.empty()) {
if (my_unique_send_hostname_args(app, hostnames))
return -1;
}
return 0;
}
#endif // WITH_UNIQUE
}
int main(int argc, char* argv[]) try
{
g_thread_init(NULL);
Gio::init();
setlocale(LC_ALL, "");
bindtextdomain(GETTEXT_PACKAGE, gobby_localedir().c_str());
bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
bool new_instance = false;
bool display_version = false;
std::vector<Glib::ustring> hostnames;
Glib::OptionGroup opt_group_gobby("gobby",
_("Gobby options"), _("Options related to Gobby"));
Glib::OptionEntry opt_version;
opt_version.set_short_name('v');
opt_version.set_long_name("version");
opt_version.set_description(
_("Display version information and exit"));
opt_group_gobby.add_entry(opt_version, display_version);
Glib::OptionEntry opt_new_instance;
opt_new_instance.set_short_name('n');
opt_new_instance.set_long_name("new-instance");
opt_new_instance.set_description(
_("Also start a new Gobby instance when there is one "
"running already"));
opt_group_gobby.add_entry(opt_new_instance, new_instance);
Glib::OptionEntry opt_connect;
opt_connect.set_short_name('c');
opt_connect.set_long_name("connect");
opt_connect.set_description(
_("Connect to given host on startup, can be given multiple times"));
opt_connect.set_arg_description(_("HOSTNAME"));
opt_group_gobby.add_entry(opt_connect, hostnames);
Glib::OptionContext opt_ctx;
opt_ctx.set_help_enabled(true);
opt_ctx.set_ignore_unknown_options(false);
opt_ctx.set_main_group(opt_group_gobby);
// I would rather like to have Gtk::Main on the stack, but I see
// no other chance to catch exceptions from the command line option
// parsing. armin.
// TODO: Maybe we should parse before initializing GTK+, using
// Gtk::Main::add_gtk_option_group() with open_default_display set
// to false.
std::auto_ptr<Gtk::Main> kit;
try
{
kit.reset(new Gtk::Main(argc, argv, opt_ctx));
}
catch(Glib::Exception& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
if(display_version)
{
std::cout << "Gobby " << PACKAGE_VERSION << std::endl;
return EXIT_SUCCESS;
}
#ifdef WITH_UNIQUE
UniqueApp* app = unique_app_new_with_commands(
"de._0x539.gobby", NULL,
"UNIQUE_GOBBY_CONNECT", Gobby::UNIQUE_GOBBY_CONNECT,
NULL);
if(!new_instance && unique_app_is_running(app))
{
int exit_code = my_unique_check_other(
app,
argc - 1, argv + 1,
hostnames);
g_object_unref(app);
return exit_code;
}
#endif // WITH_UNIQUE
GError* error = NULL;
if(!inf_init(&error))
{
std::string message = error->message;
g_error_free(error);
throw std::runtime_error(message);
}
Gobby::IconManager icon_manager;
// Set default icon
Gtk::Window::set_default_icon_name("gobby-0.5");
// Read the configuration
Gobby::Config config(Gobby::config_filename("config.xml"));
// Create window
Gobby::Window wnd(
argc-1,
argv+1,
icon_manager,
config
#ifdef WITH_UNIQUE
, app
#endif
);
#ifdef WITH_UNIQUE
g_object_unref(app);
#endif
wnd.show();
for(std::vector<Glib::ustring>::const_iterator i = hostnames.begin();
i != hostnames.end();
++ i)
{
wnd.connect_to_host(*i);
}
wnd.signal_hide().connect(sigc::ptr_fun(&Gtk::Main::quit) );
kit->run();
//inf_deinit();
return 0;
}
catch(Glib::Exception& e)
{
handle_exception(e.what() );
}
catch(std::exception& e)
{
handle_exception(e.what() );
}
<commit_msg>Fix a crash when gobby is invoked with invalid UTF-8 on the command line<commit_after>/* Gobby - GTK-based collaborative text editor
* Copyright (C) 2008-2011 Armin Burgmeier <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "features.hpp"
#include "window.hpp"
#include "core/iconmanager.hpp"
#include "util/config.hpp"
#include "util/file.hpp"
#include "util/i18n.hpp"
#include <libinfinity/common/inf-init.h>
#include <gtkmm/main.h>
#include <gtkmm/messagedialog.h>
#include <giomm/init.h>
#include <glibmm/optionentry.h>
#include <glibmm/optiongroup.h>
#include <glibmm/optioncontext.h>
#ifdef WITH_UNIQUE
# include <unique/unique.h>
#endif
#include <libintl.h> // bindtextdomain
#include <iostream>
#include <vector>
namespace
{
void handle_exception(const Glib::ustring& message)
{
Gtk::MessageDialog dlg("Unhandled exception", false,
Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
dlg.set_secondary_text(message);
dlg.run();
std::cerr << "Unhandled exception: " << message << std::endl;
}
const char* _(const char* str)
{
return Gobby::_(str);
}
std::string gobby_localedir()
{
#ifdef G_OS_WIN32
gchar* root =
g_win32_get_package_installation_directory_of_module(
NULL);
gchar* temp = g_build_filename(root, "share", "locale", NULL);
g_free(root);
gchar* result = g_win32_locale_filename_from_utf8(temp);
g_free(temp);
std::string cpp_result(result);
g_free(result);
return cpp_result;
#else
return GOBBY_LOCALEDIR;
#endif
}
#ifdef WITH_UNIQUE
int send_message_with_uris(UniqueApp* app,
gint message_id,
const std::vector<Glib::ustring>& uris)
{
std::vector<const gchar*> uri_cstrs(uris.size() + 1);
for(unsigned int i = 0; i < uris.size(); ++i)
uri_cstrs[i] = uris[i].c_str();
UniqueMessageData* message = unique_message_data_new();
unique_message_data_set_uris(
message, const_cast<gchar**>(&uri_cstrs[0]));
UniqueResponse response = unique_app_send_message(
app, message_id, message);
unique_message_data_free(message);
if(response == UNIQUE_RESPONSE_OK)
{
return 0;
}
else
{
std::cerr
<< "error sending URIs to existing gobby "
"instance (libunique): "
<< static_cast<int>(response)
<< std::endl;
return -1;
}
}
int my_unique_activate(UniqueApp* app) {
UniqueResponse response =
unique_app_send_message(app, UNIQUE_ACTIVATE, NULL);
if(response != UNIQUE_RESPONSE_OK)
{
std::cerr
<< "error activating existing gobby "
"instance (libunique): "
<< static_cast<int>(response)
<< std::endl;
return -1;
}
else
{
return 0;
}
}
int my_unique_send_file_args(UniqueApp* app,
int argc,
const char* const* argv)
{
std::vector<Glib::ustring> uris(argc);
for(int i = 0; i < argc; ++i)
{
uris[i] = Gio::File::create_for_commandline_arg(
argv[i])->get_uri();
}
return send_message_with_uris(app, UNIQUE_OPEN, uris);
}
int my_unique_send_hostname_args(
UniqueApp* app,
const std::vector<Glib::ustring>& hostnames)
{
std::vector<Glib::ustring> uris(hostnames);
for(unsigned int i = 0; i < uris.size(); ++i)
{
uris[i].insert(0, "infinote://");
}
return send_message_with_uris(
app, Gobby::UNIQUE_GOBBY_CONNECT, uris);
}
int my_unique_check_other(UniqueApp* app,
int argc, const char* const* argv,
const std::vector<Glib::ustring>& hostnames)
{
if(argc == 0 && hostnames.empty())
{
return my_unique_activate(app);
}
if(argc) {
if(my_unique_send_file_args(app, argc, argv) != 0)
return -1;
}
if(!hostnames.empty()) {
if (my_unique_send_hostname_args(app, hostnames))
return -1;
}
return 0;
}
#endif // WITH_UNIQUE
}
int main(int argc, char* argv[]) try
{
g_thread_init(NULL);
Gio::init();
setlocale(LC_ALL, "");
bindtextdomain(GETTEXT_PACKAGE, gobby_localedir().c_str());
bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
bool new_instance = false;
bool display_version = false;
std::vector<Glib::ustring> hostnames;
Glib::OptionGroup opt_group_gobby("gobby",
_("Gobby options"), _("Options related to Gobby"));
Glib::OptionEntry opt_version;
opt_version.set_short_name('v');
opt_version.set_long_name("version");
opt_version.set_description(
_("Display version information and exit"));
opt_group_gobby.add_entry(opt_version, display_version);
Glib::OptionEntry opt_new_instance;
opt_new_instance.set_short_name('n');
opt_new_instance.set_long_name("new-instance");
opt_new_instance.set_description(
_("Also start a new Gobby instance when there is one "
"running already"));
opt_group_gobby.add_entry(opt_new_instance, new_instance);
Glib::OptionEntry opt_connect;
opt_connect.set_short_name('c');
opt_connect.set_long_name("connect");
opt_connect.set_description(
_("Connect to given host on startup, can be given multiple times"));
opt_connect.set_arg_description(_("HOSTNAME"));
opt_group_gobby.add_entry(opt_connect, hostnames);
Glib::OptionContext opt_ctx;
opt_ctx.set_help_enabled(true);
opt_ctx.set_ignore_unknown_options(false);
opt_ctx.set_main_group(opt_group_gobby);
// I would rather like to have Gtk::Main on the stack, but I see
// no other chance to catch exceptions from the command line option
// parsing. armin.
// TODO: Maybe we should parse before initializing GTK+, using
// Gtk::Main::add_gtk_option_group() with open_default_display set
// to false.
std::auto_ptr<Gtk::Main> kit;
try
{
kit.reset(new Gtk::Main(argc, argv, opt_ctx));
}
catch(Glib::Exception& e)
{
// Protect for non-UTF8 command lines (GTK probably already
// converts to UTF-8 in case the system locale is not UTF-8,
// but it can happen that input is given not in the system
// locale, or simply invalid UTF-8. In that case, printing
// e.what() on stdout would throw another exception, which we
// want to avoid here, because otherwise we would want to
// show that exception in an error dialog, but GTK+ failed
// to initialize.
if(e.what().validate())
std::cerr << e.what() << std::endl;
else
std::cerr << "Invalid input on command line" << std::endl;
return EXIT_FAILURE;
}
if(display_version)
{
std::cout << "Gobby " << PACKAGE_VERSION << std::endl;
return EXIT_SUCCESS;
}
#ifdef WITH_UNIQUE
UniqueApp* app = unique_app_new_with_commands(
"de._0x539.gobby", NULL,
"UNIQUE_GOBBY_CONNECT", Gobby::UNIQUE_GOBBY_CONNECT,
NULL);
if(!new_instance && unique_app_is_running(app))
{
int exit_code = my_unique_check_other(
app,
argc - 1, argv + 1,
hostnames);
g_object_unref(app);
return exit_code;
}
#endif // WITH_UNIQUE
GError* error = NULL;
if(!inf_init(&error))
{
std::string message = error->message;
g_error_free(error);
throw std::runtime_error(message);
}
Gobby::IconManager icon_manager;
// Set default icon
Gtk::Window::set_default_icon_name("gobby-0.5");
// Read the configuration
Gobby::Config config(Gobby::config_filename("config.xml"));
// Create window
Gobby::Window wnd(
argc-1,
argv+1,
icon_manager,
config
#ifdef WITH_UNIQUE
, app
#endif
);
#ifdef WITH_UNIQUE
g_object_unref(app);
#endif
wnd.show();
for(std::vector<Glib::ustring>::const_iterator i = hostnames.begin();
i != hostnames.end();
++ i)
{
wnd.connect_to_host(*i);
}
wnd.signal_hide().connect(sigc::ptr_fun(&Gtk::Main::quit) );
kit->run();
//inf_deinit();
return 0;
}
catch(Glib::Exception& e)
{
handle_exception(e.what() );
}
catch(std::exception& e)
{
handle_exception(e.what() );
}
<|endoftext|>
|
<commit_before>// MFEM Example 1 - NURBS Version
//
// Compile with: make ex1
//
// Sample runs: ex1 -m ../../data/square-disc.mesh
// ex1 -m ../../data/star.mesh
// ex1 -m ../../data/escher.mesh
// ex1 -m ../../data/fichera.mesh
// ex1 -m ../../data/square-disc-p2.vtk -o 2
// ex1 -m ../../data/square-disc-p3.mesh -o 3
// ex1 -m ../../data/square-disc-nurbs.mesh -o -1
// ex1 -m ../../data/disc-nurbs.mesh -o -1
// ex1 -m ../../data/pipe-nurbs.mesh -o -1
// ex1 -m ../../data/star-surf.mesh
// ex1 -m ../../data/square-disc-surf.mesh
// ex1 -m ../../data/inline-segment.mesh
// ex1 -m ../../data/amr-quad.mesh
// ex1 -m ../../data/amr-hex.mesh
// ex1 -m ../../data/fichera-amr.mesh
// ex1 -m ../../data/mobius-strip.mesh
// ex1 -m ../../data/mobius-strip.mesh -o -1 -sc
//
// Description: This example code demonstrates the use of MFEM to define a
// simple finite element discretization of the Laplace problem
// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
// Specifically, we discretize using a FE space of the specified
// order, or if order < 1 using an isoparametric/isogeometric
// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
// NURBS mesh, etc.)
//
// The example highlights the use of mesh refinement, finite
// element grid functions, as well as linear and bilinear forms
// corresponding to the left-hand side and right-hand side of the
// discrete linear system. We also cover the explicit elimination
// of essential boundary conditions, static condensation, and the
// optional connection to the GLVis tool for visualization.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
/** Class for integrating the bilinear form a(u,v) := (Q Laplace u, v) where Q
can be a scalar coefficient. */
class Diffusion2Integrator: public BilinearFormIntegrator
{
private:
#ifndef MFEM_THREAD_SAFE
Vector shape,laplace;
#endif
Coefficient *Q;
public:
/// Construct a diffusion integrator with coefficient Q = 1
Diffusion2Integrator() { Q = NULL; }
/// Construct a diffusion integrator with a scalar coefficient q
Diffusion2Integrator (Coefficient &q) : Q(&q) { }
/** Given a particular Finite Element
computes the element stiffness matrix elmat. */
virtual void AssembleElementMatrix(const FiniteElement &el,
ElementTransformation &Trans,
DenseMatrix &elmat)
{
int nd = el.GetDof();
int dim = el.GetDim();
int spaceDim = Trans.GetSpaceDim();
bool square = (dim == spaceDim);
double w;
#ifdef MFEM_THREAD_SAFE
Vector shape[nd];
Vector laplace(nd);
#else
shape.SetSize(nd);
laplace.SetSize(nd);
#endif
elmat.SetSize(nd);
const IntegrationRule *ir = IntRule;
if (ir == NULL)
{
int order;
if (el.Space() == FunctionSpace::Pk)
{
order = 2*el.GetOrder() - 2;
}
else
{
order = 2*el.GetOrder() + dim - 1;
}
if (el.Space() == FunctionSpace::rQk)
{
ir = &RefinedIntRules.Get(el.GetGeomType(),order);
}
else
{
ir = &IntRules.Get(el.GetGeomType(),order);
}
}
elmat = 0.0;
for (int i = 0; i < ir->GetNPoints(); i++)
{
const IntegrationPoint &ip = ir->IntPoint(i);
Trans.SetIntPoint(&ip);
w = -ip.weight / Trans.Weight();
el.CalcShape(ip, shape);
el.CalcPhysLaplacian(Trans, laplace);
if (Q)
{
w *= Q->Eval(Trans, ip);
}
for (int j = 0; j < nd; j++)
{
for (int i = 0; i < nd; i++)
{
elmat(i, j) += w*shape(i)*laplace(j);
}
}
}
}
};
int main(int argc, char *argv[])
{
// 1. Parse command-line options.
const char *mesh_file = "../../data/star.mesh";
bool static_cond = false;
bool visualization = 1;
bool ibp = 1;
int ref_levels = -1;
Array<int> order(1);
order[0] = 1;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&ref_levels, "-r", "--refine",
"Levels of refinement or -1 for refinement till 50000 elements.");
args.AddOption(&ibp, "-ibp", "--ibp", "-no-ibp",
"--no-ibp",
"Selects the standard weak form (IBP) or the nonstandard (NO-IBP).");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(cout);
return 1;
}
args.PrintOptions(cout);
// 2. Read the mesh from the given mesh file. We can handle triangular,
// quadrilateral, tetrahedral, hexahedral, surface and volume meshes with
// the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// 3. Refine the mesh to increase the resolution. In this example we do
// 'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
// largest number that gives a final mesh with no more than 50,000
// elements.
{
if (ref_levels < 0)
{
ref_levels = (int)floor(log(50000./mesh->GetNE())/log(2.)/dim);
}
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
// 4. Define a finite element space on the mesh. Here we use continuous
// Lagrange finite elements of the specified order. If order < 1, we
// instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec;
NURBSExtension *NURBSext = NULL;
int own_fec = 0;
if (order[0] == -1) // Isoparametric
{
if (mesh->GetNodes())
{
fec = mesh->GetNodes()->OwnFEC();
own_fec = 0;
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
else
{
cout <<"Mesh does not have FEs --> Assume order 1.\n";
fec = new H1_FECollection(1, dim);
own_fec = 1;
}
}
else if (mesh->NURBSext && (order[0] > 0) ) // Subparametric NURBS
{
fec = new NURBSFECollection(order[0]);
own_fec = 1;
int nkv = mesh->NURBSext->GetNKV();
if (order.Size() == 1)
{
int tmp = order[0];
order.SetSize(nkv);
order = tmp;
}
if (order.Size() != nkv ) { mfem_error("Wrong number of orders set."); }
NURBSext = new NURBSExtension(mesh->NURBSext, order);
}
else
{
if (order.Size() > 1) { cout <<"Wrong number of orders set, needs one.\n"; }
fec = new H1_FECollection(abs(order[0]), dim);
own_fec = 1;
}
FiniteElementSpace *fespace = new FiniteElementSpace(mesh, NURBSext, fec);
cout << "Number of finite element unknowns: "
<< fespace->GetTrueVSize() << endl;
// 5. Determine the list of true (i.e. conforming) essential boundary dofs.
// In this example, the boundary conditions are defined by marking all
// the boundary attributes from the mesh as essential (Dirichlet) and
// converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (mesh->bdr_attributes.Size())
{
Array<int> ess_bdr(mesh->bdr_attributes.Max());
ess_bdr = 1;
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 6. Set up the linear form b(.) which corresponds to the right-hand side of
// the FEM linear system, which in this case is (1,phi_i) where phi_i are
// the basis functions in the finite element fespace.
LinearForm *b = new LinearForm(fespace);
ConstantCoefficient one(1.0);
b->AddDomainIntegrator(new DomainLFIntegrator(one));
b->Assemble();
// 7. Define the solution vector x as a finite element grid function
// corresponding to fespace. Initialize x with initial guess of zero,
// which satisfies the boundary conditions.
GridFunction x(fespace);
x = 0.0;
// 8. Set up the bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the Diffusion
// domain integrator.
BilinearForm *a = new BilinearForm(fespace);
if (ibp)
{
a->AddDomainIntegrator(new DiffusionIntegrator(one));
}
else
{
a->AddDomainIntegrator(new Diffusion2Integrator(one));
}
// 9. Assemble the bilinear form and the corresponding linear system,
// applying any necessary transformations such as: eliminating boundary
// conditions, applying conforming constraints for non-conforming AMR,
// static condensation, etc.
if (static_cond) { a->EnableStaticCondensation(); }
a->Assemble();
SparseMatrix A;
Vector B, X;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
cout << "Size of linear system: " << A.Height() << endl;
#ifndef MFEM_USE_SUITESPARSE
// 10. Define a simple symmetric Gauss-Seidel preconditioner and use it to
// solve the system A X = B with PCG.
GSSmoother M(A);
PCG(A, M, B, X, 1, 200, 1e-12, 0.0);
#else
// 10. If MFEM was compiled with SuiteSparse, use UMFPACK to solve the system.
UMFPackSolver umf_solver;
umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS;
umf_solver.SetOperator(A);
umf_solver.Mult(B, X);
#endif
// 11. Recover the solution as a finite element grid function.
a->RecoverFEMSolution(X, *b, x);
// 12. Save the refined mesh and the solution. This output can be viewed later
// using GLVis: "glvis -m refined.mesh -g sol.gf".
ofstream mesh_ofs("refined.mesh");
mesh_ofs.precision(8);
mesh->Print(mesh_ofs);
ofstream sol_ofs("sol.gf");
sol_ofs.precision(8);
x.Save(sol_ofs);
// 13. Send the solution by socket to a GLVis server.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock.precision(8);
sol_sock << "solution\n" << *mesh << x << flush;
}
// 14. Save data in the VisIt format
VisItDataCollection visit_dc("Example1", mesh);
visit_dc.RegisterField("solution", &x);
visit_dc.Save();
// 15. Free the used memory.
delete a;
delete b;
delete fespace;
if (own_fec) { delete fec; }
delete mesh;
return 0;
}
<commit_msg>Add cubic option + Switch to GMRES<commit_after>// MFEM Example 1 - NURBS Version
//
// Compile with: make ex1
//
// Sample runs: ex1 -m ../../data/square-disc.mesh
// ex1 -m ../../data/star.mesh
// ex1 -m ../../data/escher.mesh
// ex1 -m ../../data/fichera.mesh
// ex1 -m ../../data/square-disc-p2.vtk -o 2
// ex1 -m ../../data/square-disc-p3.mesh -o 3
// ex1 -m ../../data/square-disc-nurbs.mesh -o -1
// ex1 -m ../../data/disc-nurbs.mesh -o -1
// ex1 -m ../../data/pipe-nurbs.mesh -o -1
// ex1 -m ../../data/star-surf.mesh
// ex1 -m ../../data/square-disc-surf.mesh
// ex1 -m ../../data/inline-segment.mesh
// ex1 -m ../../data/amr-quad.mesh
// ex1 -m ../../data/amr-hex.mesh
// ex1 -m ../../data/fichera-amr.mesh
// ex1 -m ../../data/mobius-strip.mesh
// ex1 -m ../../data/mobius-strip.mesh -o -1 -sc
//
// Description: This example code demonstrates the use of MFEM to define a
// simple finite element discretization of the Laplace problem
// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
// Specifically, we discretize using a FE space of the specified
// order, or if order < 1 using an isoparametric/isogeometric
// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
// NURBS mesh, etc.)
//
// The example highlights the use of mesh refinement, finite
// element grid functions, as well as linear and bilinear forms
// corresponding to the left-hand side and right-hand side of the
// discrete linear system. We also cover the explicit elimination
// of essential boundary conditions, static condensation, and the
// optional connection to the GLVis tool for visualization.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
/** Class for integrating the bilinear form a(u,v) := (Q Laplace u, v) where Q
can be a scalar coefficient. */
class Diffusion2Integrator: public BilinearFormIntegrator
{
private:
#ifndef MFEM_THREAD_SAFE
Vector shape,laplace;
#endif
Coefficient *Q;
public:
/// Construct a diffusion integrator with coefficient Q = 1
Diffusion2Integrator() { Q = NULL; }
/// Construct a diffusion integrator with a scalar coefficient q
Diffusion2Integrator (Coefficient &q) : Q(&q) { }
/** Given a particular Finite Element
computes the element stiffness matrix elmat. */
virtual void AssembleElementMatrix(const FiniteElement &el,
ElementTransformation &Trans,
DenseMatrix &elmat)
{
int nd = el.GetDof();
int dim = el.GetDim();
int spaceDim = Trans.GetSpaceDim();
bool square = (dim == spaceDim);
double w;
#ifdef MFEM_THREAD_SAFE
Vector shape[nd];
Vector laplace(nd);
#else
shape.SetSize(nd);
laplace.SetSize(nd);
#endif
elmat.SetSize(nd);
const IntegrationRule *ir = IntRule;
if (ir == NULL)
{
int order;
if (el.Space() == FunctionSpace::Pk)
{
order = 2*el.GetOrder() - 2;
}
else
{
order = 2*el.GetOrder() + dim - 1;
}
if (el.Space() == FunctionSpace::rQk)
{
ir = &RefinedIntRules.Get(el.GetGeomType(),order);
}
else
{
ir = &IntRules.Get(el.GetGeomType(),order);
}
}
elmat = 0.0;
for (int i = 0; i < ir->GetNPoints(); i++)
{
const IntegrationPoint &ip = ir->IntPoint(i);
Trans.SetIntPoint(&ip);
w = -ip.weight / Trans.Weight();
el.CalcShape(ip, shape);
el.CalcPhysLaplacian(Trans, laplace);
if (Q)
{
w *= Q->Eval(Trans, ip);
}
for (int j = 0; j < nd; j++)
{
for (int i = 0; i < nd; i++)
{
elmat(i, j) += w*shape(i)*laplace(j);
}
}
}
}
};
/** Class for a forcing for which the exact answer is known. */
class RectLapForce : public Coefficient
{
public:
double Lx,Ly,fac;
/// c is value of constant function
explicit RectLapForce(double _Lx = 1.0,double _Ly = 1.0 ) { Lx = _Lx; Ly = _Ly; fac = 32.0/(Lx*Lx*Ly*Ly);}
/// Evaluate the coefficient
virtual double Eval(ElementTransformation &T,
const IntegrationPoint &ip)
{
double x[3];
Vector transip(x, 3);
T.Transform(ip, transip);
return fac*(x[0]*(Lx - x[0]) + x[1]*(Ly - x[1]));
}
};
int main(int argc, char *argv[])
{
// 1. Parse command-line options.
const char *mesh_file = "../../data/star.mesh";
bool static_cond = false;
bool visualization = 1;
bool ibp = 1;
int ref_levels = -1;
Array<int> order(1);
order[0] = 1;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&ref_levels, "-r", "--refine",
"Levels of refinement or -1 for refinement till 50000 elements.");
args.AddOption(&ibp, "-ibp", "--ibp", "-no-ibp",
"--no-ibp",
"Selects the standard weak form (IBP) or the nonstandard (NO-IBP).");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(cout);
return 1;
}
args.PrintOptions(cout);
// 2. Read the mesh from the given mesh file. We can handle triangular,
// quadrilateral, tetrahedral, hexahedral, surface and volume meshes with
// the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// 3. Refine the mesh to increase the resolution. In this example we do
// 'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
// largest number that gives a final mesh with no more than 50,000
// elements.
{
if (ref_levels < 0)
{
ref_levels = (int)floor(log(50000./mesh->GetNE())/log(2.)/dim);
}
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
// 4. Define a finite element space on the mesh. Here we use continuous
// Lagrange finite elements of the specified order. If order < 1, we
// instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec;
NURBSExtension *NURBSext = NULL;
int own_fec = 0;
if (order[0] == -1) // Isoparametric
{
if (mesh->GetNodes())
{
fec = mesh->GetNodes()->OwnFEC();
own_fec = 0;
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
else
{
cout <<"Mesh does not have FEs --> Assume order 1.\n";
fec = new H1_FECollection(1, dim);
own_fec = 1;
}
}
else if (order[0] == -3) // Cubics
{
fec = new CubicFECollection();
own_fec = 1;
}
else if (mesh->NURBSext && (order[0] > 0) ) // Subparametric NURBS
{
fec = new NURBSFECollection(order[0]);
own_fec = 1;
int nkv = mesh->NURBSext->GetNKV();
if (order.Size() == 1)
{
int tmp = order[0];
order.SetSize(nkv);
order = tmp;
}
if (order.Size() != nkv ) { mfem_error("Wrong number of orders set."); }
NURBSext = new NURBSExtension(mesh->NURBSext, order);
}
else
{
if (order.Size() > 1) { cout <<"Wrong number of orders set, needs one.\n"; }
fec = new H1_FECollection(abs(order[0]), dim);
own_fec = 1;
}
FiniteElementSpace *fespace = new FiniteElementSpace(mesh, NURBSext, fec);
cout << "Number of finite element unknowns: "
<< fespace->GetTrueVSize() << endl;
// 5. Determine the list of true (i.e. conforming) essential boundary dofs.
// In this example, the boundary conditions are defined by marking all
// the boundary attributes from the mesh as essential (Dirichlet) and
// converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (mesh->bdr_attributes.Size())
{
Array<int> ess_bdr(mesh->bdr_attributes.Max());
ess_bdr = 1;
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 6. Set up the linear form b(.) which corresponds to the right-hand side of
// the FEM linear system, which in this case is (1,phi_i) where phi_i are
// the basis functions in the finite element fespace.
LinearForm *b = new LinearForm(fespace);
ConstantCoefficient one(1.0);
double coord[2];
mesh->GetNode(2, coord);
RectLapForce force(coord[0],coord[1]);
b->AddDomainIntegrator(new DomainLFIntegrator(one));
b->Assemble();
// 7. Define the solution vector x as a finite element grid function
// corresponding to fespace. Initialize x with initial guess of zero,
// which satisfies the boundary conditions.
GridFunction x(fespace);
x = 0.0;
// 8. Set up the bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the Diffusion
// domain integrator.
BilinearForm *a = new BilinearForm(fespace);
if (ibp)
{
a->AddDomainIntegrator(new DiffusionIntegrator(one));
}
else
{
a->AddDomainIntegrator(new Diffusion2Integrator(one));
}
// 9. Assemble the bilinear form and the corresponding linear system,
// applying any necessary transformations such as: eliminating boundary
// conditions, applying conforming constraints for non-conforming AMR,
// static condensation, etc.
if (static_cond) { a->EnableStaticCondensation(); }
a->Assemble();
SparseMatrix A;
Vector B, X;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
cout << "Size of linear system: " << A.Height() << endl;
#ifndef MFEM_USE_SUITESPARSE
// 10. Define a simple Jacobi preconditioner and use it to
// solve the system A X = B with GMRES.
DSmoother M(A);
GMRES(A, M, B, X, 1, 200,100, 1e-12, 0.0);
#else
// 10. If MFEM was compiled with SuiteSparse, use UMFPACK to solve the system.
UMFPackSolver umf_solver;
umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS;
umf_solver.SetOperator(A);
umf_solver.Mult(B, X);
#endif
// 11. Recover the solution as a finite element grid function.
a->RecoverFEMSolution(X, *b, x);
// 12. Save the refined mesh and the solution. This output can be viewed later
// using GLVis: "glvis -m refined.mesh -g sol.gf".
ofstream mesh_ofs("refined.mesh");
mesh_ofs.precision(8);
mesh->Print(mesh_ofs);
ofstream sol_ofs("sol.gf");
sol_ofs.precision(8);
x.Save(sol_ofs);
// 13. Send the solution by socket to a GLVis server.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock.precision(8);
sol_sock << "solution\n" << *mesh << x << flush;
}
// 14. Save data in the VisIt format
VisItDataCollection visit_dc("Example1", mesh);
visit_dc.RegisterField("solution", &x);
visit_dc.Save();
// 15. Free the used memory.
delete a;
delete b;
delete fespace;
if (own_fec) { delete fec; }
delete mesh;
return 0;
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef MAIN_WINDOW_HPP
#define MAIN_WINDOW_HPP
#include <twec/id_holder.hpp>
#include <twec/player_info.hpp>
#include <twec/server_manager.hpp>
#include <twec/utils.hpp>
#include "ui_main_window.h"
#include <QMainWindow>
#include <QMessageBox>
namespace Ui
{class main_window;}
class main_window : public QMainWindow
{
Q_OBJECT
Ui::main_window* m_ui;
QTimer m_update_timer;
twec::server_manager m_servermgr;
public:
main_window(QWidget* parent = nullptr) :
QMainWindow{parent},
m_ui{new Ui::main_window}
{
m_ui->setupUi(this);
connect(&m_servermgr, SIGNAL(log_added(const std::string&)), this, SLOT(_on_log_added(const std::string&)));
connect(&m_servermgr, SIGNAL(connection_timeout()), this, SLOT(_on_connection_timeout()));
connect(&m_servermgr, SIGNAL(connection_lost()), this, SLOT(_on_connection_lost()));
connect(&m_servermgr, SIGNAL(connection_start(const std::string&)), this, SLOT(_on_connection_start(const std::string&)));
connect(&m_servermgr, SIGNAL(logged_in()), this, SLOT(_on_login()));
connect(&m_servermgr, SIGNAL(playerinfo_received(const twec::player_infos&)), this, SLOT(_on_playerinfo_received(const twec::player_infos&)));
connect(&m_servermgr, SIGNAL(job_ended(int)), this, SLOT(_on_job_ended(int)));
connect(&m_update_timer, SIGNAL(timeout()), this, SLOT(update()));
m_update_timer.start(0);
}
~main_window()
{delete m_ui;}
private slots:
void update()
{
// update server, connection, etc...
m_servermgr.update();
// update some ui stuff
for(auto& a : m_servermgr.jobmgr().get_jobs())
{
// this code rly sucks, qt does not provide itering over cells
// TODO: maybe impl celliterating one day
for(auto row(0); row < m_ui->tw_jobs->rowCount(); ++row)
for(auto col(0); col < m_ui->tw_jobs->rowCount(); ++col)
{
auto ptr(twec::to_id_holder(m_ui->tw_jobs->cellWidget(row, col)));
if(ptr)
if(ptr->get_id() == a.get_id())
m_ui->tw_jobs->item(row, 1)->setText(twec::timestr_from_ms(a.get_countdown()).c_str());
}
}
}
void on_btn_login_clicked()
{
m_servermgr.open_econ({m_ui->le_host->text().toStdString(), m_ui->sb_port->text().toStdString()}, m_ui->le_password->text().toStdString());
this->set_window_state("Trying to connect...");
}
// tab: main controlls
void on_btn_change_map_clicked()
{m_servermgr.exec_command("change_map " + m_ui->le_mapname->text().toStdString());}
void on_btn_reload_map_clicked()
{m_servermgr.exec_command("reload");}
void on_btn_start_recording_clicked()
{m_servermgr.exec_command("record " + m_ui->le_record_filename->text().toStdString());}
void on_btn_stop_recording_clicked()
{m_servermgr.exec_command("stoprecord");}
void on_btn_set_broadcast_clicked()
{m_servermgr.exec_command("broadcast " + m_ui->le_broadcast->text().toStdString());}
void on_btn_restart_round_clicked()
{m_servermgr.exec_command("restart " + m_ui->le_restart_time->text().toStdString());}
void on_btn_vote_yes_clicked()
{m_servermgr.exec_command("vote yes");}
void on_btn_vote_no_clicked()
{m_servermgr.exec_command("vote no");}
void on_btn_shutdown_clicked()
{m_servermgr.exec_command("shutdown");}
void on_btn_text_send_clicked()
{m_servermgr.exec_command("say " + m_ui->le_echo_text->text().toStdString());}
void on_btn_custom_cmd_send_clicked()
{m_servermgr.exec_command(m_ui->le_custom_cmd->text().toStdString());}
// tab: players
void on_btn_refresh_playerlist_clicked()
{
m_servermgr.request_player_info();
m_ui->tw_players->clearContents();
m_ui->tw_players->setRowCount(0);
}
void on_btn_ban_ip_clicked()
{
std::string banminutes{m_ui->le_ip_bantime->text().isEmpty() ? "5" : m_ui->le_ip_bantime->text().toStdString()};
m_servermgr.exec_command("ban " + m_ui->le_ip_ban->text().toStdString() + " " + banminutes);
}
void on_btn_unban_ip_clicked()
{m_servermgr.exec_command("unban " + m_ui->le_ip_ban->text().toStdString());}
void on_btn_kick_selected_clicked()
{
for(auto& a : m_ui->tw_players->selectedItems())
{
// only id is interesting
if(a->column() != 0)
continue;
m_servermgr.exec_command("kick " + a->text().toStdString());
}
}
void on_btn_ban_selected_clicked()
{
std::string banminutes{m_ui->le_bantime->text().isEmpty() ? "5" : m_ui->le_bantime->text().toStdString()};
for(auto& a : m_ui->tw_players->selectedItems())
{
// only id is interesting
if(a->column() != 0)
continue;
m_servermgr.exec_command("ban " + a->text().toStdString() + " " + banminutes);
}
}
// tab: jobs
void on_pb_job_add_clicked()
{
auto row(m_ui->tw_jobs->rowCount());
auto time(m_ui->te_job_time->time());
auto time_ms(twec::ms_from_time(time.hour(), time.minute(), time.second()));
m_servermgr.jobmgr().add_job(row, m_ui->le_job_command->text().toStdString(), time_ms, m_ui->cb_job_repeat->isChecked());
QTableWidgetItem* cmd_item = new QTableWidgetItem{m_ui->le_job_command->text()};
QTableWidgetItem* tm_item = new QTableWidgetItem;
QTableWidgetItem* repeat_item = new QTableWidgetItem{m_ui->cb_job_repeat->isChecked() ? "Yes" : "No"};
m_ui->tw_jobs->insertRow(row);
m_ui->tw_jobs->setItem(row, 0, cmd_item);
m_ui->tw_jobs->setItem(row, 1, tm_item);
m_ui->tw_jobs->setItem(row, 2, repeat_item);
auto* h = new twec::id_holder{row};
m_ui->tw_jobs->setCellWidget(row, 0, h);
// reset the ui
m_ui->le_job_command->clear();
m_ui->te_job_time->setTime({0, 0});
m_ui->cb_job_repeat->setChecked(false);
}
void on_pb_remove_job_clicked()
{
auto selected(m_ui->tw_jobs->selectedItems());
for(auto iter(std::begin(selected)); iter != std::end(selected); ++iter)
{
auto obj(*iter);
auto ptr(twec::to_id_holder(m_ui->tw_jobs->cellWidget(obj->row(), obj->column())));
if(ptr == nullptr)
continue;
m_servermgr.jobmgr().remove_job(ptr->get_id());
m_ui->tw_jobs->removeRow(obj->row());
break; // should be single selection
}
}
void _on_log_added(const std::string& str)
{
m_ui->te_log->moveCursor(QTextCursor::End);
m_ui->te_log->insertPlainText(str.c_str());
m_ui->te_log->moveCursor(QTextCursor::End);
}
void _on_connection_timeout()
{
QMessageBox::critical(this, "Error", "Connection attempt timed out");
this->set_window_state("Connection failed");
}
void _on_connection_lost()
{
QMessageBox::critical(this, "Error", "Connection to server lost");
this->set_window_state("Connection lost");
m_ui->tw_main->setTabText(0, "(no server)");
}
void _on_connection_start(const std::string& addr_str)
{
m_ui->tw_main->setTabText(0, addr_str.c_str());
this->set_window_state("Connected");
}
void _on_login()
{
m_ui->tw_main->setTabText(0, m_ui->tw_main->tabText(0) + "(logged)");
this->set_window_state("Logged in");
}
void _on_playerinfo_received(const twec::player_infos& infos)
{
auto table(m_ui->tw_players);
table->clearContents();
table->setRowCount(0);
auto current_row(0);
for(auto& a : infos)
{
table->insertRow(current_row);
// some ugly code...
QTableWidgetItem* id_item = new QTableWidgetItem{a.id.c_str()};
QTableWidgetItem* addr_item = new QTableWidgetItem{a.addr.c_str()};
QTableWidgetItem* name_item = new QTableWidgetItem{a.name.c_str()};
QTableWidgetItem* score_item = new QTableWidgetItem{a.score.c_str()};
table->setItem(current_row, 0, id_item);
table->setItem(current_row, 1, name_item);
table->setItem(current_row, 2, score_item);
table->setItem(current_row, 3, addr_item);
++current_row;
}
}
void _on_job_ended(int id)
{
for(auto row(0); row < m_ui->tw_jobs->rowCount(); ++row)
for(auto col(0); col < m_ui->tw_jobs->rowCount(); ++col)
{
auto ptr(twec::to_id_holder(m_ui->tw_jobs->cellWidget(row, col)));
if(ptr)
if(ptr->get_id() == id)
m_ui->tw_jobs->removeRow(row);
}
}
private:
void set_window_state(const std::string& state)
{m_ui->lb_state->setText(state.c_str());}
};
#endif // MAIN_WINDOW_HPP
<commit_msg>using auto<commit_after>//
// Copyright (c) 2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef MAIN_WINDOW_HPP
#define MAIN_WINDOW_HPP
#include <twec/id_holder.hpp>
#include <twec/player_info.hpp>
#include <twec/server_manager.hpp>
#include <twec/utils.hpp>
#include "ui_main_window.h"
#include <QMainWindow>
#include <QMessageBox>
namespace Ui
{class main_window;}
class main_window : public QMainWindow
{
Q_OBJECT
Ui::main_window* m_ui;
QTimer m_update_timer;
twec::server_manager m_servermgr;
public:
main_window(QWidget* parent = nullptr) :
QMainWindow{parent},
m_ui{new Ui::main_window}
{
m_ui->setupUi(this);
connect(&m_servermgr, SIGNAL(log_added(const std::string&)), this, SLOT(_on_log_added(const std::string&)));
connect(&m_servermgr, SIGNAL(connection_timeout()), this, SLOT(_on_connection_timeout()));
connect(&m_servermgr, SIGNAL(connection_lost()), this, SLOT(_on_connection_lost()));
connect(&m_servermgr, SIGNAL(connection_start(const std::string&)), this, SLOT(_on_connection_start(const std::string&)));
connect(&m_servermgr, SIGNAL(logged_in()), this, SLOT(_on_login()));
connect(&m_servermgr, SIGNAL(playerinfo_received(const twec::player_infos&)), this, SLOT(_on_playerinfo_received(const twec::player_infos&)));
connect(&m_servermgr, SIGNAL(job_ended(int)), this, SLOT(_on_job_ended(int)));
connect(&m_update_timer, SIGNAL(timeout()), this, SLOT(update()));
m_update_timer.start(0);
}
~main_window()
{delete m_ui;}
private slots:
void update()
{
// update server, connection, etc...
m_servermgr.update();
// update some ui stuff
for(auto& a : m_servermgr.jobmgr().get_jobs())
{
// this code rly sucks, qt does not provide itering over cells
// TODO: maybe impl celliterating one day
for(auto row(0); row < m_ui->tw_jobs->rowCount(); ++row)
for(auto col(0); col < m_ui->tw_jobs->rowCount(); ++col)
{
auto ptr(twec::to_id_holder(m_ui->tw_jobs->cellWidget(row, col)));
if(ptr)
if(ptr->get_id() == a.get_id())
m_ui->tw_jobs->item(row, 1)->setText(twec::timestr_from_ms(a.get_countdown()).c_str());
}
}
}
void on_btn_login_clicked()
{
m_servermgr.open_econ({m_ui->le_host->text().toStdString(), m_ui->sb_port->text().toStdString()}, m_ui->le_password->text().toStdString());
this->set_window_state("Trying to connect...");
}
// tab: main controlls
void on_btn_change_map_clicked()
{m_servermgr.exec_command("change_map " + m_ui->le_mapname->text().toStdString());}
void on_btn_reload_map_clicked()
{m_servermgr.exec_command("reload");}
void on_btn_start_recording_clicked()
{m_servermgr.exec_command("record " + m_ui->le_record_filename->text().toStdString());}
void on_btn_stop_recording_clicked()
{m_servermgr.exec_command("stoprecord");}
void on_btn_set_broadcast_clicked()
{m_servermgr.exec_command("broadcast " + m_ui->le_broadcast->text().toStdString());}
void on_btn_restart_round_clicked()
{m_servermgr.exec_command("restart " + m_ui->le_restart_time->text().toStdString());}
void on_btn_vote_yes_clicked()
{m_servermgr.exec_command("vote yes");}
void on_btn_vote_no_clicked()
{m_servermgr.exec_command("vote no");}
void on_btn_shutdown_clicked()
{m_servermgr.exec_command("shutdown");}
void on_btn_text_send_clicked()
{m_servermgr.exec_command("say " + m_ui->le_echo_text->text().toStdString());}
void on_btn_custom_cmd_send_clicked()
{m_servermgr.exec_command(m_ui->le_custom_cmd->text().toStdString());}
// tab: players
void on_btn_refresh_playerlist_clicked()
{
m_servermgr.request_player_info();
m_ui->tw_players->clearContents();
m_ui->tw_players->setRowCount(0);
}
void on_btn_ban_ip_clicked()
{
std::string banminutes{m_ui->le_ip_bantime->text().isEmpty() ? "5" : m_ui->le_ip_bantime->text().toStdString()};
m_servermgr.exec_command("ban " + m_ui->le_ip_ban->text().toStdString() + " " + banminutes);
}
void on_btn_unban_ip_clicked()
{m_servermgr.exec_command("unban " + m_ui->le_ip_ban->text().toStdString());}
void on_btn_kick_selected_clicked()
{
for(auto& a : m_ui->tw_players->selectedItems())
{
// only id is interesting
if(a->column() != 0)
continue;
m_servermgr.exec_command("kick " + a->text().toStdString());
}
}
void on_btn_ban_selected_clicked()
{
std::string banminutes{m_ui->le_bantime->text().isEmpty() ? "5" : m_ui->le_bantime->text().toStdString()};
for(auto& a : m_ui->tw_players->selectedItems())
{
// only id is interesting
if(a->column() != 0)
continue;
m_servermgr.exec_command("ban " + a->text().toStdString() + " " + banminutes);
}
}
// tab: jobs
void on_pb_job_add_clicked()
{
auto row(m_ui->tw_jobs->rowCount());
auto time(m_ui->te_job_time->time());
auto time_ms(twec::ms_from_time(time.hour(), time.minute(), time.second()));
m_servermgr.jobmgr().add_job(row, m_ui->le_job_command->text().toStdString(), time_ms, m_ui->cb_job_repeat->isChecked());
auto* cmd_item = new QTableWidgetItem{m_ui->le_job_command->text()};
auto* tm_item = new QTableWidgetItem;
auto* repeat_item = new QTableWidgetItem{m_ui->cb_job_repeat->isChecked() ? "Yes" : "No"};
m_ui->tw_jobs->insertRow(row);
m_ui->tw_jobs->setItem(row, 0, cmd_item);
m_ui->tw_jobs->setItem(row, 1, tm_item);
m_ui->tw_jobs->setItem(row, 2, repeat_item);
auto* h = new twec::id_holder{row};
m_ui->tw_jobs->setCellWidget(row, 0, h);
// reset the ui
m_ui->le_job_command->clear();
m_ui->te_job_time->setTime({0, 0});
m_ui->cb_job_repeat->setChecked(false);
}
void on_pb_remove_job_clicked()
{
auto selected(m_ui->tw_jobs->selectedItems());
for(auto iter(std::begin(selected)); iter != std::end(selected); ++iter)
{
auto obj(*iter);
auto ptr(twec::to_id_holder(m_ui->tw_jobs->cellWidget(obj->row(), obj->column())));
if(ptr == nullptr)
continue;
m_servermgr.jobmgr().remove_job(ptr->get_id());
m_ui->tw_jobs->removeRow(obj->row());
break; // should be single selection
}
}
void _on_log_added(const std::string& str)
{
m_ui->te_log->moveCursor(QTextCursor::End);
m_ui->te_log->insertPlainText(str.c_str());
m_ui->te_log->moveCursor(QTextCursor::End);
}
void _on_connection_timeout()
{
QMessageBox::critical(this, "Error", "Connection attempt timed out");
this->set_window_state("Connection failed");
}
void _on_connection_lost()
{
QMessageBox::critical(this, "Error", "Connection to server lost");
this->set_window_state("Connection lost");
m_ui->tw_main->setTabText(0, "(no server)");
}
void _on_connection_start(const std::string& addr_str)
{
m_ui->tw_main->setTabText(0, addr_str.c_str());
this->set_window_state("Connected");
}
void _on_login()
{
m_ui->tw_main->setTabText(0, m_ui->tw_main->tabText(0) + "(logged)");
this->set_window_state("Logged in");
}
void _on_playerinfo_received(const twec::player_infos& infos)
{
auto table(m_ui->tw_players);
table->clearContents();
table->setRowCount(0);
auto current_row(0);
for(auto& a : infos)
{
table->insertRow(current_row);
// some ugly code...
auto* id_item = new QTableWidgetItem{a.id.c_str()};
auto* addr_item = new QTableWidgetItem{a.addr.c_str()};
auto* name_item = new QTableWidgetItem{a.name.c_str()};
auto* score_item = new QTableWidgetItem{a.score.c_str()};
table->setItem(current_row, 0, id_item);
table->setItem(current_row, 1, name_item);
table->setItem(current_row, 2, score_item);
table->setItem(current_row, 3, addr_item);
++current_row;
}
}
void _on_job_ended(int id)
{
for(auto row(0); row < m_ui->tw_jobs->rowCount(); ++row)
for(auto col(0); col < m_ui->tw_jobs->rowCount(); ++col)
{
auto ptr(twec::to_id_holder(m_ui->tw_jobs->cellWidget(row, col)));
if(ptr)
if(ptr->get_id() == id)
m_ui->tw_jobs->removeRow(row);
}
}
private:
void set_window_state(const std::string& state)
{m_ui->lb_state->setText(state.c_str());}
};
#endif // MAIN_WINDOW_HPP
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// stl
#include <iostream>
// boost
#include <boost/optional.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
// mapnik
#include <mapnik/color.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/filter_factory.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/load_map.hpp>
using boost::lexical_cast;
using boost::bad_lexical_cast;
using boost::tokenizer;
namespace mapnik
{
void load_map(Map & map, std::string const& filename)
{
using boost::property_tree::ptree;
ptree pt;
read_xml(filename,pt);
boost::optional<std::string> bgcolor =
pt.get_optional<std::string>("Map.<xmlattr>.bgcolor");
if (bgcolor)
{
Color bg = color_factory::from_string(bgcolor->c_str());
map.setBackground(bg);
}
std::string srs = pt.get<std::string>("Map.<xmlattr>.srs",
"+proj=latlong +datum=WGS84");
map.set_srs(srs);
ptree::const_iterator itr = pt.get_child("Map").begin();
ptree::const_iterator end = pt.get_child("Map").end();
for (; itr != end; ++itr)
{
ptree::value_type const& v = *itr;
if (v.first == "Style")
{
std::string name = v.second.get<std::string>("<xmlattr>.name");
feature_type_style style;
ptree::const_iterator ruleIter = v.second.begin();
ptree::const_iterator endRule = v.second.end();
for (; ruleIter!=endRule; ++ruleIter)
{
ptree::value_type const& rule_tag = *ruleIter;
if (rule_tag.first == "Rule")
{
std::string name =
rule_tag.second.get<std::string>("<xmlattr>.name","");
std::string title =
rule_tag.second.get<std::string>("<xmlattr>.title","");
rule_type rule(name,title);
boost::optional<std::string> filter_expr =
rule_tag.second.get_optional<std::string>("Filter");
if (filter_expr)
{
rule.set_filter(create_filter(*filter_expr));
}
boost::optional<std::string> else_filter =
rule_tag.second.get_optional<std::string>("ElseFilter");
if (else_filter)
{
rule.set_else(true);
}
boost::optional<double> min_scale =
rule_tag.second.get_optional<double>("MinScaleDenominator");
if (min_scale)
{
rule.set_min_scale(*min_scale);
}
boost::optional<double> max_scale =
rule_tag.second.get_optional<double>("MaxScaleDenominator");
if (max_scale)
{
rule.set_max_scale(*max_scale);
}
ptree::const_iterator symIter = rule_tag.second.begin();
ptree::const_iterator endSym = rule_tag.second.end();
for( ;symIter != endSym; ++symIter)
{
ptree::value_type const& sym = *symIter;
if ( sym.first == "PointSymbolizer")
{
std::cout << sym.first << "\n";
}
else if ( sym.first == "TextSymbolizer")
{
std::string name =
sym.second.get<std::string>("<xmlattr>.name");
std::string face_name =
sym.second.get<std::string>("<xmlattr>.face_name");
unsigned size =
sym.second.get<unsigned>("<xmlattr>.size",10);
std::string color_str =
sym.second.get<std::string>("<xmlattr>.fill","black");
Color c = color_factory::from_string(color_str.c_str());
text_symbolizer text_symbol(name,face_name, size,c);
std::string placement_str =
sym.second.get<std::string>("<xmlattr>.placement","point");
if (placement_str == "line")
{
text_symbol.set_label_placement(line_placement);
}
rule.append(text_symbol);
}
else if ( sym.first == "LineSymbolizer")
{
stroke strk;
ptree::const_iterator cssIter = sym.second.begin();
ptree::const_iterator endCss = sym.second.end();
for(; cssIter != endCss; ++cssIter)
{
ptree::value_type const& css = * cssIter;
std::string css_name =
css.second.get<std::string>("<xmlattr>.name");
std::string data = css.second.data();
if (css_name == "stroke")
{
Color c = color_factory::from_string(css.second.data().c_str());
strk.set_color(c);
}
else if (css_name == "stroke-width")
{
try
{
float width = lexical_cast<float>(data);
strk.set_width(width);
}
catch (bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
}
}
else if (css_name == "stroke-opacity")
{
try
{
float opacity = lexical_cast<float>(data);
strk.set_opacity(opacity);
}
catch (bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
}
}
else if (css_name == "stroke-linejoin")
{
if ("miter" == data)
{
strk.set_line_join(mapnik::MITER_JOIN);
}
else if ("round" == data)
{
strk.set_line_join(mapnik::ROUND_JOIN);
}
else if ("bevel" == data)
{
strk.set_line_join(mapnik::BEVEL_JOIN);
}
}
else if (css_name == "stroke-linecap")
{
if ("round" == data)
{
strk.set_line_cap(mapnik::ROUND_CAP);
}
else if ("butt" == data)
{
strk.set_line_cap(mapnik::BUTT_CAP);
}
else if ("square" == data)
{
strk.set_line_cap(mapnik::SQUARE_CAP);
}
}
else if (css_name == "stroke-dasharray")
{
tokenizer<> tok (data);
std::vector<float> dash_array;
for (tokenizer<>::iterator itr = tok.begin(); itr != tok.end(); ++itr)
{
try
{
float f = boost::lexical_cast<float>(*itr);
dash_array.push_back(f);
}
catch ( boost::bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
}
}
if (dash_array.size())
{
size_t size = dash_array.size();
if ( size % 2)
{
for (size_t i=0; i < size ;++i)
{
dash_array.push_back(dash_array[i]);
}
}
std::vector<float>::const_iterator pos = dash_array.begin();
while (pos != dash_array.end())
{
strk.add_dash(*pos,*(pos + 1));
pos +=2;
}
}
}
}
rule.append(line_symbolizer(strk));
}
else if ( sym.first == "PolygonSymbolizer")
{
polygon_symbolizer poly_sym;
ptree::const_iterator cssIter = sym.second.begin();
ptree::const_iterator endCss = sym.second.end();
for(; cssIter != endCss; ++cssIter)
{
ptree::value_type const& css = * cssIter;
std::string css_name =
css.second.get<std::string>("<xmlattr>.name");
std::string data = css.second.data();
if (css_name == "fill")
{
Color c = color_factory::from_string(css.second.data().c_str());
poly_sym.set_fill(c);
}
else if (css_name == "fill-opacity")
{
try
{
float opacity = lexical_cast<float>(data);
poly_sym.set_opacity(opacity);
}
catch (bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
}
}
}
rule.append(poly_sym);
}
else if ( sym.first == "TextSymbolizer")
{
std::cout << sym.first << "\n";
}
else if ( sym.first == "RasterSymbolizer")
{
rule.append(raster_symbolizer());
}
}
style.add_rule(rule);
}
}
map.insert_style(name, style);
}
else if (v.first == "Layer")
{
std::string name = v.second.get<std::string>("<xmlattr>.name","Unnamed");
std::string srs = v.second.get<std::string>("<xmlattr>.srs","+proj=latlong +datum=WGS84");
Layer lyr(name, srs);
boost::optional<std::string> status =
v.second.get_optional<std::string>("<xmlattr>.status");
if (status && *status == "off")
{
lyr.setActive(false);
}
ptree::const_iterator itr2 = v.second.begin();
ptree::const_iterator end2 = v.second.end();
for(; itr2 != end2; ++itr2)
{
ptree::value_type const& child = *itr2;
if (child.first == "StyleName")
{
lyr.add_style(child.second.data());
}
else if (child.first == "Datasource")
{
parameters params;
ptree::const_iterator paramIter = child.second.begin();
ptree::const_iterator endParam = child.second.end();
for (; paramIter != endParam; ++paramIter)
{
ptree::value_type const& param_tag=*paramIter;
if (param_tag.first == "Parameter")
{
std::string name = param_tag.second.get<std::string>("<xmlattr>.name");
std::string value = param_tag.second.data();
std::clog << "name = " << name << " value = " << value << "\n";
params[name] = value;
}
}
//now we're ready to create datasource
boost::shared_ptr<datasource> ds = datasource_cache::instance()->create(params);
lyr.set_datasource(ds);
}
}
map.addLayer(lyr);
}
}
}
}
<commit_msg>support for ShieldSymbolizer and LinePatternSymbolizer tags<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// stl
#include <iostream>
// boost
#include <boost/optional.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include <boost/property_tree/ptree.hpp>
// use tinyxml
#define BOOST_PROPERTY_TREE_XML_PARSER_TINYXML
#include <boost/property_tree/xml_parser.hpp>
// mapnik
#include <mapnik/color.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/filter_factory.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/load_map.hpp>
using boost::lexical_cast;
using boost::bad_lexical_cast;
using boost::tokenizer;
namespace mapnik
{
void load_map(Map & map, std::string const& filename)
{
using boost::property_tree::ptree;
ptree pt;
read_xml(filename,pt);
boost::optional<std::string> bgcolor =
pt.get_optional<std::string>("Map.<xmlattr>.bgcolor");
if (bgcolor)
{
Color bg = color_factory::from_string(bgcolor->c_str());
map.setBackground(bg);
}
std::string srs = pt.get<std::string>("Map.<xmlattr>.srs",
"+proj=latlong +datum=WGS84");
map.set_srs(srs);
ptree::const_iterator itr = pt.get_child("Map").begin();
ptree::const_iterator end = pt.get_child("Map").end();
for (; itr != end; ++itr)
{
ptree::value_type const& v = *itr;
if (v.first == "Style")
{
std::string name = v.second.get<std::string>("<xmlattr>.name");
feature_type_style style;
ptree::const_iterator ruleIter = v.second.begin();
ptree::const_iterator endRule = v.second.end();
for (; ruleIter!=endRule; ++ruleIter)
{
ptree::value_type const& rule_tag = *ruleIter;
if (rule_tag.first == "Rule")
{
std::string name =
rule_tag.second.get<std::string>("<xmlattr>.name","");
std::string title =
rule_tag.second.get<std::string>("<xmlattr>.title","");
rule_type rule(name,title);
boost::optional<std::string> filter_expr =
rule_tag.second.get_optional<std::string>("Filter");
if (filter_expr)
{
rule.set_filter(create_filter(*filter_expr));
}
boost::optional<std::string> else_filter =
rule_tag.second.get_optional<std::string>("ElseFilter");
if (else_filter)
{
rule.set_else(true);
}
boost::optional<double> min_scale =
rule_tag.second.get_optional<double>("MinScaleDenominator");
if (min_scale)
{
rule.set_min_scale(*min_scale);
}
boost::optional<double> max_scale =
rule_tag.second.get_optional<double>("MaxScaleDenominator");
if (max_scale)
{
rule.set_max_scale(*max_scale);
}
ptree::const_iterator symIter = rule_tag.second.begin();
ptree::const_iterator endSym = rule_tag.second.end();
for( ;symIter != endSym; ++symIter)
{
ptree::value_type const& sym = *symIter;
if ( sym.first == "PointSymbolizer")
{
std::cout << sym.first << "\n";
}
else if ( sym.first == "LinePatternSymbolizer")
{
std::string file =
sym.second.get<std::string>("<xmlattr>.file");
std::string type =
sym.second.get<std::string>("<xmlattr>.type");
unsigned width =
sym.second.get<unsigned>("<xmlattr>.width");
unsigned height =
sym.second.get<unsigned>("<xmlattr>.height");
rule.append(line_pattern_symbolizer(file,type,width,height));
}
else if ( sym.first == "TextSymbolizer")
{
std::string name =
sym.second.get<std::string>("<xmlattr>.name");
std::string face_name =
sym.second.get<std::string>("<xmlattr>.face_name");
unsigned size =
sym.second.get<unsigned>("<xmlattr>.size",10);
std::string color_str =
sym.second.get<std::string>("<xmlattr>.fill","black");
Color c = color_factory::from_string(color_str.c_str());
text_symbolizer text_symbol(name,face_name, size,c);
std::string placement_str =
sym.second.get<std::string>("<xmlattr>.placement","point");
if (placement_str == "line")
{
text_symbol.set_label_placement(line_placement);
}
rule.append(text_symbol);
}
else if ( sym.first == "ShieldSymbolizer")
{
std::string name =
sym.second.get<std::string>("<xmlattr>.name");
std::string face_name =
sym.second.get<std::string>("<xmlattr>.face_name");
unsigned size =
sym.second.get<unsigned>("<xmlattr>.size",10);
std::string color_str =
sym.second.get<std::string>("<xmlattr>.fill","black");
Color fill = color_factory::from_string(color_str.c_str());
std::string image_file =
sym.second.get<std::string>("<xmlattr>.file");
std::string type =
sym.second.get<std::string>("<xmlattr>.type");
unsigned width =
sym.second.get<unsigned>("<xmlattr>.width");
unsigned height =
sym.second.get<unsigned>("<xmlattr>.height");
shield_symbolizer shield_symbol(name,face_name,size,fill,
image_file,type,width,height);
rule.append(shield_symbol);
}
else if ( sym.first == "LineSymbolizer")
{
stroke strk;
ptree::const_iterator cssIter = sym.second.begin();
ptree::const_iterator endCss = sym.second.end();
for(; cssIter != endCss; ++cssIter)
{
ptree::value_type const& css = * cssIter;
std::string css_name =
css.second.get<std::string>("<xmlattr>.name");
std::string data = css.second.data();
if (css_name == "stroke")
{
Color c = color_factory::from_string(css.second.data().c_str());
strk.set_color(c);
}
else if (css_name == "stroke-width")
{
try
{
float width = lexical_cast<float>(data);
strk.set_width(width);
}
catch (bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
}
}
else if (css_name == "stroke-opacity")
{
try
{
float opacity = lexical_cast<float>(data);
strk.set_opacity(opacity);
}
catch (bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
}
}
else if (css_name == "stroke-linejoin")
{
if ("miter" == data)
{
strk.set_line_join(mapnik::MITER_JOIN);
}
else if ("round" == data)
{
strk.set_line_join(mapnik::ROUND_JOIN);
}
else if ("bevel" == data)
{
strk.set_line_join(mapnik::BEVEL_JOIN);
}
}
else if (css_name == "stroke-linecap")
{
if ("round" == data)
{
strk.set_line_cap(mapnik::ROUND_CAP);
}
else if ("butt" == data)
{
strk.set_line_cap(mapnik::BUTT_CAP);
}
else if ("square" == data)
{
strk.set_line_cap(mapnik::SQUARE_CAP);
}
}
else if (css_name == "stroke-dasharray")
{
tokenizer<> tok (data);
std::vector<float> dash_array;
for (tokenizer<>::iterator itr = tok.begin(); itr != tok.end(); ++itr)
{
try
{
float f = boost::lexical_cast<float>(*itr);
dash_array.push_back(f);
}
catch ( boost::bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
}
}
if (dash_array.size())
{
size_t size = dash_array.size();
if ( size % 2)
{
for (size_t i=0; i < size ;++i)
{
dash_array.push_back(dash_array[i]);
}
}
std::vector<float>::const_iterator pos = dash_array.begin();
while (pos != dash_array.end())
{
strk.add_dash(*pos,*(pos + 1));
pos +=2;
}
}
}
}
rule.append(line_symbolizer(strk));
}
else if ( sym.first == "PolygonSymbolizer")
{
polygon_symbolizer poly_sym;
ptree::const_iterator cssIter = sym.second.begin();
ptree::const_iterator endCss = sym.second.end();
for(; cssIter != endCss; ++cssIter)
{
ptree::value_type const& css = * cssIter;
std::string css_name =
css.second.get<std::string>("<xmlattr>.name");
std::string data = css.second.data();
if (css_name == "fill")
{
Color c = color_factory::from_string(css.second.data().c_str());
poly_sym.set_fill(c);
}
else if (css_name == "fill-opacity")
{
try
{
float opacity = lexical_cast<float>(data);
poly_sym.set_opacity(opacity);
}
catch (bad_lexical_cast & ex)
{
std::clog << ex.what() << "\n";
}
}
}
rule.append(poly_sym);
}
else if ( sym.first == "TextSymbolizer")
{
std::cout << sym.first << "\n";
}
else if ( sym.first == "RasterSymbolizer")
{
rule.append(raster_symbolizer());
}
}
style.add_rule(rule);
}
}
map.insert_style(name, style);
}
else if (v.first == "Layer")
{
std::string name = v.second.get<std::string>("<xmlattr>.name","Unnamed");
std::string srs = v.second.get<std::string>("<xmlattr>.srs","+proj=latlong +datum=WGS84");
Layer lyr(name, srs);
boost::optional<std::string> status =
v.second.get_optional<std::string>("<xmlattr>.status");
if (status && *status == "off")
{
lyr.setActive(false);
}
ptree::const_iterator itr2 = v.second.begin();
ptree::const_iterator end2 = v.second.end();
for(; itr2 != end2; ++itr2)
{
ptree::value_type const& child = *itr2;
if (child.first == "StyleName")
{
lyr.add_style(child.second.data());
}
else if (child.first == "Datasource")
{
parameters params;
ptree::const_iterator paramIter = child.second.begin();
ptree::const_iterator endParam = child.second.end();
for (; paramIter != endParam; ++paramIter)
{
ptree::value_type const& param_tag=*paramIter;
if (param_tag.first == "Parameter")
{
std::string name = param_tag.second.get<std::string>("<xmlattr>.name");
std::string value = param_tag.second.data();
std::clog << "name = " << name << " value = " << value << "\n";
params[name] = value;
}
}
//now we're ready to create datasource
boost::shared_ptr<datasource> ds = datasource_cache::instance()->create(params);
lyr.set_datasource(ds);
}
}
map.addLayer(lyr);
}
}
}
}
<|endoftext|>
|
<commit_before>#include <dsnutil/log/init.h>
#include <dsnutil/log/sinkmanager.h>
#include <dsnutil/null_deleter.h>
#include <boost/log/utility/setup/formatter_parser.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/trivial.hpp>
/** \brief Initialize default logging environment
*
* Sets up some basic default parameters for the boost::log based logging environment and registers
* a formatter for boost::log::trivial::severity_level values.
*/
void dsn::log::init(const std::string& filename)
{
boost::log::register_simple_formatter_factory<boost::log::trivial::severity_level, char>("Severity");
boost::log::add_common_attributes();
static const std::string format{ "%TimeStamp% %Severity% (P:%ProcessID%,T:%ThreadID%) (%Class%@%This%): %Message%" };
dsn::log::SinkManager& manager = dsn::log::SinkManager::getInstance();
// create backend for std::clog sink
boost::shared_ptr<boost::log::sinks::text_ostream_backend> backend = boost::make_shared<boost::log::sinks::text_ostream_backend>();
backend->add_stream(boost::shared_ptr<std::ostream>(&std::clog, dsn::null_deleter()));
backend->auto_flush(true);
// create the actual sink
typedef boost::log::sinks::synchronous_sink<boost::log::sinks::text_ostream_backend> sink_t;
boost::shared_ptr<sink_t> sink(new sink_t(backend));
sink->set_formatter(boost::log::parse_formatter(format));
// register sink with manager
manager.add("std::clog", sink);
BOOST_LOG_TRIVIAL(trace) << "Initialized default console log settings";
if (filename.length() > 0) {
// setup default logfile with given name/pattern, rotation at 1GB size or daily at 00:00:00
boost::log::add_file_log(boost::log::keywords::file_name = filename,
boost::log::keywords::format = format,
boost::log::keywords::time_based_rotation = boost::log::sinks::file::rotation_at_time_point(0, 0, 0),
boost::log::keywords::rotation_size = 1024 * 1024 * 1024);
BOOST_LOG_TRIVIAL(trace) << "Initialized default settings for file: " << filename;
}
}
<commit_msg>Clean up dsn::log::init()<commit_after>#include <dsnutil/log/init.h>
#include <dsnutil/log/sinkmanager.h>
#include <dsnutil/null_deleter.h>
#include <boost/log/utility/setup/formatter_parser.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/trivial.hpp>
/** \brief Initialize default logging environment
*
* Sets up some basic default parameters for the boost::log based logging environment and registers
* a formatter for boost::log::trivial::severity_level values.
*/
void dsn::log::init(const std::string& filename)
{
boost::log::register_simple_formatter_factory<boost::log::trivial::severity_level, char>("Severity");
boost::log::add_common_attributes();
static const std::string format{ "%TimeStamp% %Severity% (P:%ProcessID%,T:%ThreadID%) (%Class%@%This%): %Message%" };
dsn::log::SinkManager& manager = dsn::log::SinkManager::getInstance();
// create backend and sink for std::clog
typedef boost::log::sinks::text_ostream_backend backend_t;
boost::shared_ptr<backend_t> backend = boost::make_shared<backend_t>();
backend->add_stream(boost::shared_ptr<std::ostream>(&std::clog, dsn::null_deleter()));
backend->auto_flush(true);
typedef boost::log::sinks::synchronous_sink<backend_t> sink_t;
boost::shared_ptr<sink_t> sink(new sink_t(backend));
sink->set_formatter(boost::log::parse_formatter(format));
manager.add("std::clog", sink);
BOOST_LOG_TRIVIAL(trace) << "Initialized default console log settings (std::clog)";
if (filename.length() > 0) {
// setup backend and sink for the given logfile name, default rotation parameters are:
//
// - daily at 00:00:00
// - at 1GB size
typedef boost::log::sinks::text_file_backend backend_t;
boost::shared_ptr<backend_t> fileBackend = boost::make_shared<backend_t>(boost::log::keywords::file_name = filename,
boost::log::keywords::rotation_size = 1024 * 1024 * 1024,
boost::log::keywords::time_based_rotation = boost::log::sinks::file::rotation_at_time_point(0, 0, 0),
boost::log::keywords::format = format);
typedef boost::log::sinks::synchronous_sink<backend_t> sink_t;
boost::shared_ptr<sink_t> sink(new sink_t(fileBackend));
manager.add("file://" + filename, sink);
BOOST_LOG_TRIVIAL(trace) << "Initialized default settings for file: " << filename;
}
}
<|endoftext|>
|
<commit_before>/*
* Handler for HTTP requests.
*
* author: Max Kellermann <[email protected]>
*/
#include "lb_http.hxx"
#include "lb_instance.hxx"
#include "lb_connection.hxx"
#include "lb_config.hxx"
#include "lb_session.hxx"
#include "lb_cookie.hxx"
#include "lb_jvm_route.hxx"
#include "lb_headers.hxx"
#include "ssl_filter.hxx"
#include "address_envelope.h"
#include "address_sticky.h"
#include "http-server.h"
#include "http-client.h"
#include "tcp-stock.h"
#include "tcp-balancer.h"
#include "lease.h"
#include "header-writer.h"
#include "http-response.h"
#include "stock.h"
#include "clock.h"
#include "access-log.h"
#include "strmap.h"
#include "failure.h"
#include "bulldog.h"
#include "abort-close.h"
#include <http/status.h>
#include <daemon/log.h>
struct lb_request {
struct lb_connection *connection;
struct tcp_balancer *balancer;
struct http_server_request *request;
/**
* The request body (wrapperd with istream_hold).
*/
struct istream *body;
struct async_operation_ref *async_ref;
struct stock_item *stock_item;
const struct address_envelope *current_address;
unsigned new_cookie;
};
static void
log_error(int level, const struct lb_connection *connection,
const char *prefix, GError *error)
{
daemon_log(level, "%s (listener='%s' cluster='%s'): %s\n",
prefix,
connection->listener->name.c_str(),
connection->listener->cluster->name.c_str(),
error->message);
}
static bool
send_fallback(struct http_server_request *request,
const struct lb_fallback_config *fallback)
{
if (!fallback->location.empty()) {
http_server_send_redirect(request, HTTP_STATUS_FOUND,
fallback->location.c_str(), "Found");
return true;
} else if (!fallback->message.empty()) {
/* custom status + error message */
assert(http_status_is_valid(fallback->status));
http_server_send_message(request, fallback->status,
fallback->message.c_str());
return true;
} else
return false;
}
/**
* Generate a cookie for sticky worker selection. Return only worker
* numbers that are not known to be failing. Returns 0 on total
* failure.
*/
static unsigned
generate_cookie(const struct address_list *list)
{
assert(list->size >= 2);
const unsigned first = lb_cookie_generate(list->size);
unsigned i = first;
do {
assert(i >= 1 && i <= list->size);
const struct address_envelope *envelope =
list->addresses[i % list->size];
if (!failure_check(&envelope->address, envelope->length) &&
bulldog_check(&envelope->address, envelope->length) &&
!bulldog_is_fading(&envelope->address, envelope->length))
return i;
i = lb_cookie_next(list->size, i);
} while (i != first);
/* all nodes have failed */
return first;
}
/**
* Is the specified error a server failure, that justifies
* blacklisting the server for a while?
*/
static bool
is_server_failure(GError *error)
{
return error->domain == http_client_quark() &&
error->code != HTTP_CLIENT_UNSPECIFIED;
}
/*
* socket lease
*
*/
static void
my_socket_release(bool reuse, void *ctx)
{
struct lb_request *request2 = (struct lb_request *)ctx;
tcp_balancer_put(request2->balancer,
request2->stock_item, !reuse);
}
static const struct lease my_socket_lease = {
.release = my_socket_release,
};
/*
* HTTP response handler
*
*/
static void
my_response_response(http_status_t status, struct strmap *headers,
struct istream *body, void *ctx)
{
struct lb_request *request2 = (struct lb_request *)ctx;
struct http_server_request *request = request2->request;
struct growing_buffer *headers2 = headers_dup(request->pool, headers);
if (request2->request->method == HTTP_METHOD_HEAD)
/* pass Content-Length, even though there is no response body
(RFC 2616 14.13) */
headers_copy_one(headers, headers2, "content-length");
if (request2->new_cookie != 0) {
char buffer[64];
/* "Discard" must be last, to work around an Android bug*/
snprintf(buffer, sizeof(buffer),
"beng_lb_node=0-%x; HttpOnly; Path=/; Version=1; Discard",
request2->new_cookie);
header_write(headers2, "cookie2", "$Version=\"1\"");
header_write(headers2, "set-cookie", buffer);
}
http_server_response(request2->request, status, headers2, body);
}
static void
my_response_abort(GError *error, void *ctx)
{
struct lb_request *request2 = (struct lb_request *)ctx;
const struct lb_connection *connection = request2->connection;
if (is_server_failure(error))
failure_add(&request2->current_address->address,
request2->current_address->length);
log_error(2, connection, "Error", error);
g_error_free(error);
if (!send_fallback(request2->request,
&connection->listener->cluster->fallback))
http_server_send_message(request2->request, HTTP_STATUS_BAD_GATEWAY,
"Server failure");
}
static const struct http_response_handler my_response_handler = {
.response = my_response_response,
.abort = my_response_abort,
};
/*
* stock callback
*
*/
static void
my_stock_ready(struct stock_item *item, void *ctx)
{
struct lb_request *request2 = (struct lb_request *)ctx;
struct http_server_request *request = request2->request;
request2->stock_item = item;
request2->current_address = tcp_balancer_get_last();
const char *peer_subject = request2->connection->ssl_filter != NULL
? ssl_filter_get_peer_subject(request2->connection->ssl_filter)
: NULL;
const char *peer_issuer_subject = request2->connection->ssl_filter != NULL
? ssl_filter_get_peer_issuer_subject(request2->connection->ssl_filter)
: NULL;
struct strmap *headers =
lb_forward_request_headers(request->pool, request->headers,
request->local_host_and_port,
request->remote_host,
peer_subject, peer_issuer_subject,
request2->connection->listener->cluster->mangle_via);
struct growing_buffer *headers2 = headers_dup(request->pool, headers);
http_client_request(request->pool,
tcp_stock_item_get(item),
tcp_stock_item_get_domain(item) == AF_LOCAL
? ISTREAM_SOCKET : ISTREAM_TCP,
&my_socket_lease, request2,
request->method, request->uri,
headers2, request2->body, true,
&my_response_handler, request2,
request2->async_ref);
}
static void
my_stock_error(GError *error, void *ctx)
{
struct lb_request *request2 = (struct lb_request *)ctx;
const struct lb_connection *connection = request2->connection;
log_error(2, connection, "Connect error", error);
g_error_free(error);
if (request2->body != NULL)
istream_close_unused(request2->body);
if (!send_fallback(request2->request,
&connection->listener->cluster->fallback))
http_server_send_message(request2->request, HTTP_STATUS_BAD_GATEWAY,
"Connection failure");
}
static const struct stock_get_handler my_stock_handler = {
.ready = my_stock_ready,
.error = my_stock_error,
};
/*
* http connection handler
*
*/
static void
lb_http_connection_request(struct http_server_request *request,
void *ctx,
struct async_operation_ref *async_ref)
{
struct lb_connection *connection = (struct lb_connection *)ctx;
++connection->instance->http_request_counter;
connection->request_start_time = now_us();
const struct lb_cluster_config *cluster = connection->listener->cluster;
assert(cluster != NULL);
assert(!cluster->members.empty());
struct lb_request *request2 =
(struct lb_request *)p_malloc(request->pool, sizeof(*request2));
request2->connection = connection;
request2->balancer = connection->instance->tcp_balancer;
request2->request = request;
request2->body = request->body != NULL
? istream_hold_new(request->pool, request->body)
: NULL;
request2->async_ref = async_ref;
request2->new_cookie = 0;
unsigned session_sticky = 0;
switch (cluster->address_list.sticky_mode) {
case STICKY_NONE:
case STICKY_FAILOVER:
break;
case STICKY_SOURCE_IP:
session_sticky = socket_address_sticky(request->remote_address);
break;
case STICKY_SESSION_MODULO:
session_sticky = lb_session_get(request->headers,
connection->listener->cluster->session_cookie.c_str());
break;
case STICKY_COOKIE:
session_sticky = lb_cookie_get(request->headers);
if (session_sticky == 0)
request2->new_cookie = session_sticky =
generate_cookie(&cluster->address_list);
break;
case STICKY_JVM_ROUTE:
session_sticky = lb_jvm_route_get(request->headers, cluster);
break;
}
tcp_balancer_get(request2->balancer, request->pool,
session_sticky,
&cluster->address_list,
20,
&my_stock_handler, request2,
async_optional_close_on_abort(request->pool,
request2->body,
async_ref));
}
static void
lb_http_connection_log(struct http_server_request *request,
http_status_t status, off_t length,
uint64_t bytes_received, uint64_t bytes_sent,
void *ctx)
{
struct lb_connection *connection = (struct lb_connection *)ctx;
access_log(request, NULL,
strmap_get_checked(request->headers, "referer"),
strmap_get_checked(request->headers, "user-agent"),
status, length,
bytes_received, bytes_sent,
now_us() - connection->request_start_time);
}
static void
lb_http_connection_error(GError *error, void *ctx)
{
struct lb_connection *connection = (struct lb_connection *)ctx;
log_error(2, connection, "Error", error);
g_error_free(error);
assert(connection->http != NULL);
connection->http = NULL;
lb_connection_remove(connection);
}
static void
lb_http_connection_free(void *ctx)
{
struct lb_connection *connection = (struct lb_connection *)ctx;
assert(connection->http != NULL);
connection->http = NULL;
lb_connection_remove(connection);
}
const struct http_server_connection_handler lb_http_connection_handler = {
lb_http_connection_request,
lb_http_connection_log,
lb_http_connection_error,
lb_http_connection_free,
};
<commit_msg>lb_http: use lb_connection_log_gerror()<commit_after>/*
* Handler for HTTP requests.
*
* author: Max Kellermann <[email protected]>
*/
#include "lb_http.hxx"
#include "lb_instance.hxx"
#include "lb_connection.hxx"
#include "lb_config.hxx"
#include "lb_session.hxx"
#include "lb_cookie.hxx"
#include "lb_jvm_route.hxx"
#include "lb_headers.hxx"
#include "lb_log.hxx"
#include "ssl_filter.hxx"
#include "address_envelope.h"
#include "address_sticky.h"
#include "http-server.h"
#include "http-client.h"
#include "tcp-stock.h"
#include "tcp-balancer.h"
#include "lease.h"
#include "header-writer.h"
#include "http-response.h"
#include "stock.h"
#include "clock.h"
#include "access-log.h"
#include "strmap.h"
#include "failure.h"
#include "bulldog.h"
#include "abort-close.h"
#include <http/status.h>
#include <daemon/log.h>
struct lb_request {
struct lb_connection *connection;
struct tcp_balancer *balancer;
struct http_server_request *request;
/**
* The request body (wrapperd with istream_hold).
*/
struct istream *body;
struct async_operation_ref *async_ref;
struct stock_item *stock_item;
const struct address_envelope *current_address;
unsigned new_cookie;
};
static bool
send_fallback(struct http_server_request *request,
const struct lb_fallback_config *fallback)
{
if (!fallback->location.empty()) {
http_server_send_redirect(request, HTTP_STATUS_FOUND,
fallback->location.c_str(), "Found");
return true;
} else if (!fallback->message.empty()) {
/* custom status + error message */
assert(http_status_is_valid(fallback->status));
http_server_send_message(request, fallback->status,
fallback->message.c_str());
return true;
} else
return false;
}
/**
* Generate a cookie for sticky worker selection. Return only worker
* numbers that are not known to be failing. Returns 0 on total
* failure.
*/
static unsigned
generate_cookie(const struct address_list *list)
{
assert(list->size >= 2);
const unsigned first = lb_cookie_generate(list->size);
unsigned i = first;
do {
assert(i >= 1 && i <= list->size);
const struct address_envelope *envelope =
list->addresses[i % list->size];
if (!failure_check(&envelope->address, envelope->length) &&
bulldog_check(&envelope->address, envelope->length) &&
!bulldog_is_fading(&envelope->address, envelope->length))
return i;
i = lb_cookie_next(list->size, i);
} while (i != first);
/* all nodes have failed */
return first;
}
/**
* Is the specified error a server failure, that justifies
* blacklisting the server for a while?
*/
static bool
is_server_failure(GError *error)
{
return error->domain == http_client_quark() &&
error->code != HTTP_CLIENT_UNSPECIFIED;
}
/*
* socket lease
*
*/
static void
my_socket_release(bool reuse, void *ctx)
{
struct lb_request *request2 = (struct lb_request *)ctx;
tcp_balancer_put(request2->balancer,
request2->stock_item, !reuse);
}
static const struct lease my_socket_lease = {
.release = my_socket_release,
};
/*
* HTTP response handler
*
*/
static void
my_response_response(http_status_t status, struct strmap *headers,
struct istream *body, void *ctx)
{
struct lb_request *request2 = (struct lb_request *)ctx;
struct http_server_request *request = request2->request;
struct growing_buffer *headers2 = headers_dup(request->pool, headers);
if (request2->request->method == HTTP_METHOD_HEAD)
/* pass Content-Length, even though there is no response body
(RFC 2616 14.13) */
headers_copy_one(headers, headers2, "content-length");
if (request2->new_cookie != 0) {
char buffer[64];
/* "Discard" must be last, to work around an Android bug*/
snprintf(buffer, sizeof(buffer),
"beng_lb_node=0-%x; HttpOnly; Path=/; Version=1; Discard",
request2->new_cookie);
header_write(headers2, "cookie2", "$Version=\"1\"");
header_write(headers2, "set-cookie", buffer);
}
http_server_response(request2->request, status, headers2, body);
}
static void
my_response_abort(GError *error, void *ctx)
{
struct lb_request *request2 = (struct lb_request *)ctx;
const struct lb_connection *connection = request2->connection;
if (is_server_failure(error))
failure_add(&request2->current_address->address,
request2->current_address->length);
lb_connection_log_gerror(2, connection, "Error", error);
g_error_free(error);
if (!send_fallback(request2->request,
&connection->listener->cluster->fallback))
http_server_send_message(request2->request, HTTP_STATUS_BAD_GATEWAY,
"Server failure");
}
static const struct http_response_handler my_response_handler = {
.response = my_response_response,
.abort = my_response_abort,
};
/*
* stock callback
*
*/
static void
my_stock_ready(struct stock_item *item, void *ctx)
{
struct lb_request *request2 = (struct lb_request *)ctx;
struct http_server_request *request = request2->request;
request2->stock_item = item;
request2->current_address = tcp_balancer_get_last();
const char *peer_subject = request2->connection->ssl_filter != NULL
? ssl_filter_get_peer_subject(request2->connection->ssl_filter)
: NULL;
const char *peer_issuer_subject = request2->connection->ssl_filter != NULL
? ssl_filter_get_peer_issuer_subject(request2->connection->ssl_filter)
: NULL;
struct strmap *headers =
lb_forward_request_headers(request->pool, request->headers,
request->local_host_and_port,
request->remote_host,
peer_subject, peer_issuer_subject,
request2->connection->listener->cluster->mangle_via);
struct growing_buffer *headers2 = headers_dup(request->pool, headers);
http_client_request(request->pool,
tcp_stock_item_get(item),
tcp_stock_item_get_domain(item) == AF_LOCAL
? ISTREAM_SOCKET : ISTREAM_TCP,
&my_socket_lease, request2,
request->method, request->uri,
headers2, request2->body, true,
&my_response_handler, request2,
request2->async_ref);
}
static void
my_stock_error(GError *error, void *ctx)
{
struct lb_request *request2 = (struct lb_request *)ctx;
const struct lb_connection *connection = request2->connection;
lb_connection_log_gerror(2, connection, "Connect error", error);
g_error_free(error);
if (request2->body != NULL)
istream_close_unused(request2->body);
if (!send_fallback(request2->request,
&connection->listener->cluster->fallback))
http_server_send_message(request2->request, HTTP_STATUS_BAD_GATEWAY,
"Connection failure");
}
static const struct stock_get_handler my_stock_handler = {
.ready = my_stock_ready,
.error = my_stock_error,
};
/*
* http connection handler
*
*/
static void
lb_http_connection_request(struct http_server_request *request,
void *ctx,
struct async_operation_ref *async_ref)
{
struct lb_connection *connection = (struct lb_connection *)ctx;
++connection->instance->http_request_counter;
connection->request_start_time = now_us();
const struct lb_cluster_config *cluster = connection->listener->cluster;
assert(cluster != NULL);
assert(!cluster->members.empty());
struct lb_request *request2 =
(struct lb_request *)p_malloc(request->pool, sizeof(*request2));
request2->connection = connection;
request2->balancer = connection->instance->tcp_balancer;
request2->request = request;
request2->body = request->body != NULL
? istream_hold_new(request->pool, request->body)
: NULL;
request2->async_ref = async_ref;
request2->new_cookie = 0;
unsigned session_sticky = 0;
switch (cluster->address_list.sticky_mode) {
case STICKY_NONE:
case STICKY_FAILOVER:
break;
case STICKY_SOURCE_IP:
session_sticky = socket_address_sticky(request->remote_address);
break;
case STICKY_SESSION_MODULO:
session_sticky = lb_session_get(request->headers,
connection->listener->cluster->session_cookie.c_str());
break;
case STICKY_COOKIE:
session_sticky = lb_cookie_get(request->headers);
if (session_sticky == 0)
request2->new_cookie = session_sticky =
generate_cookie(&cluster->address_list);
break;
case STICKY_JVM_ROUTE:
session_sticky = lb_jvm_route_get(request->headers, cluster);
break;
}
tcp_balancer_get(request2->balancer, request->pool,
session_sticky,
&cluster->address_list,
20,
&my_stock_handler, request2,
async_optional_close_on_abort(request->pool,
request2->body,
async_ref));
}
static void
lb_http_connection_log(struct http_server_request *request,
http_status_t status, off_t length,
uint64_t bytes_received, uint64_t bytes_sent,
void *ctx)
{
struct lb_connection *connection = (struct lb_connection *)ctx;
access_log(request, NULL,
strmap_get_checked(request->headers, "referer"),
strmap_get_checked(request->headers, "user-agent"),
status, length,
bytes_received, bytes_sent,
now_us() - connection->request_start_time);
}
static void
lb_http_connection_error(GError *error, void *ctx)
{
struct lb_connection *connection = (struct lb_connection *)ctx;
lb_connection_log_gerror(2, connection, "Error", error);
g_error_free(error);
assert(connection->http != NULL);
connection->http = NULL;
lb_connection_remove(connection);
}
static void
lb_http_connection_free(void *ctx)
{
struct lb_connection *connection = (struct lb_connection *)ctx;
assert(connection->http != NULL);
connection->http = NULL;
lb_connection_remove(connection);
}
const struct http_server_connection_handler lb_http_connection_handler = {
lb_http_connection_request,
lb_http_connection_log,
lb_http_connection_error,
lb_http_connection_free,
};
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWorldPointPicker.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 "vtkWorldPointPicker.h"
#include "vtkCamera.h"
#include "vtkCommand.h"
#include "vtkObjectFactory.h"
#include "vtkRenderer.h"
vtkCxxRevisionMacro(vtkWorldPointPicker, "1.17");
vtkStandardNewMacro(vtkWorldPointPicker);
vtkWorldPointPicker::vtkWorldPointPicker()
{
}
// Perform pick operation with selection point provided. The z location
// is recovered from the zBuffer. Always returns 0 since no actors are picked.
int vtkWorldPointPicker::Pick(float selectionX, float selectionY,
float selectionZ, vtkRenderer *renderer)
{
vtkCamera *camera;
float cameraFP[4];
float display[3], *world;
float *displayCoord;
float z;
// Initialize the picking process
this->Initialize();
this->Renderer = renderer;
this->SelectionPoint[0] = selectionX;
this->SelectionPoint[1] = selectionY;
this->SelectionPoint[2] = selectionZ;
// Invoke start pick method if defined
this->InvokeEvent(vtkCommand::StartPickEvent,NULL);
z = renderer->GetZ ((int) selectionX, (int) selectionY);
// if z is 1.0, we assume the user has picked a point on the
// screen that has not been rendered into. Use the camera's focal
// point for the z value. The test value .999999 has to be used
// instead of 1.0 because for some reason our SGI Infinite Reality
// engine won't return a 1.0 from the zbuffer
if (z < 0.999999)
{
selectionZ = z;
vtkDebugMacro(<< " z from zBuffer: " << selectionZ);
}
else
{
// Get camera focal point and position. Convert to display (screen)
// coordinates. We need a depth value for z-buffer.
camera = renderer->GetActiveCamera();
camera->GetFocalPoint((float *)cameraFP); cameraFP[3] = 1.0;
renderer->SetWorldPoint(cameraFP);
renderer->WorldToDisplay();
displayCoord = renderer->GetDisplayPoint();
selectionZ = displayCoord[2];
vtkDebugMacro(<< "computed z from focal point: " << selectionZ);
}
// now convert the display point to world coordinates
display[0] = selectionX;
display[1] = selectionY;
display[2] = selectionZ;
renderer->SetDisplayPoint (display);
renderer->DisplayToWorld ();
world = renderer->GetWorldPoint ();
for (int i=0; i < 3; i++)
{
this->PickPosition[i] = world[i] / world[3];
}
// Invoke end pick method if defined
this->InvokeEvent(vtkCommand::EndPickEvent,NULL);
return 0;
}
void vtkWorldPointPicker::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
<commit_msg>ENH - Since renderers are rendered backwards from numlayers->0, the z-buffer data is wiped out for all but the last rendered layer (0). For multiple-layer renderwindows, we need to perform a pick render before accessing z-buffer info, or else we will get renderer[0]'s z-buffer info.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWorldPointPicker.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 "vtkWorldPointPicker.h"
#include "vtkCamera.h"
#include "vtkCommand.h"
#include "vtkObjectFactory.h"
#include "vtkRenderer.h"
vtkCxxRevisionMacro(vtkWorldPointPicker, "1.18");
vtkStandardNewMacro(vtkWorldPointPicker);
vtkWorldPointPicker::vtkWorldPointPicker()
{
}
// Perform pick operation with selection point provided. The z location
// is recovered from the zBuffer. Always returns 0 since no actors are picked.
int vtkWorldPointPicker::Pick(float selectionX, float selectionY,
float selectionZ, vtkRenderer *renderer)
{
vtkCamera *camera;
float cameraFP[4];
float display[3], *world;
float *displayCoord;
float z;
// Initialize the picking process
this->Initialize();
this->Renderer = renderer;
this->SelectionPoint[0] = selectionX;
this->SelectionPoint[1] = selectionY;
this->SelectionPoint[2] = selectionZ;
// Invoke start pick method if defined
this->InvokeEvent(vtkCommand::StartPickEvent,NULL);
// Since renderers are rendered backwards from numlayers->0, the
// z-buffer data is wiped out for all but the last rendered layer (0).
// for multiple-layer renderwindows, we need to perform a pick render
// before accessing z-buffer info, or else we will get renderer[0]'s
// z-buffer info.
if (renderer->GetLayer() != 0)
{
vtkDebugMacro(<< " Renderer not on layer 0, Getting Z from PickProp() ");
renderer->PickProp((int) selectionX, (int) selectionY);
selectionZ = renderer->GetPickedZ();
vtkDebugMacro(<< " z from transparent renderer: " << selectionZ);
}
else
{
z = renderer->GetZ ((int) selectionX, (int) selectionY);
// if z is 1.0, we assume the user has picked a point on the
// screen that has not been rendered into. Use the camera's focal
// point for the z value. The test value .999999 has to be used
// instead of 1.0 because for some reason our SGI Infinite Reality
// engine won't return a 1.0 from the zbuffer
if (z < 0.999999)
{
selectionZ = z;
vtkDebugMacro(<< " z from zBuffer: " << selectionZ);
}
else
{
// Get camera focal point and position. Convert to display (screen)
// coordinates. We need a depth value for z-buffer.
camera = renderer->GetActiveCamera();
camera->GetFocalPoint((float *)cameraFP); cameraFP[3] = 1.0;
renderer->SetWorldPoint(cameraFP);
renderer->WorldToDisplay();
displayCoord = renderer->GetDisplayPoint();
selectionZ = displayCoord[2];
vtkDebugMacro(<< "computed z from focal point: " << selectionZ);
}
}
// now convert the display point to world coordinates
display[0] = selectionX;
display[1] = selectionY;
display[2] = selectionZ;
renderer->SetDisplayPoint (display);
renderer->DisplayToWorld ();
world = renderer->GetWorldPoint ();
for (int i=0; i < 3; i++)
{
this->PickPosition[i] = world[i] / world[3];
}
// Invoke end pick method if defined
this->InvokeEvent(vtkCommand::EndPickEvent,NULL);
return 0;
}
void vtkWorldPointPicker::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
<|endoftext|>
|
<commit_before>#include "manager.hpp"
#include <string.h>
using namespace std;
using namespace moodycamel;
using namespace headers;
using namespace chrono;
void Manager::initNetmap(){
if(geteuid() != 0){
fatal("You need to be root in order to use Netmap!");
}
routingTable = make_shared<LinuxTable>(this->interfaces);
//routingTable->print_table();
memset(&nmreq_root, 0, sizeof(struct nmreq));
nmreq_root.nr_version = NETMAP_API;
nmreq_root.nr_tx_slots = 2048;
nmreq_root.nr_rx_slots = 2048;
nmreq_root.nr_tx_rings = numWorkers;
nmreq_root.nr_rx_rings = numWorkers;
nmreq_root.nr_ringid = 0;
nmreq_root.nr_flags = NR_REG_NIC_SW;
nmreq_root.nr_cmd = 0;
nmreq_root.nr_arg1 = 0;
nmreq_root.nr_arg2 = 1;
nmreq_root.nr_arg3 = 256;
int iface_num=0;
for(auto iface : interfacesToUse){
logInfo("Manager::initNetmap Preparing interface " + iface);
int fd = 0;
fds.push_back(fd = open("/dev/netmap", O_RDWR));
strncpy(nmreq_root.nr_name, iface.c_str(), 16);
ioctl(fd, NIOCREGIF, &nmreq_root);
if(!mmapRegion){
mmapRegion = mmap(0, nmreq_root.nr_memsize,
PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(mmapRegion == MAP_FAILED){
logErr("Manager::initNetmap() mmap() failed (netmap module loaded?)");
logErr("error: " + string(strerror(errno)));
abort();
}
}
if(nmreq_root.nr_tx_rings != numWorkers){
stringstream sstream;
sstream << "Could not set the correct amount of TX rings!" << endl;
sstream << "Present: " << nmreq_root.nr_tx_rings << endl;
sstream << "Expected: " << numWorkers << endl;
sstream << "Please use the following command" << endl;
sstream << "ethtool -L " << iface <<" combined " << numWorkers << endl;
fatal(sstream.str());
}
if(nmreq_root.nr_rx_rings != numWorkers){
stringstream sstream;
sstream << "Could not set the correct amount of RX rings!" << endl;
sstream << "Present: " << nmreq_root.nr_rx_rings << endl;
sstream << "Expected: " << numWorkers << endl;
sstream << "Please use the following command" << endl;
sstream << "ethtool -L " << iface <<" combined " << numWorkers << endl;
fatal(sstream.str());
}
netmap_if* nifp = NETMAP_IF(mmapRegion, nmreq_root.nr_offset);
netmapIfs.push_back(nifp);
netmapTxRings.resize(netmapTxRings.size()+1);
netmapRxRings.resize(netmapRxRings.size()+1);
for(uint32_t i=0; i<nifp->ni_tx_rings+1; i++){
netmapTxRings[iface_num].push_back(NETMAP_TXRING(nifp, i));
}
for(uint32_t i=0; i<nifp->ni_rx_rings+1; i++){
netmapRxRings[iface_num].push_back(NETMAP_RXRING(nifp, i));
}
for(uint32_t bufIdx = nifp->ni_bufs_head; bufIdx;
bufIdx = * reinterpret_cast<uint32_t*>(NETMAP_BUF(netmapTxRings[0][0], bufIdx))){
freeBufs.push_back(bufIdx);
}
#ifdef DEBUG
logDebug("Having " + int2str(freeBufs.size()) + " free buffers at the moment");
#endif
shared_ptr<Interface> iface_ptr;
for(auto i : interfaces){
if(iface == i->name){
iface_ptr = i;
break;
}
}
if(iface_ptr == nullptr){
fatal("Manager::initNetmap something went wrong: netmap interface not found in netlink context");
}
iface_ptr->netmapIndex = iface_num++;
}
logInfo("Manager::initNetmap Interface preparations finished.\n");
for(unsigned int i=0; i<numWorkers; i++){
inRings.emplace_back(make_shared<ConcurrentQueue<frame>>(RING_SIZE));
outRings.emplace_back(make_shared<ConcurrentQueue<frame>>(RING_SIZE));
}
routingTable->buildNextHopList();
routingTable->print_table();
numInterfaces = netmapIfs.size();
curLPM = make_shared<LPM>(*(routingTable.get()));
};
std::vector<shared_ptr<Interface>> Manager::fillNetLink(){
vector<shared_ptr<Interface>> interfaces = Netlink::getAllInterfaces();
sort(interfaces.begin(), interfaces.end());
return interfaces;
};
void Manager::startWorkerThreads(){
arpTable.createCurrentTable(routingTable);
for(unsigned i=0; i<numWorkers; i++){
workers.push_back(new Worker(curLPM, arpTable.getCurrentTable(),
inRings[i], outRings[i], interfaces, i));
}
};
void Manager::startStatsThread(){
auto statsFun = [&](vector<Worker*> workers){
while(1){
for(auto w : workers){
w->printAndClearStats();
}
this_thread::sleep_for(chrono::milliseconds(1000));
}
};
statsThread = new thread(statsFun, workers);
};
void Manager::process(){
// Prepare poll fd set
pollfd* pfds = new pollfd[numInterfaces];
for(unsigned int i=0; i<numInterfaces; i++){
pfds[i].fd = fds[i];
pfds[i].events = POLLOUT | POLLIN;
}
// use poll to get new frames
if(0 > poll(pfds, numInterfaces, -1)){
fatal("poll() failed");
}
// Run over all interfaces and rings -> enqueue new frames for workers
for(uint16_t iface=0; iface < numInterfaces; iface++){
// netmap rings
for(unsigned int worker=0; worker < numWorkers; worker++){
netmap_ring* ring = netmapRxRings[iface][worker];
while(nm_ring_space(ring)){
uint32_t numFrames = nm_ring_space(ring);
numFrames = min(numFrames, (uint32_t) freeBufs.size());
if(numFrames == 0){
break;
}
if(numFrames > MANAGER_BULK_SIZE){
numFrames = MANAGER_BULK_SIZE;
}
uint32_t slotIdx = ring->head;
frame f[MANAGER_BULK_SIZE];
for(uint32_t i=0; i<numFrames; i++){
f[i].buf_ptr = reinterpret_cast<uint8_t*>(
NETMAP_BUF(ring, ring->slot[slotIdx].buf_idx));
f[i].len = ring->slot[slotIdx].len;
f[i].iface = iface;
f[i].vlan = 0;
#ifdef DEBUG
logDebug("Manager::process received frame from iface: " + int2str(f[i].iface)
+ ", length: " + int2str(f[i].len)
+ ", buf_idx: " + int2str(ring->slot[slotIdx].buf_idx)
+ ", buf_ptr: 0x" + int2strHex((uint64_t) f[i].buf_ptr));
#endif
ring->slot[slotIdx].buf_idx = freeBufs.back();
ring->slot[slotIdx].flags = NS_BUF_CHANGED;
freeBufs.pop_back();
#ifdef DEBUG
logDebug("Manager::process replacement rx buf_idx: "
+ int2str(ring->slot[slotIdx].buf_idx));
#endif
slotIdx = nm_ring_next(ring, slotIdx);
ring->head = slotIdx;
ring->cur = slotIdx;
}
inRings[worker]->try_enqueue_bulk(f, numFrames);
#ifdef DEBUG
logDebug("Manager::process enqueue new frames");
#endif
}
}
// TODO host ring
}
// Run over all frames processed by the workers and enqueue to netmap
for(unsigned int worker=0; worker < numWorkers; worker++){
frame frame;
while(outRings[worker]->try_dequeue(frame)){
// Check for discard/host/arp flag
unsigned int ringid;
if(frame.iface & frame::IFACE_HOST){
#ifdef DEBUG
logDebug("Manager::process Forwarding frame to kernel");
#endif
ringid = numWorkers;
} else if(frame.iface & frame::IFACE_ARP){
#ifdef DEBUG
logDebug("Manager::process handling ARP frame");
#endif
ringid = worker;
arpTable.handleFrame(frame);
} else if(frame.iface & frame::IFACE_NOMAC){
#ifdef DEBUG
logDebug("Manager::process no MAC for target");
#endif
ringid = worker;
ipv4* ipv4_hdr = reinterpret_cast<ipv4*>(frame.buf_ptr + sizeof(ether));
uint32_t ip = ipv4_hdr->d_ip;
auto it = missingMACs.find(ip);
if(it == missingMACs.end()){
#ifdef DEBUG
stringstream sstream;
sstream << "Manager::process no ARP request sent yet,";
sstream << " sending now via interface ";
sstream << (frame.iface & frame::IFACE_ID);
logDebug(sstream.str());
#endif
macRequest mr;
mr.ip = ip;
mr.iface = frame.iface & frame::IFACE_ID;
mr.time = steady_clock::now();
arpTable.prepareRequest(ip, frame.iface & frame::IFACE_ID, frame);
missingMACs[ip] = mr;
} else {
//duration<double> diff = it->second.time - steady_clock::now();
//if(diff.count() < 0.5){
if(false){
// Give it a bit more time and just discard the frame
frame.iface |= frame::IFACE_DISCARD;
#ifdef DEBUG
logDebug("Manager::process no new ARP request");
#endif
} else {
// Send out a new ARP Request
arpTable.prepareRequest(ip, frame.iface & frame::IFACE_ID, frame);
#ifdef DEBUG
logDebug("Manager::process prepare new ARP request");
#endif
}
}
} else {
ringid = worker;
}
if(frame.iface & frame::IFACE_DISCARD){
// Just reclaim buffer
#ifdef DEBUG
logDebug("Manager::process discarding frame");
#endif
freeBufs.push_back(NETMAP_BUF_IDX(netmapTxRings[0][0], frame.buf_ptr));
continue;
}
uint16_t iface = frame.iface & frame::IFACE_ID;
netmap_ring* ring = netmapTxRings[iface][ringid];
uint32_t slotIdx = ring->head;
// Make sure frame has at least minimum size
if(frame.len < 60){
frame.len = 60;
}
if(nm_ring_space(ring)){
freeBufs.push_back(ring->slot[slotIdx].buf_idx);
ring->slot[slotIdx].buf_idx = NETMAP_BUF_IDX(ring, frame.buf_ptr);
ring->slot[slotIdx].flags = NS_BUF_CHANGED;
ring->slot[slotIdx].len = frame.len;
ring->head = nm_ring_next(ring, ring->head);
ring->cur = ring->head;
} else {
freeBufs.push_back(NETMAP_BUF_IDX(ring, frame.buf_ptr));
}
#ifdef DEBUG
logDebug("Manager::process sending frame to netmap,\n iface: " + int2str(iface)
+ ", slotIdx: " + int2str(slotIdx)
+ ", buf_idx: " + int2str(ring->slot[slotIdx].buf_idx)
+ ", length: " + int2str(ring->slot[slotIdx].len));
logDebug("Manager::process Hexdump of frame:");
neolib::hex_dump(NETMAP_BUF(ring, ring->slot[slotIdx].buf_idx),
ring->slot[slotIdx].len , cerr);
#endif
}
}
}
void Manager::printInterfaces(){
#ifdef DEBUG
for(auto i : interfaces){
logDebug(i->toString());
}
#endif
};
<commit_msg>reenable ARP rate limiter<commit_after>#include "manager.hpp"
#include <string.h>
using namespace std;
using namespace moodycamel;
using namespace headers;
using namespace chrono;
void Manager::initNetmap(){
if(geteuid() != 0){
fatal("You need to be root in order to use Netmap!");
}
routingTable = make_shared<LinuxTable>(this->interfaces);
//routingTable->print_table();
memset(&nmreq_root, 0, sizeof(struct nmreq));
nmreq_root.nr_version = NETMAP_API;
nmreq_root.nr_tx_slots = 2048;
nmreq_root.nr_rx_slots = 2048;
nmreq_root.nr_tx_rings = numWorkers;
nmreq_root.nr_rx_rings = numWorkers;
nmreq_root.nr_ringid = 0;
nmreq_root.nr_flags = NR_REG_NIC_SW;
nmreq_root.nr_cmd = 0;
nmreq_root.nr_arg1 = 0;
nmreq_root.nr_arg2 = 1;
nmreq_root.nr_arg3 = 256;
int iface_num=0;
for(auto iface : interfacesToUse){
logInfo("Manager::initNetmap Preparing interface " + iface);
int fd = 0;
fds.push_back(fd = open("/dev/netmap", O_RDWR));
strncpy(nmreq_root.nr_name, iface.c_str(), 16);
ioctl(fd, NIOCREGIF, &nmreq_root);
if(!mmapRegion){
mmapRegion = mmap(0, nmreq_root.nr_memsize,
PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(mmapRegion == MAP_FAILED){
logErr("Manager::initNetmap() mmap() failed (netmap module loaded?)");
logErr("error: " + string(strerror(errno)));
abort();
}
}
if(nmreq_root.nr_tx_rings != numWorkers){
stringstream sstream;
sstream << "Could not set the correct amount of TX rings!" << endl;
sstream << "Present: " << nmreq_root.nr_tx_rings << endl;
sstream << "Expected: " << numWorkers << endl;
sstream << "Please use the following command" << endl;
sstream << "ethtool -L " << iface <<" combined " << numWorkers << endl;
fatal(sstream.str());
}
if(nmreq_root.nr_rx_rings != numWorkers){
stringstream sstream;
sstream << "Could not set the correct amount of RX rings!" << endl;
sstream << "Present: " << nmreq_root.nr_rx_rings << endl;
sstream << "Expected: " << numWorkers << endl;
sstream << "Please use the following command" << endl;
sstream << "ethtool -L " << iface <<" combined " << numWorkers << endl;
fatal(sstream.str());
}
netmap_if* nifp = NETMAP_IF(mmapRegion, nmreq_root.nr_offset);
netmapIfs.push_back(nifp);
netmapTxRings.resize(netmapTxRings.size()+1);
netmapRxRings.resize(netmapRxRings.size()+1);
for(uint32_t i=0; i<nifp->ni_tx_rings+1; i++){
netmapTxRings[iface_num].push_back(NETMAP_TXRING(nifp, i));
}
for(uint32_t i=0; i<nifp->ni_rx_rings+1; i++){
netmapRxRings[iface_num].push_back(NETMAP_RXRING(nifp, i));
}
for(uint32_t bufIdx = nifp->ni_bufs_head; bufIdx;
bufIdx = * reinterpret_cast<uint32_t*>(NETMAP_BUF(netmapTxRings[0][0], bufIdx))){
freeBufs.push_back(bufIdx);
}
#ifdef DEBUG
logDebug("Having " + int2str(freeBufs.size()) + " free buffers at the moment");
#endif
shared_ptr<Interface> iface_ptr;
for(auto i : interfaces){
if(iface == i->name){
iface_ptr = i;
break;
}
}
if(iface_ptr == nullptr){
fatal("Manager::initNetmap something went wrong: netmap interface not found in netlink context");
}
iface_ptr->netmapIndex = iface_num++;
}
logInfo("Manager::initNetmap Interface preparations finished.\n");
for(unsigned int i=0; i<numWorkers; i++){
inRings.emplace_back(make_shared<ConcurrentQueue<frame>>(RING_SIZE));
outRings.emplace_back(make_shared<ConcurrentQueue<frame>>(RING_SIZE));
}
routingTable->buildNextHopList();
routingTable->print_table();
numInterfaces = netmapIfs.size();
curLPM = make_shared<LPM>(*(routingTable.get()));
};
std::vector<shared_ptr<Interface>> Manager::fillNetLink(){
vector<shared_ptr<Interface>> interfaces = Netlink::getAllInterfaces();
sort(interfaces.begin(), interfaces.end());
return interfaces;
};
void Manager::startWorkerThreads(){
arpTable.createCurrentTable(routingTable);
for(unsigned i=0; i<numWorkers; i++){
workers.push_back(new Worker(curLPM, arpTable.getCurrentTable(),
inRings[i], outRings[i], interfaces, i));
}
};
void Manager::startStatsThread(){
auto statsFun = [&](vector<Worker*> workers){
while(1){
for(auto w : workers){
w->printAndClearStats();
}
this_thread::sleep_for(chrono::milliseconds(1000));
}
};
statsThread = new thread(statsFun, workers);
};
void Manager::process(){
// Prepare poll fd set
pollfd* pfds = new pollfd[numInterfaces];
for(unsigned int i=0; i<numInterfaces; i++){
pfds[i].fd = fds[i];
pfds[i].events = POLLOUT | POLLIN;
}
// use poll to get new frames
if(0 > poll(pfds, numInterfaces, -1)){
fatal("poll() failed");
}
// Run over all interfaces and rings -> enqueue new frames for workers
for(uint16_t iface=0; iface < numInterfaces; iface++){
// netmap rings
for(unsigned int worker=0; worker < numWorkers; worker++){
netmap_ring* ring = netmapRxRings[iface][worker];
while(nm_ring_space(ring)){
uint32_t numFrames = nm_ring_space(ring);
numFrames = min(numFrames, (uint32_t) freeBufs.size());
if(numFrames == 0){
break;
}
if(numFrames > MANAGER_BULK_SIZE){
numFrames = MANAGER_BULK_SIZE;
}
uint32_t slotIdx = ring->head;
frame f[MANAGER_BULK_SIZE];
for(uint32_t i=0; i<numFrames; i++){
f[i].buf_ptr = reinterpret_cast<uint8_t*>(
NETMAP_BUF(ring, ring->slot[slotIdx].buf_idx));
f[i].len = ring->slot[slotIdx].len;
f[i].iface = iface;
f[i].vlan = 0;
#ifdef DEBUG
logDebug("Manager::process received frame from iface: " + int2str(f[i].iface)
+ ", length: " + int2str(f[i].len)
+ ", buf_idx: " + int2str(ring->slot[slotIdx].buf_idx)
+ ", buf_ptr: 0x" + int2strHex((uint64_t) f[i].buf_ptr));
#endif
ring->slot[slotIdx].buf_idx = freeBufs.back();
ring->slot[slotIdx].flags = NS_BUF_CHANGED;
freeBufs.pop_back();
#ifdef DEBUG
logDebug("Manager::process replacement rx buf_idx: "
+ int2str(ring->slot[slotIdx].buf_idx));
#endif
slotIdx = nm_ring_next(ring, slotIdx);
ring->head = slotIdx;
ring->cur = slotIdx;
}
inRings[worker]->try_enqueue_bulk(f, numFrames);
#ifdef DEBUG
logDebug("Manager::process enqueue new frames");
#endif
}
}
// TODO host ring
}
// Run over all frames processed by the workers and enqueue to netmap
for(unsigned int worker=0; worker < numWorkers; worker++){
frame frame;
while(outRings[worker]->try_dequeue(frame)){
// Check for discard/host/arp flag
unsigned int ringid;
if(frame.iface & frame::IFACE_HOST){
#ifdef DEBUG
logDebug("Manager::process Forwarding frame to kernel");
#endif
ringid = numWorkers;
} else if(frame.iface & frame::IFACE_ARP){
#ifdef DEBUG
logDebug("Manager::process handling ARP frame");
#endif
ringid = worker;
arpTable.handleFrame(frame);
} else if(frame.iface & frame::IFACE_NOMAC){
#ifdef DEBUG
logDebug("Manager::process no MAC for target");
#endif
ringid = worker;
ipv4* ipv4_hdr = reinterpret_cast<ipv4*>(frame.buf_ptr + sizeof(ether));
uint32_t ip = ipv4_hdr->d_ip;
auto it = missingMACs.find(ip);
if(it == missingMACs.end()){
#ifdef DEBUG
stringstream sstream;
sstream << "Manager::process no ARP request sent yet,";
sstream << " sending now via interface ";
sstream << (frame.iface & frame::IFACE_ID);
logDebug(sstream.str());
#endif
macRequest mr;
mr.ip = ip;
mr.iface = frame.iface & frame::IFACE_ID;
mr.time = steady_clock::now();
arpTable.prepareRequest(ip, frame.iface & frame::IFACE_ID, frame);
missingMACs[ip] = mr;
} else {
duration<double> diff = it->second.time - steady_clock::now();
if(diff.count() < 0.5){
//if(false){
// Give it a bit more time and just discard the frame
frame.iface |= frame::IFACE_DISCARD;
#ifdef DEBUG
logDebug("Manager::process no new ARP request");
#endif
} else {
// Send out a new ARP Request
arpTable.prepareRequest(ip, frame.iface & frame::IFACE_ID, frame);
#ifdef DEBUG
logDebug("Manager::process prepare new ARP request");
#endif
}
}
} else {
ringid = worker;
}
if(frame.iface & frame::IFACE_DISCARD){
// Just reclaim buffer
#ifdef DEBUG
logDebug("Manager::process discarding frame");
#endif
freeBufs.push_back(NETMAP_BUF_IDX(netmapTxRings[0][0], frame.buf_ptr));
continue;
}
uint16_t iface = frame.iface & frame::IFACE_ID;
netmap_ring* ring = netmapTxRings[iface][ringid];
uint32_t slotIdx = ring->head;
// Make sure frame has at least minimum size
if(frame.len < 60){
frame.len = 60;
}
if(nm_ring_space(ring)){
freeBufs.push_back(ring->slot[slotIdx].buf_idx);
ring->slot[slotIdx].buf_idx = NETMAP_BUF_IDX(ring, frame.buf_ptr);
ring->slot[slotIdx].flags = NS_BUF_CHANGED;
ring->slot[slotIdx].len = frame.len;
ring->head = nm_ring_next(ring, ring->head);
ring->cur = ring->head;
} else {
freeBufs.push_back(NETMAP_BUF_IDX(ring, frame.buf_ptr));
}
#ifdef DEBUG
logDebug("Manager::process sending frame to netmap,\n iface: " + int2str(iface)
+ ", slotIdx: " + int2str(slotIdx)
+ ", buf_idx: " + int2str(ring->slot[slotIdx].buf_idx)
+ ", length: " + int2str(ring->slot[slotIdx].len));
logDebug("Manager::process Hexdump of frame:");
neolib::hex_dump(NETMAP_BUF(ring, ring->slot[slotIdx].buf_idx),
ring->slot[slotIdx].len , cerr);
#endif
}
}
}
void Manager::printInterfaces(){
#ifdef DEBUG
for(auto i : interfaces){
logDebug(i->toString());
}
#endif
};
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_OPENCL_COPY_HPP
#define STAN_MATH_PRIM_MAT_FUN_OPENCL_COPY_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/opencl_context.hpp>
#include <stan/math/opencl/kernel_cl.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/kernels/copy.hpp>
#include <stan/math/opencl/kernels/pack.hpp>
#include <stan/math/opencl/kernels/unpack.hpp>
#include <stan/math/opencl/buffer_types.hpp>
#include <stan/math/opencl/err/check_opencl.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/scal/err/check_size_match.hpp>
#include <stan/math/prim/arr/fun/vec_concat.hpp>
#include <CL/cl.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
#include <type_traits>
namespace stan {
namespace math {
/**
* Copies the source Eigen matrix to
* the destination matrix that is stored
* on the OpenCL device.
*
* @tparam T type of data in the Eigen matrix
* @param dst destination matrix on the OpenCL device
* @param src source Eigen matrix
*
* @throw <code>std::invalid_argument</code> if the
* matrices do not have matching dimensions
*/
template <int R, int C>
void copy(matrix_cl& dst, const Eigen::Matrix<double, R, C>& src) {
check_size_match("copy (Eigen -> (OpenCL))", "src.rows()", src.rows(),
"dst.rows()", dst.rows());
check_size_match("copy (Eigen -> (OpenCL))", "src.cols()", src.cols(),
"dst.cols()", dst.cols());
if (src.size() == 0) {
return;
}
try {
/**
* Writes the contents of src to the OpenCL buffer
* starting at the offset 0
* CL_FALSE denotes that the call is non-blocking
* This means that future kernels need to know about the copy_event
* So that they do not execute until this transfer finishes.
*/
cl::CommandQueue queue = opencl_context.queue();
cl::Event copy_event;
queue.enqueueBarrierWithWaitList(&dst.read_write_events());
dst.clear_read_write_events();
queue.enqueueWriteBuffer(dst.buffer(), CL_FALSE, 0,
sizeof(double) * dst.size(), src.data(),
&dst.read_write_events(), ©_event);
dst.add_write_event(copy_event);
} catch (const cl::Error& e) {
check_opencl_error("copy Eigen->(OpenCL)", e);
}
}
/**
* Copies the source matrix that is stored
* on the OpenCL device to the destination Eigen
* matrix.
*
* @tparam T type of data in the Eigen matrix
* @param dst destination Eigen matrix
* @param src source matrix on the OpenCL device
*
* @throw <code>std::invalid_argument</code> if the
* matrices do not have matching dimensions
*/
template <int R, int C>
void copy(Eigen::Matrix<double, R, C>& dst, const matrix_cl& src) {
check_size_match("copy ((OpenCL) -> Eigen)", "src.rows()", src.rows(),
"dst.rows()", dst.rows());
check_size_match("copy ((OpenCL) -> Eigen)", "src.cols()", src.cols(),
"dst.cols()", dst.cols());
if (src.size() == 0) {
return;
}
try {
/**
* Reads the contents of the OpenCL buffer
* starting at the offset 0 to the Eigen
* matrix
* CL_TRUE denotes that the call is blocking
* We do not want to pass data back to the CPU until all of the jobs
* called on the source matrix are finished.
*/
cl::CommandQueue queue = opencl_context.queue();
cl::Event copy_event;
queue.enqueueReadBuffer(src.buffer(), CL_TRUE, 0,
sizeof(double) * dst.size(), dst.data(),
&src.read_write_events(), ©_event);
copy_event.wait();
src.clear_read_write_events();
} catch (const cl::Error& e) {
check_opencl_error("copy (OpenCL)->Eigen", e);
}
}
/**
* Packs the flat triagnular matrix on the OpenCL device and
* copies it to the std::vector.
*
* @tparam triangular_view the triangularity of the source matrix
* @param src the flat triangular source matrix on the OpenCL device
* @return the packed std::vector
*/
template <TriangularViewCL triangular_view>
inline std::vector<double> packed_copy(const matrix_cl& src) {
const int packed_size = src.rows() * (src.rows() + 1) / 2;
std::vector<double> dst(packed_size);
if (dst.size() == 0) {
return dst;
}
try {
cl::CommandQueue queue = opencl_context.queue();
matrix_cl packed(packed_size, 1);
stan::math::opencl_kernels::pack(cl::NDRange(src.rows(), src.rows()),
packed, src, src.rows(), src.rows(),
triangular_view);
cl::Event copy_event;
queue.enqueueReadBuffer(packed.buffer(), CL_FALSE, 0,
sizeof(double) * packed_size, dst.data(),
&packed.read_write_events(), ©_event);
copy_event.wait();
src.clear_read_write_events();
} catch (const cl::Error& e) {
check_opencl_error("packed_copy (OpenCL->std::vector)", e);
}
return dst;
}
/**
* Copies the packed triangular matrix from
* the source std::vector to an OpenCL buffer and
* unpacks it to a flat matrix on the OpenCL device.
*
* @tparam triangular_view the triangularity of the source matrix
* @param src the packed source std::vector
* @param rows the number of rows in the flat matrix
* @return the destination flat matrix on the OpenCL device
* @throw <code>std::invalid_argument</code> if the
* size of the vector does not match the expected size
* for the packed triangular matrix
*/
template <TriangularViewCL triangular_view>
inline matrix_cl packed_copy(const std::vector<double>& src, int rows) {
const int packed_size = rows * (rows + 1) / 2;
check_size_match("copy (packed std::vector -> OpenCL)", "src.size()",
src.size(), "rows * (rows + 1) / 2", packed_size);
matrix_cl dst(rows, rows);
if (dst.size() == 0) {
return dst;
}
try {
cl::CommandQueue queue = opencl_context.queue();
matrix_cl packed(packed_size, 1);
cl::Event packed_event;
queue.enqueueWriteBuffer(packed.buffer(), CL_FALSE, 0,
sizeof(double) * packed_size, src.data(), NULL,
&packed_event);
packed.add_write_event(packed_event);
stan::math::opencl_kernels::unpack(cl::NDRange(dst.rows(), dst.rows()), dst,
packed, dst.rows(), dst.rows(),
triangular_view);
} catch (const cl::Error& e) {
check_opencl_error("packed_copy (std::vector->OpenCL)", e);
}
return dst;
}
/**
* Copies the source matrix to the
* destination matrix. Both matrices
* are stored on the OpenCL device.
*
* @param dst destination matrix
* @param src source matrix
*
* @throw <code>std::invalid_argument</code> if the
* matrices do not have matching dimensions
*/
inline void copy(matrix_cl& dst, const matrix_cl& src) {
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.rows()", src.rows(),
"dst.rows()", dst.rows());
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.cols()", src.cols(),
"dst.cols()", dst.cols());
if (src.size() == 0) {
return;
}
try {
/**
* Copies the contents of the src buffer to the dst buffer
* see the matrix_cl(matrix_cl&) constructor
* for explanation
*/
cl::CommandQueue queue = opencl_context.queue();
auto mat_events = vec_concat(dst.read_write_events(), src.write_events());
cl::Event copy_event;
queue.enqueueCopyBuffer(src.buffer(), dst.buffer(), 0, 0,
sizeof(double) * src.size(), &mat_events,
©_event);
dst.add_write_event(copy_event);
src.add_read_event(copy_event);
} catch (const cl::Error& e) {
check_opencl_error("copy (OpenCL)->(OpenCL)", e);
}
}
/**
* Copy A 1 by 1 source matrix from the Device to the host.
* @tparam An arithmetic type to pass the value from the OpenCL matrix to.
* @param dst Arithmetic to receive the matrix_cl value.
* @param src A 1x1 matrix on the device.
*/
template <typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0>
inline void copy(T& dst, const matrix_cl& src) {
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.rows()", src.rows(),
"dst.rows()", 1);
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.cols()", src.cols(),
"dst.cols()", 1);
try {
cl::CommandQueue queue = opencl_context.queue();
cl::Event copy_event;
queue.enqueueReadBuffer(src.buffer(), CL_FALSE, 0, sizeof(int), &dst,
&src.write_events(), ©_event);
copy_event.wait();
src.clear_read_write_events();
} catch (const cl::Error& e) {
check_opencl_error("copy (OpenCL)->(OpenCL)", e);
}
}
/**
* Copy an arithmetic type to the device.
* @tparam An arithmetic type to pass the value from the OpenCL matrix to.
* @param src Arithmetic to receive the matrix_cl value.
* @param dst A 1x1 matrix on the device.
*/
template <typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0>
inline void copy(matrix_cl& dst, const T& src) {
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.rows()", dst.rows(),
"dst.rows()", 1);
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.cols()", dst.cols(),
"dst.cols()", 1);
try {
cl::CommandQueue queue = opencl_context.queue();
cl::Event copy_event;
queue.enqueueBarrierWithWaitList(&dst.read_write_events());
dst.clear_read_write_events();
queue.enqueueWriteBuffer(dst.buffer(), CL_FALSE, 0, sizeof(T), &src,
&dst.read_write_events(), ©_event);
dst.add_write_event(copy_event);
} catch (const cl::Error& e) {
check_opencl_error("copy (OpenCL)->(OpenCL)", e);
}
}
} // namespace math
} // namespace stan
#endif
#endif
<commit_msg>set copy to host to only wait for write events<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_OPENCL_COPY_HPP
#define STAN_MATH_PRIM_MAT_FUN_OPENCL_COPY_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/opencl_context.hpp>
#include <stan/math/opencl/kernel_cl.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/kernels/copy.hpp>
#include <stan/math/opencl/kernels/pack.hpp>
#include <stan/math/opencl/kernels/unpack.hpp>
#include <stan/math/opencl/buffer_types.hpp>
#include <stan/math/opencl/err/check_opencl.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/scal/err/check_size_match.hpp>
#include <stan/math/prim/arr/fun/vec_concat.hpp>
#include <CL/cl.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
#include <type_traits>
namespace stan {
namespace math {
/**
* Copies the source Eigen matrix to
* the destination matrix that is stored
* on the OpenCL device.
*
* @tparam T type of data in the Eigen matrix
* @param dst destination matrix on the OpenCL device
* @param src source Eigen matrix
*
* @throw <code>std::invalid_argument</code> if the
* matrices do not have matching dimensions
*/
template <int R, int C>
void copy(matrix_cl& dst, const Eigen::Matrix<double, R, C>& src) {
check_size_match("copy (Eigen -> (OpenCL))", "src.rows()", src.rows(),
"dst.rows()", dst.rows());
check_size_match("copy (Eigen -> (OpenCL))", "src.cols()", src.cols(),
"dst.cols()", dst.cols());
if (src.size() == 0) {
return;
}
try {
/**
* Writes the contents of src to the OpenCL buffer
* starting at the offset 0
* CL_FALSE denotes that the call is non-blocking
* This means that future kernels need to know about the copy_event
* So that they do not execute until this transfer finishes.
*/
cl::CommandQueue queue = opencl_context.queue();
cl::Event copy_event;
queue.enqueueBarrierWithWaitList(&dst.read_write_events());
dst.clear_read_write_events();
queue.enqueueWriteBuffer(dst.buffer(), CL_FALSE, 0,
sizeof(double) * dst.size(), src.data(),
&dst.read_write_events(), ©_event);
dst.add_write_event(copy_event);
} catch (const cl::Error& e) {
check_opencl_error("copy Eigen->(OpenCL)", e);
}
}
/**
* Copies the source matrix that is stored
* on the OpenCL device to the destination Eigen
* matrix.
*
* @tparam T type of data in the Eigen matrix
* @param dst destination Eigen matrix
* @param src source matrix on the OpenCL device
*
* @throw <code>std::invalid_argument</code> if the
* matrices do not have matching dimensions
*/
template <int R, int C>
void copy(Eigen::Matrix<double, R, C>& dst, const matrix_cl& src) {
check_size_match("copy ((OpenCL) -> Eigen)", "src.rows()", src.rows(),
"dst.rows()", dst.rows());
check_size_match("copy ((OpenCL) -> Eigen)", "src.cols()", src.cols(),
"dst.cols()", dst.cols());
if (src.size() == 0) {
return;
}
try {
/**
* Reads the contents of the OpenCL buffer
* starting at the offset 0 to the Eigen
* matrix
* CL_TRUE denotes that the call is blocking
* We do not want to pass data back to the CPU until all of the jobs
* called on the source matrix are finished.
*/
cl::CommandQueue queue = opencl_context.queue();
cl::Event copy_event;
queue.enqueueReadBuffer(src.buffer(), CL_FALSE, 0,
sizeof(double) * dst.size(), dst.data(),
&src.write_events(), ©_event);
copy_event.wait();
src.clear_write_events();
} catch (const cl::Error& e) {
check_opencl_error("copy (OpenCL)->Eigen", e);
}
}
/**
* Packs the flat triagnular matrix on the OpenCL device and
* copies it to the std::vector.
*
* @tparam triangular_view the triangularity of the source matrix
* @param src the flat triangular source matrix on the OpenCL device
* @return the packed std::vector
*/
template <TriangularViewCL triangular_view>
inline std::vector<double> packed_copy(const matrix_cl& src) {
const int packed_size = src.rows() * (src.rows() + 1) / 2;
std::vector<double> dst(packed_size);
if (dst.size() == 0) {
return dst;
}
try {
cl::CommandQueue queue = opencl_context.queue();
matrix_cl packed(packed_size, 1);
stan::math::opencl_kernels::pack(cl::NDRange(src.rows(), src.rows()),
packed, src, src.rows(), src.rows(),
triangular_view);
cl::Event copy_event;
queue.enqueueReadBuffer(packed.buffer(), CL_FALSE, 0,
sizeof(double) * packed_size, dst.data(),
&packed.write_events(), ©_event);
} catch (const cl::Error& e) {
check_opencl_error("packed_copy (OpenCL->std::vector)", e);
}
return dst;
}
/**
* Copies the packed triangular matrix from
* the source std::vector to an OpenCL buffer and
* unpacks it to a flat matrix on the OpenCL device.
*
* @tparam triangular_view the triangularity of the source matrix
* @param src the packed source std::vector
* @param rows the number of rows in the flat matrix
* @return the destination flat matrix on the OpenCL device
* @throw <code>std::invalid_argument</code> if the
* size of the vector does not match the expected size
* for the packed triangular matrix
*/
template <TriangularViewCL triangular_view>
inline matrix_cl packed_copy(const std::vector<double>& src, int rows) {
const int packed_size = rows * (rows + 1) / 2;
check_size_match("copy (packed std::vector -> OpenCL)", "src.size()",
src.size(), "rows * (rows + 1) / 2", packed_size);
matrix_cl dst(rows, rows);
if (dst.size() == 0) {
return dst;
}
try {
cl::CommandQueue queue = opencl_context.queue();
matrix_cl packed(packed_size, 1);
cl::Event packed_event;
queue.enqueueWriteBuffer(packed.buffer(), CL_FALSE, 0,
sizeof(double) * packed_size, src.data(), NULL,
&packed_event);
packed.add_write_event(packed_event);
stan::math::opencl_kernels::unpack(cl::NDRange(dst.rows(), dst.rows()), dst,
packed, dst.rows(), dst.rows(),
triangular_view);
} catch (const cl::Error& e) {
check_opencl_error("packed_copy (std::vector->OpenCL)", e);
}
return dst;
}
/**
* Copies the source matrix to the
* destination matrix. Both matrices
* are stored on the OpenCL device.
*
* @param dst destination matrix
* @param src source matrix
*
* @throw <code>std::invalid_argument</code> if the
* matrices do not have matching dimensions
*/
inline void copy(matrix_cl& dst, const matrix_cl& src) {
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.rows()", src.rows(),
"dst.rows()", dst.rows());
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.cols()", src.cols(),
"dst.cols()", dst.cols());
if (src.size() == 0) {
return;
}
try {
/**
* Copies the contents of the src buffer to the dst buffer
* see the matrix_cl(matrix_cl&) constructor
* for explanation
*/
cl::CommandQueue queue = opencl_context.queue();
auto mat_events = vec_concat(dst.read_write_events(), src.write_events());
cl::Event copy_event;
queue.enqueueCopyBuffer(src.buffer(), dst.buffer(), 0, 0,
sizeof(double) * src.size(), &mat_events,
©_event);
dst.add_write_event(copy_event);
src.add_read_event(copy_event);
} catch (const cl::Error& e) {
check_opencl_error("copy (OpenCL)->(OpenCL)", e);
}
}
/**
* Copy A 1 by 1 source matrix from the Device to the host.
* @tparam An arithmetic type to pass the value from the OpenCL matrix to.
* @param dst Arithmetic to receive the matrix_cl value.
* @param src A 1x1 matrix on the device.
*/
template <typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0>
inline void copy(T& dst, const matrix_cl& src) {
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.rows()", src.rows(),
"dst.rows()", 1);
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.cols()", src.cols(),
"dst.cols()", 1);
try {
cl::CommandQueue queue = opencl_context.queue();
cl::Event copy_event;
queue.enqueueReadBuffer(src.buffer(), CL_FALSE, 0, sizeof(int), &dst,
&src.write_events(), ©_event);
copy_event.wait();
} catch (const cl::Error& e) {
check_opencl_error("copy (OpenCL)->(OpenCL)", e);
}
}
/**
* Copy an arithmetic type to the device.
* @tparam An arithmetic type to pass the value from the OpenCL matrix to.
* @param src Arithmetic to receive the matrix_cl value.
* @param dst A 1x1 matrix on the device.
*/
template <typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0>
inline void copy(matrix_cl& dst, const T& src) {
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.rows()", dst.rows(),
"dst.rows()", 1);
check_size_match("copy ((OpenCL) -> (OpenCL))", "src.cols()", dst.cols(),
"dst.cols()", 1);
try {
cl::CommandQueue queue = opencl_context.queue();
cl::Event copy_event;
queue.enqueueBarrierWithWaitList(&dst.read_write_events());
dst.clear_read_write_events();
queue.enqueueWriteBuffer(dst.buffer(), CL_FALSE, 0, sizeof(T), &src,
&dst.read_write_events(), ©_event);
dst.add_write_event(copy_event);
} catch (const cl::Error& e) {
check_opencl_error("copy (OpenCL)->(OpenCL)", e);
}
}
} // namespace math
} // namespace stan
#endif
#endif
<|endoftext|>
|
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Testing/MathUtilities.h"
#include "SurgSim/Math/Quaternion.h"
using SurgSim::Math::Vector3d;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::makeRotationQuaternion;
using SurgSim::Math::makeRigidTransform;
namespace SurgSim
{
namespace Testing
{
SurgSim::Math::RigidTransform3d interpolatePose(
const Vector3d& startAngles,
const Vector3d& endAngles,
const Vector3d& startPosition,
const Vector3d& endPosition,
const double& t)
{
Vector3d angles = interpolate(startAngles, endAngles, t);
Vector3d position = interpolate(startPosition, endPosition, t);
return makeRigidTransform<Quaterniond,Vector3d>(
Quaterniond(makeRotationQuaternion<double, Eigen::DontAlign>(angles.x(), Vector3d::UnitX()) *
makeRotationQuaternion<double, Eigen::DontAlign>(angles.y(), Vector3d::UnitY()) *
makeRotationQuaternion<double, Eigen::DontAlign>(angles.z(), Vector3d::UnitZ())),
position);
}
template <>
SurgSim::Math::Quaterniond interpolate(
const SurgSim::Math::Quaterniond& start,
const SurgSim::Math::Quaterniond& end,
const double& t)
{
return SurgSim::Math::interpolate(start, end, t);
}
template <>
SurgSim::Math::RigidTransform3d interpolate(
const SurgSim::Math::RigidTransform3d& start,
const SurgSim::Math::RigidTransform3d& end,
const double& t)
{
return SurgSim::Math::interpolate(start, end, t);
}
}; // Testing
}; // SurgSim
<commit_msg>Remove Eigen::DontAlign in MathUtilities.cpp<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Testing/MathUtilities.h"
#include "SurgSim/Math/Quaternion.h"
using SurgSim::Math::Vector3d;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::makeRotationQuaternion;
using SurgSim::Math::makeRigidTransform;
namespace SurgSim
{
namespace Testing
{
SurgSim::Math::RigidTransform3d interpolatePose(
const Vector3d& startAngles,
const Vector3d& endAngles,
const Vector3d& startPosition,
const Vector3d& endPosition,
const double& t)
{
Vector3d angles = interpolate(startAngles, endAngles, t);
Vector3d position = interpolate(startPosition, endPosition, t);
return makeRigidTransform<Quaterniond,Vector3d>(
Quaterniond(makeRotationQuaternion(angles.x(), Vector3d::UnitX().eval()) *
makeRotationQuaternion(angles.y(), Vector3d::UnitY().eval()) *
makeRotationQuaternion(angles.z(), Vector3d::UnitZ().eval())),
position);
}
template <>
SurgSim::Math::Quaterniond interpolate(
const SurgSim::Math::Quaterniond& start,
const SurgSim::Math::Quaterniond& end,
const double& t)
{
return SurgSim::Math::interpolate(start, end, t);
}
template <>
SurgSim::Math::RigidTransform3d interpolate(
const SurgSim::Math::RigidTransform3d& start,
const SurgSim::Math::RigidTransform3d& end,
const double& t)
{
return SurgSim::Math::interpolate(start, end, t);
}
}; // Testing
}; // SurgSim
<|endoftext|>
|
<commit_before>#include "optimize.hpp"
#include <vector>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <stdexcept>
#include <limits>
#include <algorithm>
#include "pll_util.hpp"
#include "constants.hpp"
using namespace std;
// local helpers
void traverse_update_partials(pll_utree_t * tree, pll_partition_t * partition,
pll_utree_t ** travbuffer, double * branch_lengths, unsigned int * matrix_indices,
pll_operation_t * operations);
double compute_negative_lnl_unrooted_ranged (void * p, double *x);
double optimize_triplet_lbfgsb_ranged (pll_partition_t * partition, pll_utree_t * tree,
double factr, double pgtol, unsigned int begin, unsigned int span);
double compute_edge_loglikelihood_ranged(pll_partition_t * partition,
unsigned int parent_clv_index, int parent_scaler_index, unsigned int child_clv_index,
int child_scaler_index, unsigned int matrix_index, unsigned int freqs_index,
unsigned int begin, unsigned int span);
void update_partial_ranged(pll_partition_t * partition, pll_operation_t * op,
unsigned int begin, unsigned int span);
double pll_optimize_parameters_brent_ranged(pll_optimize_options_t * params,
double xmin, double xguess, double xmax);
void update_partial_ranged(pll_partition_t * partition, pll_operation_t * op,
unsigned int begin, unsigned int span)
{
#ifdef __AVX
auto attrib = PLL_ATTRIB_ARCH_AVX;
#else
auto attrib = PLL_ATTRIB_ARCH_SSE;
#endif
// make sure we actually skip the first <begin> entries ov the CLVs. Their size is
// number of states * number of rate cats
auto size = partition->states * partition->rate_cats;
auto skip_clv = begin * size;
// scalers are per site, so we just skip <begin>
// check if scalers exist, and if so shift them accordingly
unsigned int * parent_scaler = (op->parent_scaler_index == PLL_SCALE_BUFFER_NONE) ?
nullptr : partition->scale_buffer[op->parent_scaler_index] + begin;
unsigned int * child1_scaler = (op->child1_scaler_index == PLL_SCALE_BUFFER_NONE) ?
nullptr : partition->scale_buffer[op->child1_scaler_index] + begin;
unsigned int * child2_scaler = (op->child2_scaler_index == PLL_SCALE_BUFFER_NONE) ?
nullptr : partition->scale_buffer[op->child2_scaler_index] + begin;
pll_core_update_partial(partition->states,
span, // begin + span = first CLV entry not used in computation
partition->rate_cats,
partition->clv[op->parent_clv_index] + skip_clv,
parent_scaler,
partition->clv[op->child1_clv_index] + skip_clv,
partition->clv[op->child2_clv_index] + skip_clv,
partition->pmatrix[op->child1_matrix_index],
partition->pmatrix[op->child2_matrix_index],
child1_scaler,
child2_scaler,
attrib
);
// ranged computation leaves the CLV outside of the range as 0's. This is incorrect; it should be 1
// which is why we need to meset the values outside of the range to 1
// fill_n(partition->clv[op->parent_clv_index], skip_clv, 1.0);
// auto first_after_skip = (begin + span) * size;
// fill_n(partition->clv[op->parent_clv_index] + first_after_skip,
// (partition->sites * size) - first_after_skip, 1.0);
}
/* compute the negative lnL (score function for L-BFGS-B
* Original author: Diego Darriba <[email protected]>
* Used with permission.
* With modifications.
*/
double compute_negative_lnl_unrooted_ranged (void * p, double *x)
{
lk_set * params = (lk_set *) p;
pll_partition_t * partition = params->partition;
double score;
pll_update_prob_matrices (partition, 0,
params->matrix_indices,
x,
3);
update_partial_ranged (partition, params->operation, params->begin, params->span);
score = -1 * pll_compute_edge_loglikelihood (
partition,
params->tree->clv_index,
params->tree->scaler_index,
params->tree->back->clv_index,
params->tree->back->scaler_index,
params->tree->pmatrix_index,
0);
// params->begin,
// params->span);
return score;
}
/* optimize the 3 adjacent branches of the node (tree) simultaneously
* we assume that 'tree' is the virtual root and the CLVs of the nodes adjacent
* to the optimized branches are valid.
* This function returns the updated branch lengths in the tree structure and
* the likelihood score.
* Original author: Diego Darriba <[email protected]>
* Used with permission.
* With modifications.
*/
double optimize_triplet_lbfgsb_ranged (pll_partition_t * partition,
pll_utree_t * tree,
double factr,
double pgtol,
unsigned int begin,
unsigned int span)
{
/* L-BFGS-B parameters */
unsigned int num_variables = 3;
double score = 0;
double x[3], lower_bounds[3], upper_bounds[3];
int bound_type[3];
/* set x vector */
x[0] = tree->length;
x[1] = tree->next->length;
x[2] = tree->next->next->length;
/* set boundaries */
lower_bounds[0] = lower_bounds[1] = lower_bounds[2] = PLL_OPT_MIN_BRANCH_LEN;
upper_bounds[0] = upper_bounds[1] = upper_bounds[2] = PLL_OPT_MAX_BRANCH_LEN;
bound_type[0] = bound_type[1] = bound_type[2] = PLL_LBFGSB_BOUND_BOTH;
/* set operation for updating the CLV on the virtual root edge */
pll_operation_t op;
op.child1_clv_index = tree->next->back->clv_index;
op.child1_matrix_index = tree->next->back->pmatrix_index;
op.child1_scaler_index = tree->next->back->scaler_index;
op.child2_clv_index = tree->next->next->back->clv_index;
op.child2_matrix_index = tree->next->next->back->pmatrix_index;
op.child2_scaler_index = tree->next->next->back->scaler_index;
op.parent_clv_index = tree->clv_index;
op.parent_scaler_index = tree->scaler_index;
/* set likelihood parameters */
lk_set params;
params.partition = partition;
params.tree = tree;
params.matrix_indices[0] = tree->pmatrix_index;
params.matrix_indices[1] = tree->next->pmatrix_index;
params.matrix_indices[2] = tree->next->next->pmatrix_index;
params.operation = &op;
params.begin = begin;
params.span = span;
/* optimize branches */
score = pll_minimize_lbfgsb (x, lower_bounds, upper_bounds, bound_type,
num_variables, factr, pgtol, ¶ms,
compute_negative_lnl_unrooted_ranged);
/* set lengths back to the tree structure */
tree->length = tree->back->length = x[0];
tree->next->length = tree->next->back->length = x[1];
tree->next->next->length = tree->next->next->back->length = x[2];
return score;
}
double optimize_branch_triplet_ranged(pll_partition_t * partition, pll_utree_t * tree, Range range)
{
// compute logl once to give us a logl starting point
auto logl = -1* optimize_triplet_lbfgsb_ranged (partition, tree, 1e7, OPT_PARAM_EPSILON,
range.begin, range.span);
auto cur_logl = -numeric_limits<double>::infinity();
while (fabs (cur_logl - logl) > OPT_EPSILON)
{
logl = cur_logl;
cur_logl = -1* optimize_triplet_lbfgsb_ranged (partition, tree, 1e7, OPT_PARAM_EPSILON,
range.begin, range.span);
}
return cur_logl;
}
void traverse_update_partials(pll_utree_t * tree, pll_partition_t * partition,
pll_utree_t ** travbuffer, double * branch_lengths, unsigned int * matrix_indices,
pll_operation_t * operations)
{
unsigned int num_matrices, num_ops;
/* perform a full traversal*/
assert(tree->next != nullptr);
unsigned int traversal_size;
// TODO this only needs to be done once, outside of this func. pass traversal size also
// however this is practically nonexistent impact compared to clv comp
pll_utree_traverse(tree, cb_full_traversal, travbuffer, &traversal_size);
/* given the computed traversal descriptor, generate the operations
structure, and the corresponding probability matrix indices that
may need recomputing */
pll_utree_create_operations(travbuffer,
traversal_size,
branch_lengths,
matrix_indices,
operations,
&num_matrices,
&num_ops);
pll_update_prob_matrices(partition,
0, // use model 0
matrix_indices,// matrices to update
branch_lengths,
num_matrices); // how many should be updated
/* use the operations array to compute all num_ops inner CLVs. Operations
will be carried out sequentially starting from operation 0 towrds num_ops-1 */
pll_update_partials(partition, operations, num_ops);
}
double optimize_branch_lengths(pll_utree_t * tree, pll_partition_t * partition, pll_optimize_options_t& params,
pll_utree_t ** travbuffer, double cur_logl, double lnl_monitor, int* smoothings)
{
if (!tree->next)
tree = tree->back;
traverse_update_partials(tree, partition, travbuffer, params.lk_params.branch_lengths,
params.lk_params.matrix_indices, params.lk_params.operations);
pll_errno = 0; // hotfix
cur_logl = -1 * pll_optimize_branch_lengths_iterative(
partition, tree, 0, 0,
OPT_PARAM_EPSILON, *smoothings++, 1); // last param = 1 means branch lengths are iteratively
// updated during the call
if (cur_logl+1e-6 < lnl_monitor)
throw runtime_error{string("cur_logl < lnl_monitor: ") + to_string(cur_logl) + string(" : ")
+ to_string(lnl_monitor)};
// reupdate the indices as they may have changed
params.lk_params.where.unrooted_t.parent_clv_index = tree->clv_index;
params.lk_params.where.unrooted_t.parent_scaler_index =
tree->scaler_index;
params.lk_params.where.unrooted_t.child_clv_index = tree->back->clv_index;
params.lk_params.where.unrooted_t.child_scaler_index =
tree->back->scaler_index;
params.lk_params.where.unrooted_t.edge_pmatrix_index =
tree->pmatrix_index;
return cur_logl;
}
void optimize(Model& model, pll_utree_t * tree, pll_partition_t * partition,
const Tree_Numbers& nums, const bool opt_branches, const bool opt_model)
{
if (!opt_branches && !opt_model)
return;
if (opt_branches)
set_branch_length(tree, DEFAULT_BRANCH_LENGTH);
auto symmetries = (&(model.symmetries())[0]);
// sadly we explicitly need these buffers here and in the params structure
vector<pll_utree_t*> travbuffer(nums.nodes);
vector<double> branch_lengths(nums.branches);
vector<unsigned int> matrix_indices(nums.branches);
vector<pll_operation_t> operations(nums.nodes);
traverse_update_partials(tree, partition, &travbuffer[0], &branch_lengths[0],
&matrix_indices[0], &operations[0]);
// compute logl once to give us a logl starting point
auto logl = pll_compute_edge_loglikelihood (partition, tree->clv_index,
tree->scaler_index,
tree->back->clv_index,
tree->back->scaler_index,
tree->pmatrix_index, 0);
double cur_logl = -numeric_limits<double>::infinity();
int smoothings = 1;
double lnl_monitor = logl;
// set up high level options structure
pll_optimize_options_t params;
params.lk_params.partition = partition;
params.lk_params.operations = &operations[0];
params.lk_params.branch_lengths = &branch_lengths[0];
params.lk_params.matrix_indices = &matrix_indices[0];
params.lk_params.alpha_value = model.alpha();
params.lk_params.freqs_index = 0;
params.lk_params.rooted = 0;
params.lk_params.where.unrooted_t.parent_clv_index = tree->clv_index;
params.lk_params.where.unrooted_t.parent_scaler_index = tree->scaler_index;
params.lk_params.where.unrooted_t.child_clv_index = tree->back->clv_index;
params.lk_params.where.unrooted_t.child_scaler_index =
tree->back->scaler_index;
params.lk_params.where.unrooted_t.edge_pmatrix_index = tree->pmatrix_index;
/* optimization parameters */
params.params_index = 0;
params.mixture_index = 0;
params.subst_params_symmetries = symmetries;
params.factr = 1e7;
params.pgtol = OPT_PARAM_EPSILON;
// double xmin;
// double xguess;
// double xmax;
while (fabs (cur_logl - logl) > OPT_EPSILON)
{
logl = cur_logl;
if (opt_model)
{
params.which_parameters = PLL_PARAMETER_ALPHA;
// pll_optimize_parameters_brent_ranged(¶ms, xmin, xguess, xmax);
pll_optimize_parameters_brent(¶ms);
params.which_parameters = PLL_PARAMETER_SUBST_RATES;
pll_optimize_parameters_lbfgsb(¶ms);
// params.which_parameters = PLL_PARAMETER_FREQUENCIES;
// pll_optimize_parameters_lbfgsb(¶ms);
params.which_parameters = PLL_PARAMETER_PINV;
// cur_logl = -1 * pll_optimize_parameters_brent_ranged(¶ms, xmin, xguess, xmax);
cur_logl = -1 * pll_optimize_parameters_brent(¶ms);
}
if (opt_branches)
cur_logl = optimize_branch_lengths(tree,
partition, params, &travbuffer[0], cur_logl, lnl_monitor, &smoothings);
}
if (opt_model)
{
// update epa model object as well
model.alpha(params.lk_params.alpha_value);
model.substitution_rates(partition->subst_params[0], 6);
model.base_frequencies(partition->frequencies[params.params_index], partition->states);
}
}
void compute_and_set_empirical_frequencies(pll_partition_t * partition, Model& model)
{
double * empirical_freqs = pll_compute_empirical_frequencies (partition);
pll_set_frequencies (partition, 0, 0, empirical_freqs);
model.base_frequencies(partition->frequencies[0], partition->states);
free (empirical_freqs);
}
<commit_msg>refactored optimization, unter anderem changed partial init for the ranged case to only be done once (CLV to 1.0 outside range)<commit_after>#include "optimize.hpp"
#include <vector>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <stdexcept>
#include <limits>
#include <algorithm>
#include "pll_util.hpp"
#include "constants.hpp"
using namespace std;
/* Update a single partial likelihood vector (CLV) based on a range. Requires the
CLV to be appropriately initialized (0.0 within the range, 1.0 without)*/
static void update_partial_ranged(pll_partition_t * partition, pll_operation_t * op,
unsigned int begin, unsigned int span)
{
// quick probe to check if properly initialized
if (begin > 0)
assert(partition->clv[op->parent_clv_index][0] != 0.0);
#ifdef __AVX
auto attrib = PLL_ATTRIB_ARCH_AVX;
#else
auto attrib = PLL_ATTRIB_ARCH_SSE;
#endif
// make sure we actually skip the first <begin> entries ov the CLVs. Their size is
// number of states * number of rate cats
auto size = partition->states * partition->rate_cats;
auto skip_clv = begin * size;
// scalers are per site, so we just skip <begin>
// check if scalers exist, and if so shift them accordingly
unsigned int * parent_scaler = (op->parent_scaler_index == PLL_SCALE_BUFFER_NONE) ?
nullptr : partition->scale_buffer[op->parent_scaler_index] + begin;
unsigned int * child1_scaler = (op->child1_scaler_index == PLL_SCALE_BUFFER_NONE) ?
nullptr : partition->scale_buffer[op->child1_scaler_index] + begin;
unsigned int * child2_scaler = (op->child2_scaler_index == PLL_SCALE_BUFFER_NONE) ?
nullptr : partition->scale_buffer[op->child2_scaler_index] + begin;
pll_core_update_partial(partition->states,
span, // begin + span = first CLV entry not used in computation
partition->rate_cats,
partition->clv[op->parent_clv_index] + skip_clv,
parent_scaler,
partition->clv[op->child1_clv_index] + skip_clv,
partition->clv[op->child2_clv_index] + skip_clv,
partition->pmatrix[op->child1_matrix_index],
partition->pmatrix[op->child2_matrix_index],
child1_scaler,
child2_scaler,
attrib
);
}
/* compute the negative lnL (score function for L-BFGS-B
* Original author: Diego Darriba <[email protected]>
* Used with permission.
* With modifications.
*/
static double compute_negative_lnl_unrooted_ranged (void * p, double *x)
{
lk_set * params = (lk_set *) p;
pll_partition_t * partition = params->partition;
pll_update_prob_matrices (partition, 0,
params->matrix_indices,
x,
3);
update_partial_ranged (partition, params->operation, params->begin, params->span);
return -1 * pll_compute_edge_loglikelihood (
partition,
params->tree->clv_index,
params->tree->scaler_index,
params->tree->back->clv_index,
params->tree->back->scaler_index,
params->tree->pmatrix_index,
0);
}
/* optimize the 3 adjacent branches of the node (tree) simultaneously
* we assume that 'tree' is the virtual root and the CLVs of the nodes adjacent
* to the optimized branches are valid.
* This function returns the updated branch lengths in the tree structure and
* the likelihood score.
* Original author: Diego Darriba <[email protected]>
* Used with permission.
* With modifications.
*/
static double optimize_triplet_lbfgsb_ranged (pll_partition_t * partition,
pll_utree_t * tree,
double factr,
double pgtol,
unsigned int begin,
unsigned int span)
{
/* L-BFGS-B parameters */
unsigned int num_variables = 3;
double score = 0;
double x[3], lower_bounds[3], upper_bounds[3];
int bound_type[3];
/* set x vector */
x[0] = tree->length;
x[1] = tree->next->length;
x[2] = tree->next->next->length;
/* set boundaries */
lower_bounds[0] = lower_bounds[1] = lower_bounds[2] = PLL_OPT_MIN_BRANCH_LEN;
upper_bounds[0] = upper_bounds[1] = upper_bounds[2] = PLL_OPT_MAX_BRANCH_LEN;
bound_type[0] = bound_type[1] = bound_type[2] = PLL_LBFGSB_BOUND_BOTH;
/* set operation for updating the CLV on the virtual root edge */
pll_operation_t op;
op.child1_clv_index = tree->next->back->clv_index;
op.child1_matrix_index = tree->next->back->pmatrix_index;
op.child1_scaler_index = tree->next->back->scaler_index;
op.child2_clv_index = tree->next->next->back->clv_index;
op.child2_matrix_index = tree->next->next->back->pmatrix_index;
op.child2_scaler_index = tree->next->next->back->scaler_index;
op.parent_clv_index = tree->clv_index;
op.parent_scaler_index = tree->scaler_index;
/* set likelihood parameters */
lk_set params;
params.partition = partition;
params.tree = tree;
params.matrix_indices[0] = tree->pmatrix_index;
params.matrix_indices[1] = tree->next->pmatrix_index;
params.matrix_indices[2] = tree->next->next->pmatrix_index;
params.operation = &op;
params.begin = begin;
params.span = span;
/* optimize branches */
score = pll_minimize_lbfgsb (x, lower_bounds, upper_bounds, bound_type,
num_variables, factr, pgtol, ¶ms,
compute_negative_lnl_unrooted_ranged);
/* set lengths back to the tree structure */
tree->length = tree->back->length = x[0];
tree->next->length = tree->next->back->length = x[1];
tree->next->next->length = tree->next->next->back->length = x[2];
return score;
}
void fill_without(pll_partition_t * partition, unsigned int clv_index, Range& range, double value)
{
auto size = partition->states * partition->rate_cats;
auto skip_clv = range.begin * size;
auto clv = partition->clv[clv_index];
fill_n(clv, skip_clv, value);
auto first_after_skip = (range.begin + range.span) * size;
fill_n(clv + first_after_skip,
(partition->sites * size) - first_after_skip, value);
}
double optimize_branch_triplet_ranged(pll_partition_t * partition, pll_utree_t * tree, Range range)
{
// fill the partial's non-valid regions with one
fill_without(partition, tree->clv_index, range, 1.0);
// compute logl once to give us a logl starting point
auto logl = -1* optimize_triplet_lbfgsb_ranged (partition, tree, 1e7, OPT_PARAM_EPSILON,
range.begin, range.span);
auto cur_logl = -numeric_limits<double>::infinity();
while (fabs (cur_logl - logl) > OPT_EPSILON)
{
logl = cur_logl;
cur_logl = -1* optimize_triplet_lbfgsb_ranged (partition, tree, 1e7, OPT_PARAM_EPSILON,
range.begin, range.span);
}
return cur_logl;
}
static void traverse_update_partials(pll_utree_t * tree, pll_partition_t * partition,
pll_utree_t ** travbuffer, double * branch_lengths, unsigned int * matrix_indices,
pll_operation_t * operations)
{
unsigned int num_matrices, num_ops;
/* perform a full traversal*/
assert(tree->next != nullptr);
unsigned int traversal_size;
// TODO this only needs to be done once, outside of this func. pass traversal size also
// however this is practically nonexistent impact compared to clv comp
pll_utree_traverse(tree, cb_full_traversal, travbuffer, &traversal_size);
/* given the computed traversal descriptor, generate the operations
structure, and the corresponding probability matrix indices that
may need recomputing */
pll_utree_create_operations(travbuffer,
traversal_size,
branch_lengths,
matrix_indices,
operations,
&num_matrices,
&num_ops);
pll_update_prob_matrices(partition,
0, // use model 0
matrix_indices,// matrices to update
branch_lengths,
num_matrices); // how many should be updated
/* use the operations array to compute all num_ops inner CLVs. Operations
will be carried out sequentially starting from operation 0 towrds num_ops-1 */
pll_update_partials(partition, operations, num_ops);
}
double optimize_branch_lengths(pll_utree_t * tree, pll_partition_t * partition, pll_optimize_options_t& params,
pll_utree_t ** travbuffer, double cur_logl, double lnl_monitor, int* smoothings)
{
if (!tree->next)
tree = tree->back;
traverse_update_partials(tree, partition, travbuffer, params.lk_params.branch_lengths,
params.lk_params.matrix_indices, params.lk_params.operations);
pll_errno = 0; // hotfix
cur_logl = -1 * pll_optimize_branch_lengths_iterative(
partition, tree, 0, 0,
OPT_PARAM_EPSILON, *smoothings++, 1); // last param = 1 means branch lengths are iteratively
// updated during the call
if (cur_logl+1e-6 < lnl_monitor)
throw runtime_error{string("cur_logl < lnl_monitor: ") + to_string(cur_logl) + string(" : ")
+ to_string(lnl_monitor)};
// reupdate the indices as they may have changed
params.lk_params.where.unrooted_t.parent_clv_index = tree->clv_index;
params.lk_params.where.unrooted_t.parent_scaler_index =
tree->scaler_index;
params.lk_params.where.unrooted_t.child_clv_index = tree->back->clv_index;
params.lk_params.where.unrooted_t.child_scaler_index =
tree->back->scaler_index;
params.lk_params.where.unrooted_t.edge_pmatrix_index =
tree->pmatrix_index;
return cur_logl;
}
void optimize(Model& model, pll_utree_t * tree, pll_partition_t * partition,
const Tree_Numbers& nums, const bool opt_branches, const bool opt_model)
{
if (!opt_branches && !opt_model)
return;
if (opt_branches)
set_branch_length(tree, DEFAULT_BRANCH_LENGTH);
auto symmetries = (&(model.symmetries())[0]);
// sadly we explicitly need these buffers here and in the params structure
vector<pll_utree_t*> travbuffer(nums.nodes);
vector<double> branch_lengths(nums.branches);
vector<unsigned int> matrix_indices(nums.branches);
vector<pll_operation_t> operations(nums.nodes);
traverse_update_partials(tree, partition, &travbuffer[0], &branch_lengths[0],
&matrix_indices[0], &operations[0]);
// compute logl once to give us a logl starting point
auto logl = pll_compute_edge_loglikelihood (partition, tree->clv_index,
tree->scaler_index,
tree->back->clv_index,
tree->back->scaler_index,
tree->pmatrix_index, 0);
double cur_logl = -numeric_limits<double>::infinity();
int smoothings = 1;
double lnl_monitor = logl;
// set up high level options structure
pll_optimize_options_t params;
params.lk_params.partition = partition;
params.lk_params.operations = &operations[0];
params.lk_params.branch_lengths = &branch_lengths[0];
params.lk_params.matrix_indices = &matrix_indices[0];
params.lk_params.alpha_value = model.alpha();
params.lk_params.freqs_index = 0;
params.lk_params.rooted = 0;
params.lk_params.where.unrooted_t.parent_clv_index = tree->clv_index;
params.lk_params.where.unrooted_t.parent_scaler_index = tree->scaler_index;
params.lk_params.where.unrooted_t.child_clv_index = tree->back->clv_index;
params.lk_params.where.unrooted_t.child_scaler_index =
tree->back->scaler_index;
params.lk_params.where.unrooted_t.edge_pmatrix_index = tree->pmatrix_index;
/* optimization parameters */
params.params_index = 0;
params.mixture_index = 0;
params.subst_params_symmetries = symmetries;
params.factr = 1e7;
params.pgtol = OPT_PARAM_EPSILON;
// double xmin;
// double xguess;
// double xmax;
while (fabs (cur_logl - logl) > OPT_EPSILON)
{
logl = cur_logl;
if (opt_model)
{
params.which_parameters = PLL_PARAMETER_ALPHA;
// pll_optimize_parameters_brent_ranged(¶ms, xmin, xguess, xmax);
pll_optimize_parameters_brent(¶ms);
params.which_parameters = PLL_PARAMETER_SUBST_RATES;
pll_optimize_parameters_lbfgsb(¶ms);
// params.which_parameters = PLL_PARAMETER_FREQUENCIES;
// pll_optimize_parameters_lbfgsb(¶ms);
params.which_parameters = PLL_PARAMETER_PINV;
// cur_logl = -1 * pll_optimize_parameters_brent_ranged(¶ms, xmin, xguess, xmax);
cur_logl = -1 * pll_optimize_parameters_brent(¶ms);
}
if (opt_branches)
cur_logl = optimize_branch_lengths(tree,
partition, params, &travbuffer[0], cur_logl, lnl_monitor, &smoothings);
}
if (opt_model)
{
// update epa model object as well
model.alpha(params.lk_params.alpha_value);
model.substitution_rates(partition->subst_params[0], 6);
model.base_frequencies(partition->frequencies[params.params_index], partition->states);
}
}
void compute_and_set_empirical_frequencies(pll_partition_t * partition, Model& model)
{
double * empirical_freqs = pll_compute_empirical_frequencies (partition);
pll_set_frequencies (partition, 0, 0, empirical_freqs);
model.base_frequencies(partition->frequencies[0], partition->states);
free (empirical_freqs);
}
<|endoftext|>
|
<commit_before><commit_msg>another fix for friend track extractions<commit_after><|endoftext|>
|
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" Target size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" Standard Star size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" Sky Fiber size %d \n",M.size());
F.Ngal = M.size();
assign_priority_class(M);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
print_time(time,"# ... took :");
// fiber positioners
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F);
pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..]
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
// Make a plan ----------------------------------------------------
print_time(t,"# Start assignment at : ");
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,-1);
int inv_count=0;
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);//suborder[jused] is jused-th used plate
not_done=false;
A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
inv_count++;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates actually used %d \n",F.NUsedplate);
for(int i=0;i<F.NUsedplate;i++)printf(" jused %d j %d\n",i,A.suborder[i]);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<3; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(j,M,P,pp,F,A);
}
// Results -------------------------------------------------------*/
std::vector <int> total_used_by_class(M.priority_list.size(),0);
int total_used_SS=0;
int total_used_SF=0;
for (int jused=0;jused<F.NUsedplate;++jused){
std::vector <int> used_by_class(M.priority_list.size(),0);
int used_SS=0;
int used_SF=0;
int j=A.suborder[jused];
for(int k=0;k<F.Nfiber;++k){
int g=A.TF[j][k];
if(g!=-1){
if(M[g].SS){
total_used_SS++;
used_SS++;
}
else if(M[g].SF){
used_SF++;
total_used_SF++;
}
else{
used_by_class[M[g].priority_class]++;
total_used_by_class[M[g].priority_class]++;
}
}
}
printf(" plate jused %5d j %5d SS %4d SF %4d",jused,j,used_SS,used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,used_by_class[pr]);
}
printf("\n");
}
printf(" Totals SS %4d SF %4d",total_used_SS,total_used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,total_used_by_class[pr]);
}
printf("\n");
if (F.PrintAscii) for (int j=0; j<F.Nplate; j++){
write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int j=0; j<F.Nplate; j++){
fa_write(j,F.outDir,M,P,pp,F,A); // Write output
}
/*
display_results("doc/figs/",G,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
*/
print_time(t,"# Finished !... in");
return(0);
}
<commit_msg>jused only in ascii write<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" Target size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" Standard Star size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" Sky Fiber size %d \n",M.size());
F.Ngal = M.size();
assign_priority_class(M);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
print_time(time,"# ... took :");
// fiber positioners
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F);
pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..]
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
// Make a plan ----------------------------------------------------
print_time(t,"# Start assignment at : ");
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,-1);
int inv_count=0;
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);//suborder[jused] is jused-th used plate
not_done=false;
A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
inv_count++;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates actually used %d \n",F.NUsedplate);
for(int i=0;i<F.NUsedplate;i++)printf(" jused %d j %d\n",i,A.suborder[i]);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<3; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(j,M,P,pp,F,A);
}
// Results -------------------------------------------------------*/
std::vector <int> total_used_by_class(M.priority_list.size(),0);
int total_used_SS=0;
int total_used_SF=0;
for (int jused=0;jused<F.NUsedplate;++jused){
std::vector <int> used_by_class(M.priority_list.size(),0);
int used_SS=0;
int used_SF=0;
int j=A.suborder[jused];
for(int k=0;k<F.Nfiber;++k){
int g=A.TF[j][k];
if(g!=-1){
if(M[g].SS){
total_used_SS++;
used_SS++;
}
else if(M[g].SF){
used_SF++;
total_used_SF++;
}
else{
used_by_class[M[g].priority_class]++;
total_used_by_class[M[g].priority_class]++;
}
}
}
printf(" plate jused %5d j %5d SS %4d SF %4d",jused,j,used_SS,used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,used_by_class[pr]);
}
printf("\n");
}
printf(" Totals SS %4d SF %4d",total_used_SS,total_used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,total_used_by_class[pr]);
}
printf("\n");
if (F.PrintAscii) for (int jused=0; j<F.NUsedplate; j++){
int j=A.suborder[jused];
write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int j=0; j<F.Nplate; j++){
fa_write(j,F.outDir,M,P,pp,F,A); // Write output
}
/*
display_results("doc/figs/",G,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
*/
print_time(t,"# Finished !... in");
return(0);
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
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/>.
*/
//#define NDEBUG
#include "radioInterface.h"
#include <Logger.h>
GSM::Time VectorQueue::nextTime() const
{
GSM::Time retVal;
ScopedLock lock(mLock);
while (mQ.size()==0) mWriteSignal.wait(mLock);
return mQ.top()->time();
}
radioVector* VectorQueue::getStaleBurst(const GSM::Time& targTime)
{
ScopedLock lock(mLock);
if ((mQ.size()==0)) {
return NULL;
}
if (mQ.top()->time() < targTime) {
radioVector* retVal = mQ.top();
mQ.pop();
return retVal;
}
return NULL;
}
radioVector* VectorQueue::getCurrentBurst(const GSM::Time& targTime)
{
ScopedLock lock(mLock);
if ((mQ.size()==0)) {
return NULL;
}
if (mQ.top()->time() == targTime) {
radioVector* retVal = mQ.top();
mQ.pop();
return retVal;
}
return NULL;
}
RadioInterface::RadioInterface(RadioDevice *wRadio,
int wReceiveOffset,
int wRadioOversampling,
int wTransceiverOversampling,
GSM::Time wStartTime)
{
underrun = false;
sendCursor = 0;
rcvCursor = 0;
mOn = false;
mRadio = wRadio;
receiveOffset = wReceiveOffset;
samplesPerSymbol = wRadioOversampling;
mClock.set(wStartTime);
loadTest = false;
powerScaling = 1.0;
}
RadioInterface::~RadioInterface(void) {
if (rcvBuffer!=NULL) delete rcvBuffer;
//mReceiveFIFO.clear();
}
double RadioInterface::fullScaleInputValue(void) {
return mRadio->fullScaleInputValue();
}
double RadioInterface::fullScaleOutputValue(void) {
return mRadio->fullScaleOutputValue();
}
void RadioInterface::setPowerAttenuation(double atten)
{
double rfAtten, digAtten;
rfAtten = mRadio->setTxGain(mRadio->maxTxGain() - atten);
digAtten = atten - rfAtten;
if (digAtten < 1.0)
powerScaling = 1.0;
else
powerScaling = 1.0/sqrt(pow(10, (digAtten/10.0)));
}
short *RadioInterface::radioifyVector(signalVector &wVector,
short *retVector,
float scale,
bool zeroOut)
{
signalVector::iterator itr = wVector.begin();
short *shortItr = retVector;
if (zeroOut) {
while (itr < wVector.end()) {
*shortItr++ = 0;
*shortItr++ = 0;
itr++;
}
} else if (scale != 1.0) {
while (itr < wVector.end()) {
*shortItr++ = (short) (itr->real() * scale);
*shortItr++ = (short) (itr->imag() * scale);
itr++;
}
} else {
while (itr < wVector.end()) {
*shortItr++ = (short) (itr->real());
*shortItr++ = (short) (itr->imag());
itr++;
}
}
return retVector;
}
void RadioInterface::unRadioifyVector(short *shortVector, signalVector& newVector)
{
signalVector::iterator itr = newVector.begin();
short *shortItr = shortVector;
while (itr < newVector.end()) {
*itr++ = Complex<float>(*shortItr,*(shortItr+1));
//LOG(DEBUG) << (*(itr-1));
shortItr += 2;
}
}
bool started = false;
void RadioInterface::pushBuffer(void) {
if (sendCursor < 2*INCHUNK*samplesPerSymbol) return;
// send resampleVector
int samplesWritten = mRadio->writeSamples(sendBuffer,
INCHUNK*samplesPerSymbol,
&underrun,
writeTimestamp);
//LOG(DEBUG) << "writeTimestamp: " << writeTimestamp << ", samplesWritten: " << samplesWritten;
writeTimestamp += (TIMESTAMP) samplesWritten;
if (sendCursor > 2*samplesWritten)
memcpy(sendBuffer,sendBuffer+samplesWritten*2,sizeof(short)*2*(sendCursor-2*samplesWritten));
sendCursor = sendCursor - 2*samplesWritten;
}
void RadioInterface::pullBuffer(void)
{
bool localUnderrun;
// receive receiveVector
short* shortVector = rcvBuffer+rcvCursor;
//LOG(DEBUG) << "Reading USRP samples at timestamp " << readTimestamp;
int samplesRead = mRadio->readSamples(shortVector,OUTCHUNK*samplesPerSymbol,&overrun,readTimestamp,&localUnderrun);
underrun |= localUnderrun;
readTimestamp += (TIMESTAMP) samplesRead;
while (samplesRead < OUTCHUNK*samplesPerSymbol) {
int oldSamplesRead = samplesRead;
samplesRead += mRadio->readSamples(shortVector+2*samplesRead,
OUTCHUNK*samplesPerSymbol-samplesRead,
&overrun,
readTimestamp,
&localUnderrun);
underrun |= localUnderrun;
readTimestamp += (TIMESTAMP) (samplesRead - oldSamplesRead);
}
//LOG(DEBUG) << "samplesRead " << samplesRead;
rcvCursor += samplesRead*2;
}
bool RadioInterface::tuneTx(double freq)
{
return mRadio->setTxFreq(freq);
}
bool RadioInterface::tuneRx(double freq)
{
return mRadio->setRxFreq(freq);
}
void RadioInterface::start()
{
LOG(INFO) << "starting radio interface...";
mAlignRadioServiceLoopThread.start((void * (*)(void*))AlignRadioServiceLoopAdapter,
(void*)this);
writeTimestamp = mRadio->initialWriteTimestamp();
readTimestamp = mRadio->initialReadTimestamp();
mRadio->start();
LOG(DEBUG) << "Radio started";
mRadio->updateAlignment(writeTimestamp-10000);
mRadio->updateAlignment(writeTimestamp-10000);
sendBuffer = new short[2*2*INCHUNK*samplesPerSymbol];
rcvBuffer = new short[2*2*OUTCHUNK*samplesPerSymbol];
mOn = true;
}
void *AlignRadioServiceLoopAdapter(RadioInterface *radioInterface)
{
while (1) {
radioInterface->alignRadio();
pthread_testcancel();
}
return NULL;
}
void RadioInterface::alignRadio() {
sleep(60);
mRadio->updateAlignment(writeTimestamp+ (TIMESTAMP) 10000);
}
void RadioInterface::driveTransmitRadio(signalVector &radioBurst, bool zeroBurst) {
if (!mOn) return;
radioifyVector(radioBurst, sendBuffer+sendCursor, powerScaling, zeroBurst);
sendCursor += (radioBurst.size()*2);
pushBuffer();
}
void RadioInterface::driveReceiveRadio() {
if (!mOn) return;
if (mReceiveFIFO.size() > 8) return;
pullBuffer();
GSM::Time rcvClock = mClock.get();
rcvClock.decTN(receiveOffset);
unsigned tN = rcvClock.TN();
int rcvSz = rcvCursor/2;
int readSz = 0;
const int symbolsPerSlot = gSlotLen + 8;
// while there's enough data in receive buffer, form received
// GSM bursts and pass up to Transceiver
// Using the 157-156-156-156 symbols per timeslot format.
while (rcvSz > (symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol) {
signalVector rxVector((symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol);
unRadioifyVector(rcvBuffer+readSz*2,rxVector);
GSM::Time tmpTime = rcvClock;
if (rcvClock.FN() >= 0) {
//LOG(DEBUG) << "FN: " << rcvClock.FN();
radioVector *rxBurst = NULL;
if (!loadTest)
rxBurst = new radioVector(rxVector,tmpTime);
else {
if (tN % 4 == 0)
rxBurst = new radioVector(*finalVec9,tmpTime);
else
rxBurst = new radioVector(*finalVec,tmpTime);
}
mReceiveFIFO.put(rxBurst);
}
mClock.incTN();
rcvClock.incTN();
//if (mReceiveFIFO.size() >= 16) mReceiveFIFO.wait(8);
//LOG(DEBUG) << "receiveFIFO: wrote radio vector at time: " << mClock.get() << ", new size: " << mReceiveFIFO.size() ;
readSz += (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;
rcvSz -= (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;
tN = rcvClock.TN();
}
if (readSz > 0) {
memcpy(rcvBuffer,rcvBuffer+2*readSz,sizeof(short)*2*(rcvCursor-readSz));
rcvCursor = rcvCursor-2*readSz;
}
}
<commit_msg>transceiver: fix bug in setting low-level attenuation<commit_after>/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
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/>.
*/
//#define NDEBUG
#include "radioInterface.h"
#include <Logger.h>
GSM::Time VectorQueue::nextTime() const
{
GSM::Time retVal;
ScopedLock lock(mLock);
while (mQ.size()==0) mWriteSignal.wait(mLock);
return mQ.top()->time();
}
radioVector* VectorQueue::getStaleBurst(const GSM::Time& targTime)
{
ScopedLock lock(mLock);
if ((mQ.size()==0)) {
return NULL;
}
if (mQ.top()->time() < targTime) {
radioVector* retVal = mQ.top();
mQ.pop();
return retVal;
}
return NULL;
}
radioVector* VectorQueue::getCurrentBurst(const GSM::Time& targTime)
{
ScopedLock lock(mLock);
if ((mQ.size()==0)) {
return NULL;
}
if (mQ.top()->time() == targTime) {
radioVector* retVal = mQ.top();
mQ.pop();
return retVal;
}
return NULL;
}
RadioInterface::RadioInterface(RadioDevice *wRadio,
int wReceiveOffset,
int wRadioOversampling,
int wTransceiverOversampling,
GSM::Time wStartTime)
{
underrun = false;
sendCursor = 0;
rcvCursor = 0;
mOn = false;
mRadio = wRadio;
receiveOffset = wReceiveOffset;
samplesPerSymbol = wRadioOversampling;
mClock.set(wStartTime);
loadTest = false;
powerScaling = 1.0;
}
RadioInterface::~RadioInterface(void) {
if (rcvBuffer!=NULL) delete rcvBuffer;
//mReceiveFIFO.clear();
}
double RadioInterface::fullScaleInputValue(void) {
return mRadio->fullScaleInputValue();
}
double RadioInterface::fullScaleOutputValue(void) {
return mRadio->fullScaleOutputValue();
}
void RadioInterface::setPowerAttenuation(double atten)
{
double rfGain, digAtten;
rfGain = mRadio->setTxGain(mRadio->maxTxGain() - atten);
digAtten = atten - mRadio->maxTxGain() + rfGain;
if (digAtten < 1.0)
powerScaling = 1.0;
else
powerScaling = 1.0/sqrt(pow(10, (digAtten/10.0)));
}
short *RadioInterface::radioifyVector(signalVector &wVector,
short *retVector,
float scale,
bool zeroOut)
{
signalVector::iterator itr = wVector.begin();
short *shortItr = retVector;
if (zeroOut) {
while (itr < wVector.end()) {
*shortItr++ = 0;
*shortItr++ = 0;
itr++;
}
} else if (scale != 1.0) {
while (itr < wVector.end()) {
*shortItr++ = (short) (itr->real() * scale);
*shortItr++ = (short) (itr->imag() * scale);
itr++;
}
} else {
while (itr < wVector.end()) {
*shortItr++ = (short) (itr->real());
*shortItr++ = (short) (itr->imag());
itr++;
}
}
return retVector;
}
void RadioInterface::unRadioifyVector(short *shortVector, signalVector& newVector)
{
signalVector::iterator itr = newVector.begin();
short *shortItr = shortVector;
while (itr < newVector.end()) {
*itr++ = Complex<float>(*shortItr,*(shortItr+1));
//LOG(DEBUG) << (*(itr-1));
shortItr += 2;
}
}
bool started = false;
void RadioInterface::pushBuffer(void) {
if (sendCursor < 2*INCHUNK*samplesPerSymbol) return;
// send resampleVector
int samplesWritten = mRadio->writeSamples(sendBuffer,
INCHUNK*samplesPerSymbol,
&underrun,
writeTimestamp);
//LOG(DEBUG) << "writeTimestamp: " << writeTimestamp << ", samplesWritten: " << samplesWritten;
writeTimestamp += (TIMESTAMP) samplesWritten;
if (sendCursor > 2*samplesWritten)
memcpy(sendBuffer,sendBuffer+samplesWritten*2,sizeof(short)*2*(sendCursor-2*samplesWritten));
sendCursor = sendCursor - 2*samplesWritten;
}
void RadioInterface::pullBuffer(void)
{
bool localUnderrun;
// receive receiveVector
short* shortVector = rcvBuffer+rcvCursor;
//LOG(DEBUG) << "Reading USRP samples at timestamp " << readTimestamp;
int samplesRead = mRadio->readSamples(shortVector,OUTCHUNK*samplesPerSymbol,&overrun,readTimestamp,&localUnderrun);
underrun |= localUnderrun;
readTimestamp += (TIMESTAMP) samplesRead;
while (samplesRead < OUTCHUNK*samplesPerSymbol) {
int oldSamplesRead = samplesRead;
samplesRead += mRadio->readSamples(shortVector+2*samplesRead,
OUTCHUNK*samplesPerSymbol-samplesRead,
&overrun,
readTimestamp,
&localUnderrun);
underrun |= localUnderrun;
readTimestamp += (TIMESTAMP) (samplesRead - oldSamplesRead);
}
//LOG(DEBUG) << "samplesRead " << samplesRead;
rcvCursor += samplesRead*2;
}
bool RadioInterface::tuneTx(double freq)
{
return mRadio->setTxFreq(freq);
}
bool RadioInterface::tuneRx(double freq)
{
return mRadio->setRxFreq(freq);
}
void RadioInterface::start()
{
LOG(INFO) << "starting radio interface...";
mAlignRadioServiceLoopThread.start((void * (*)(void*))AlignRadioServiceLoopAdapter,
(void*)this);
writeTimestamp = mRadio->initialWriteTimestamp();
readTimestamp = mRadio->initialReadTimestamp();
mRadio->start();
LOG(DEBUG) << "Radio started";
mRadio->updateAlignment(writeTimestamp-10000);
mRadio->updateAlignment(writeTimestamp-10000);
sendBuffer = new short[2*2*INCHUNK*samplesPerSymbol];
rcvBuffer = new short[2*2*OUTCHUNK*samplesPerSymbol];
mOn = true;
}
void *AlignRadioServiceLoopAdapter(RadioInterface *radioInterface)
{
while (1) {
radioInterface->alignRadio();
pthread_testcancel();
}
return NULL;
}
void RadioInterface::alignRadio() {
sleep(60);
mRadio->updateAlignment(writeTimestamp+ (TIMESTAMP) 10000);
}
void RadioInterface::driveTransmitRadio(signalVector &radioBurst, bool zeroBurst) {
if (!mOn) return;
radioifyVector(radioBurst, sendBuffer+sendCursor, powerScaling, zeroBurst);
sendCursor += (radioBurst.size()*2);
pushBuffer();
}
void RadioInterface::driveReceiveRadio() {
if (!mOn) return;
if (mReceiveFIFO.size() > 8) return;
pullBuffer();
GSM::Time rcvClock = mClock.get();
rcvClock.decTN(receiveOffset);
unsigned tN = rcvClock.TN();
int rcvSz = rcvCursor/2;
int readSz = 0;
const int symbolsPerSlot = gSlotLen + 8;
// while there's enough data in receive buffer, form received
// GSM bursts and pass up to Transceiver
// Using the 157-156-156-156 symbols per timeslot format.
while (rcvSz > (symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol) {
signalVector rxVector((symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol);
unRadioifyVector(rcvBuffer+readSz*2,rxVector);
GSM::Time tmpTime = rcvClock;
if (rcvClock.FN() >= 0) {
//LOG(DEBUG) << "FN: " << rcvClock.FN();
radioVector *rxBurst = NULL;
if (!loadTest)
rxBurst = new radioVector(rxVector,tmpTime);
else {
if (tN % 4 == 0)
rxBurst = new radioVector(*finalVec9,tmpTime);
else
rxBurst = new radioVector(*finalVec,tmpTime);
}
mReceiveFIFO.put(rxBurst);
}
mClock.incTN();
rcvClock.incTN();
//if (mReceiveFIFO.size() >= 16) mReceiveFIFO.wait(8);
//LOG(DEBUG) << "receiveFIFO: wrote radio vector at time: " << mClock.get() << ", new size: " << mReceiveFIFO.size() ;
readSz += (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;
rcvSz -= (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;
tN = rcvClock.TN();
}
if (readSz > 0) {
memcpy(rcvBuffer,rcvBuffer+2*readSz,sizeof(short)*2*(rcvCursor-readSz));
rcvCursor = rcvCursor-2*readSz;
}
}
<|endoftext|>
|
<commit_before>#ifndef MATLIB_PML_BCPM_H
#define MATLIB_PML_BCPM_H
#include "pml.hpp"
#include "pml_rand.hpp"
#include <algorithm>
namespace pml {
// ----------- POTENTIALS ----------- //
class Potential {
public:
explicit Potential(double log_c_) : log_c(log_c_) {}
public:
bool operator<(const Potential &other) const{
return this->log_c < other.log_c;
}
virtual Vector rand() const = 0;
virtual Vector mean() const = 0;
virtual void update(const Vector &obs) = 0;
public:
double log_c;
};
class DirichletPotential : public Potential {
public:
DirichletPotential(size_t K, double log_c_ = 0) : Potential(log_c_) {
alpha = Vector::ones(K);
}
DirichletPotential(const Vector& alpha_, double log_c_ = 0)
: Potential(log_c_), alpha(alpha_) {}
public:
void operator*=(const DirichletPotential &p){
*this = this->operator*(p);
}
DirichletPotential operator*(const DirichletPotential &p) const{
double delta = std::lgamma(sum(alpha)) - sum(lgamma(alpha)) +
std::lgamma(sum(p.alpha)) - sum(lgamma(p.alpha)) +
sum(lgamma(alpha + p.alpha-1)) -
std::lgamma(sum(alpha + p.alpha -1));
return DirichletPotential(alpha + p.alpha - 1,
log_c + p.log_c + delta);
}
void update(const Vector &obs) override{
double log_c = std::lgamma(sum(obs)+1) - std::lgamma(sum(obs+1));
this->operator*=(DirichletPotential(obs+1, log_c));
}
Vector rand() const override {
return dirichlet::rand(alpha);
}
Vector mean() const override {
return normalize(alpha);
}
public:
Vector alpha;
};
class GammaPotential : public Potential {
public:
GammaPotential(double a_ = 1, double b_ = 1, double log_c_ = 0)
: Potential(log_c_), a(a_), b(b_){}
public:
void operator*=(const GammaPotential &other){
*this = this->operator*(other);
}
GammaPotential operator*(const GammaPotential &other) const{
double delta = std::lgamma(a + other.a - 1)
- std::lgamma(a) - std::lgamma(other.a)
+ std::log(b + other.b)
+ a * std::log(b/(b + other.b))
+ other.a * std::log(other.b/(b + other.b));
return GammaPotential(a + other.a - 1,
b + other.b,
log_c + other.log_c + delta);
}
Vector rand() const override {
return gamma::rand(a, b, 1);
}
Vector mean() const override {
return Vector(1, a / b);
}
void update(const Vector &obs) override {
this->operator*=(GammaPotential(obs.first()+1, 1));
}
public:
double a;
double b;
};
// ----------- OBSERVATION MODELS ----------- //
struct PoissonRandom{
Vector operator()(const Vector ¶m) const {
return poisson::rand(param.first(), 1);
}
};
struct MultinomialRandom{
Vector operator()(const Vector ¶m) const {
return multinomial::rand(param, 100);
}
};
// ----------- MESSAGE----------- //
template <class P>
class Message {
public:
size_t size() const {
return components.size();
}
void add_component(const P &potential){
components.push_back(potential);
}
void add_component(const P &potential, double log_c){
components.push_back(potential);
components.back().log_c = log_c;
}
friend Message<P> operator*(const Message<P> &m1, const Message<P> &m2){
Message<P> msg;
for(auto &component1 : m1.components)
for(auto &component2 : m2.components)
msg.add_component(component1 * component2);
return msg;
}
void update(const Vector& obs) {
for(auto &component : components){
component.update(obs);
}
}
// Returns mean and cpp (Maybe renamed)
std::pair<Vector, double> evaluate(int N = 1){
Vector consts;
Matrix params;
for(auto &potential: components){
consts.append(potential.log_c);
params.appendColumn(potential.mean());
}
consts = normalizeExp(consts);
// Calculate mean
Vector mean = sumRows(transpose(transpose(params)*consts));
// Calculate cpp as the sum of last N probabilities
double cpp = 0;
for(int i=0; i < N; ++i)
cpp += consts(consts.size() - i - 1);
return {mean, cpp};
};
void prune(size_t max_components){
while(components.size() > max_components){
// Find mininum no-change element
auto iter = std::min_element(components.begin(), components.end()-1);
// Swap the last two elements to save the order of the change comp.
std::swap(*(components.end()-1), *(components.end()-2));
// Swap last element with the minimum compoment.
std::swap(*iter, components.back());
// Delete minimum component.
components.pop_back();
}
}
public:
std::vector<P> components;
};
// ----------- MODEL----------- //
template <class P, class Obs>
class Model{
public:
Model(const P &prior_, double p1_) : prior(prior_), p1(p1_){
log_p1 = std::log(p1);
log_p0 = std::log(1-p1);
}
public:
// returns "states" as first matrix and "obervations" as second
std::pair<Matrix, Matrix> generateData(size_t T){
Matrix states, obs;
Vector state = prior.rand();
for (size_t t=0; t<T; t++) {
if (t > 0 && uniform::rand() < p1) {
state = prior.rand();
}
states.appendColumn(state);
obs.appendColumn(observation(state));
}
return {states, obs};
}
Message<P> initialMessage(){
Message<P> message;
message.add_component(prior, log_p0);
message.add_component(prior, log_p1);
return message;
}
Message<P> predict(const Message<P> &prev){
Message<P> message = prev;
Vector consts;
for(auto &component : message.components){
consts.append(component.log_c);
component.log_c += log_p0;
}
message.add_component(prior, log_p1 + logSumExp(consts));
return message;
}
private:
P prior;
Obs observation;
double p1; // probability of change
double log_p1, log_p0;
};
template <class P, class Obs>
class ForwardBackward {
public:
ForwardBackward(const Model<P, Obs> &model_,
int lag_ = 0, int max_components_ = 100)
: model(model_), lag(lag_), max_components(max_components_) {}
public:
void oneStepForward(std::vector<Message<P>> &alpha, const Vector& obs) {
// predict step
if (alpha.size() == 0)
alpha.push_back(model.initialMessage());
else
alpha.push_back(model.predict(alpha.back()));
// update step
alpha.back().update(obs);
}
void oneStepBackward(std::vector<Message<P>> &beta, const Vector& obs) {
// predict step
if (beta.size()==0)
beta.push_back(model.initialMessage());
else
beta.push_back(model.predict(beta.back()));
// update step
beta.back().update(obs);
}
std::vector<Message<P>> forward(const Matrix& obs){
std::vector<Message<P>> alpha;
for (size_t i=0; i<obs.ncols(); i++) {
oneStepForward(alpha, obs.getColumn(i));
alpha.back().prune(max_components);
}
return alpha;
}
std::vector<Message<P>> backward(const Matrix& obs){
std::vector<Message<P>> beta;
for (size_t i=obs.ncols(); i>0; i--) {
oneStepBackward(beta, obs.getColumn(i-1));
beta.back().prune(max_components);
}
// We calculated Beta backwards, we need to reverse the list.
std::reverse(beta.begin(), beta.end());
return beta;
}
// Returns mean and cpp
std::pair<Matrix, Vector> filtering(const Matrix& obs) {
// Run forward
auto alpha = forward(obs);
// Calculate mean and cpp
Matrix mean;
Vector cpp;
for(auto &message : alpha){
auto result = message.evaluate();
mean.appendColumn(result.first);
cpp.append(result.second);
}
return {mean, cpp};
}
// Returns mean and cpp
std::pair<Matrix, Vector> smoothing(const Matrix& obs) {
Matrix mean;
Vector cpp;
// Run Forward and Backward
auto alpha = forward(obs);
auto beta = backward(obs);
// Calculate Smoothed density
Message<P> gamma;
for(size_t i=0; i < obs.ncols(); ++i) {
gamma = alpha[i] * beta[i];
auto result = gamma.evaluate(beta[i].size());
mean.appendColumn(result.first);
cpp.append(result.second);
}
return {mean, cpp};
}
// a.k.a. fixed-lag smoothing
std::pair<Matrix, Vector> online_smoothing(const Matrix& obs) {
if( lag == 0){
return filtering(obs);
}
Matrix mean;
Vector cpp;
std::vector<Message<P>> alpha = forward(obs);
Message<P> gamma;
for (size_t t=0; t<obs.ncols()-lag+1; t++) {
auto beta = backward(obs.getColumns(Range(t, t+lag)));
gamma = alpha[t] * beta[0];
auto result = gamma.evaluate(beta[0].size());
mean.appendColumn(result.first);
cpp.append(result.second);
// if T-lag is reached, smooth the rest
if(t == obs.ncols()-lag){
for(int i = 1; i < lag; ++i){
gamma = alpha[t+i] * beta[i];
auto result = gamma.evaluate(beta[i].size());
mean.appendColumn(result.first);
cpp.append(result.second);
}
}
}
return {mean, cpp};
}
public:
Model<P, Obs> model;
int lag;
int max_components;
};
/*
// ----------- FORWARD-BACKWARD ----------- //
class ForwardBackward{
// needs better implementation via heap
void prun(Message* msg) {
while (msg->components.size() > (unsigned) max_components) {
std::vector<Component*> &comps = msg->components;
double min_c = comps[0]->log_c;
int min_id = 0;
for (size_t i=1; i<comps.size(); i++) {
if (comps[i]->log_c < min_c) {
min_c = comps[i]->log_c;
min_id = i;
}
}
comps.erase(comps.begin() + min_id);
}
}
*/
}
#endif //MATLIB_PML_BCPM_H
<commit_msg>unnecessary comments removed<commit_after>#ifndef MATLIB_PML_BCPM_H
#define MATLIB_PML_BCPM_H
#include "pml.hpp"
#include "pml_rand.hpp"
#include <algorithm>
namespace pml {
// ----------- POTENTIALS ----------- //
class Potential {
public:
explicit Potential(double log_c_) : log_c(log_c_) {}
public:
bool operator<(const Potential &other) const{
return this->log_c < other.log_c;
}
virtual Vector rand() const = 0;
virtual Vector mean() const = 0;
virtual void update(const Vector &obs) = 0;
public:
double log_c;
};
class DirichletPotential : public Potential {
public:
DirichletPotential(size_t K, double log_c_ = 0) : Potential(log_c_) {
alpha = Vector::ones(K);
}
DirichletPotential(const Vector& alpha_, double log_c_ = 0)
: Potential(log_c_), alpha(alpha_) {}
public:
void operator*=(const DirichletPotential &p){
*this = this->operator*(p);
}
DirichletPotential operator*(const DirichletPotential &p) const{
double delta = std::lgamma(sum(alpha)) - sum(lgamma(alpha)) +
std::lgamma(sum(p.alpha)) - sum(lgamma(p.alpha)) +
sum(lgamma(alpha + p.alpha-1)) -
std::lgamma(sum(alpha + p.alpha -1));
return DirichletPotential(alpha + p.alpha - 1,
log_c + p.log_c + delta);
}
void update(const Vector &obs) override{
double log_c = std::lgamma(sum(obs)+1) - std::lgamma(sum(obs+1));
this->operator*=(DirichletPotential(obs+1, log_c));
}
Vector rand() const override {
return dirichlet::rand(alpha);
}
Vector mean() const override {
return normalize(alpha);
}
public:
Vector alpha;
};
class GammaPotential : public Potential {
public:
GammaPotential(double a_ = 1, double b_ = 1, double log_c_ = 0)
: Potential(log_c_), a(a_), b(b_){}
public:
void operator*=(const GammaPotential &other){
*this = this->operator*(other);
}
GammaPotential operator*(const GammaPotential &other) const{
double delta = std::lgamma(a + other.a - 1)
- std::lgamma(a) - std::lgamma(other.a)
+ std::log(b + other.b)
+ a * std::log(b/(b + other.b))
+ other.a * std::log(other.b/(b + other.b));
return GammaPotential(a + other.a - 1,
b + other.b,
log_c + other.log_c + delta);
}
Vector rand() const override {
return gamma::rand(a, b, 1);
}
Vector mean() const override {
return Vector(1, a / b);
}
void update(const Vector &obs) override {
this->operator*=(GammaPotential(obs.first()+1, 1));
}
public:
double a;
double b;
};
// ----------- OBSERVATION MODELS ----------- //
struct PoissonRandom{
Vector operator()(const Vector ¶m) const {
return poisson::rand(param.first(), 1);
}
};
struct MultinomialRandom{
Vector operator()(const Vector ¶m) const {
return multinomial::rand(param, 100);
}
};
// ----------- MESSAGE----------- //
template <class P>
class Message {
public:
size_t size() const {
return components.size();
}
void add_component(const P &potential){
components.push_back(potential);
}
void add_component(const P &potential, double log_c){
components.push_back(potential);
components.back().log_c = log_c;
}
friend Message<P> operator*(const Message<P> &m1, const Message<P> &m2){
Message<P> msg;
for(auto &component1 : m1.components)
for(auto &component2 : m2.components)
msg.add_component(component1 * component2);
return msg;
}
void update(const Vector& obs) {
for(auto &component : components){
component.update(obs);
}
}
// Returns mean and cpp (Maybe renamed)
std::pair<Vector, double> evaluate(int N = 1){
Vector consts;
Matrix params;
for(auto &potential: components){
consts.append(potential.log_c);
params.appendColumn(potential.mean());
}
consts = normalizeExp(consts);
// Calculate mean
Vector mean = sumRows(transpose(transpose(params)*consts));
// Calculate cpp as the sum of last N probabilities
double cpp = 0;
for(int i=0; i < N; ++i)
cpp += consts(consts.size() - i - 1);
return {mean, cpp};
};
void prune(size_t max_components){
while(components.size() > max_components){
// Find mininum no-change element
auto iter = std::min_element(components.begin(), components.end()-1);
// Swap the last two elements to save the order of the change comp.
std::swap(*(components.end()-1), *(components.end()-2));
// Swap last element with the minimum compoment.
std::swap(*iter, components.back());
// Delete minimum component.
components.pop_back();
}
}
public:
std::vector<P> components;
};
// ----------- MODEL----------- //
template <class P, class Obs>
class Model{
public:
Model(const P &prior_, double p1_) : prior(prior_), p1(p1_){
log_p1 = std::log(p1);
log_p0 = std::log(1-p1);
}
public:
// returns "states" as first matrix and "obervations" as second
std::pair<Matrix, Matrix> generateData(size_t T){
Matrix states, obs;
Vector state = prior.rand();
for (size_t t=0; t<T; t++) {
if (t > 0 && uniform::rand() < p1) {
state = prior.rand();
}
states.appendColumn(state);
obs.appendColumn(observation(state));
}
return {states, obs};
}
Message<P> initialMessage(){
Message<P> message;
message.add_component(prior, log_p0);
message.add_component(prior, log_p1);
return message;
}
Message<P> predict(const Message<P> &prev){
Message<P> message = prev;
Vector consts;
for(auto &component : message.components){
consts.append(component.log_c);
component.log_c += log_p0;
}
message.add_component(prior, log_p1 + logSumExp(consts));
return message;
}
private:
P prior;
Obs observation;
double p1; // probability of change
double log_p1, log_p0;
};
template <class P, class Obs>
class ForwardBackward {
public:
ForwardBackward(const Model<P, Obs> &model_,
int lag_ = 0, int max_components_ = 100)
: model(model_), lag(lag_), max_components(max_components_) {}
public:
void oneStepForward(std::vector<Message<P>> &alpha, const Vector& obs) {
// predict step
if (alpha.size() == 0)
alpha.push_back(model.initialMessage());
else
alpha.push_back(model.predict(alpha.back()));
// update step
alpha.back().update(obs);
}
void oneStepBackward(std::vector<Message<P>> &beta, const Vector& obs) {
// predict step
if (beta.size()==0)
beta.push_back(model.initialMessage());
else
beta.push_back(model.predict(beta.back()));
// update step
beta.back().update(obs);
}
std::vector<Message<P>> forward(const Matrix& obs){
std::vector<Message<P>> alpha;
for (size_t i=0; i<obs.ncols(); i++) {
oneStepForward(alpha, obs.getColumn(i));
alpha.back().prune(max_components);
}
return alpha;
}
std::vector<Message<P>> backward(const Matrix& obs){
std::vector<Message<P>> beta;
for (size_t i=obs.ncols(); i>0; i--) {
oneStepBackward(beta, obs.getColumn(i-1));
beta.back().prune(max_components);
}
// We calculated Beta backwards, we need to reverse the list.
std::reverse(beta.begin(), beta.end());
return beta;
}
// Returns mean and cpp
std::pair<Matrix, Vector> filtering(const Matrix& obs) {
// Run forward
auto alpha = forward(obs);
// Calculate mean and cpp
Matrix mean;
Vector cpp;
for(auto &message : alpha){
auto result = message.evaluate();
mean.appendColumn(result.first);
cpp.append(result.second);
}
return {mean, cpp};
}
// Returns mean and cpp
std::pair<Matrix, Vector> smoothing(const Matrix& obs) {
Matrix mean;
Vector cpp;
// Run Forward and Backward
auto alpha = forward(obs);
auto beta = backward(obs);
// Calculate Smoothed density
Message<P> gamma;
for(size_t i=0; i < obs.ncols(); ++i) {
gamma = alpha[i] * beta[i];
auto result = gamma.evaluate(beta[i].size());
mean.appendColumn(result.first);
cpp.append(result.second);
}
return {mean, cpp};
}
// a.k.a. fixed-lag smoothing
std::pair<Matrix, Vector> online_smoothing(const Matrix& obs) {
if( lag == 0){
return filtering(obs);
}
Matrix mean;
Vector cpp;
std::vector<Message<P>> alpha = forward(obs);
Message<P> gamma;
for (size_t t=0; t<obs.ncols()-lag+1; t++) {
auto beta = backward(obs.getColumns(Range(t, t+lag)));
gamma = alpha[t] * beta[0];
auto result = gamma.evaluate(beta[0].size());
mean.appendColumn(result.first);
cpp.append(result.second);
// if T-lag is reached, smooth the rest
if(t == obs.ncols()-lag){
for(int i = 1; i < lag; ++i){
gamma = alpha[t+i] * beta[i];
auto result = gamma.evaluate(beta[i].size());
mean.appendColumn(result.first);
cpp.append(result.second);
}
}
}
return {mean, cpp};
}
public:
Model<P, Obs> model;
int lag;
int max_components;
};
}
#endif //MATLIB_PML_BCPM_H
<|endoftext|>
|
<commit_before>/// \file sqlplus.hh
/// \brief Deprecated backwards-compatibility header. Use mysql++.h in
/// new code instead.
#warning This header is obsolete. Please use mysql++.h instead.
#include "mysql++.h"
using namespace mysqlpp;
<commit_msg>Yet another sqlplus.hh fix. Doxygen stuff well and truly gone now.<commit_after>// Do not add a Doxygen \file comment. It just takes extra time to
// parse this file (and it's one of the biggest ones, because mysql++.h
// includes almost all the other files!), with no serious benefit.
#warning This header is obsolete. Please use mysql++.h instead.
#include "mysql++.h"
using namespace mysqlpp;
<|endoftext|>
|
<commit_before>//MIT License
//Copyright(c) 2017 Patrick Laughrea
#include "parser.h"
#include "errors.h"
#include "patternsContainers.h"
#include "WebssonUtils/utilsWebss.h"
using namespace std;
using namespace webss;
const char ERROR_NO_DEFAULT[] = "no default value, so value must be implemented";
void setDefaultValue(Webss& value, const ParamStandard& defaultValue);
template <class Parameters>
Tuple makeDefaultTuple(const Parameters& params)
{
Tuple tuple(params.getSharedKeys());
for (Tuple::size_type i = 0; i < params.size(); ++i)
setDefaultValue(tuple[i], params[i]);
return tuple;
}
void setDefaultValue(Webss& value, const ParamStandard& defaultValue)
{
if (defaultValue.hasTemplateHead())
value = makeDefaultTuple(defaultValue.getTemplateHeadStandard().getParameters());
else if (!defaultValue.hasDefaultValue())
throw runtime_error(ERROR_NO_DEFAULT);
else
value = Webss(defaultValue.getDefaultPointer());
}
template <class Parameters>
void checkDefaultValues(Tuple& tuple, const Parameters& params)
{
for (Tuple::size_type index = 0; index < tuple.size(); ++index)
if (tuple.at(index).getType() == WebssType::NONE)
setDefaultValue(tuple[index], params[index]);
}
class ParserTemplates : public Parser
{
public:
Webss parseTemplateBodyStandard(const TemplateHeadStandard::Parameters& params)
{
return parseTemplateBody<TemplateHeadStandard::Parameters>(params, [&](const TemplateHeadStandard::Parameters& params) { return Webss(parseTemplateTupleStandard(params)); }, [&](const TemplateHeadStandard::Parameters& params) { return Webss(parseTemplateTupleText(params), true); });
}
Webss parseTemplateBodyText(const TemplateHeadStandard::Parameters& params)
{
return parseTemplateBody<TemplateHeadStandard::Parameters>(params, [&](const TemplateHeadStandard::Parameters& params) { return Webss(parseTemplateTupleText(params), true); }, [&](const TemplateHeadStandard::Parameters& params) { return Webss(parseTemplateTupleText(params), true); });
}
template <class Parameters>
Webss parseTemplateBody(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText)
{
switch (nextTag = getTag(it))
{
case Tag::START_DICTIONARY:
return parseTemplateDictionary<Parameters>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
case Tag::START_LIST:
return parseTemplateList<Parameters>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
case Tag::START_TUPLE:
return funcTemplTupleRegular(params);
case Tag::TEXT_TUPLE:
return funcTemplTupleText(params);
default:
throw runtime_error(ERROR_UNEXPECTED);
}
}
private:
template <class Parameters>
Dictionary parseTemplateDictionary(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText)
{
return parseContainer<Dictionary, ConType::DICTIONARY>(Dictionary(), [&](Dictionary& dict)
{
string name;
if (nextTag == Tag::NAME_START)
name = parseNameSafe();
else if (nextTag == Tag::EXPLICIT_NAME)
name = parseNameExplicit();
else
throw runtime_error(ERROR_UNEXPECTED);
switch (nextTag = getTag(it))
{
case Tag::START_LIST:
dict.addSafe(move(name), parseTemplateList<Parameters>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)));
break;
case Tag::START_TUPLE:
dict.addSafe(move(name), funcTemplTupleRegular(params));
break;
case Tag::TEXT_TUPLE:
dict.addSafe(move(name), funcTemplTupleText(params));
break;
default:
throw runtime_error(ERROR_UNEXPECTED);
}
});
}
template <class Parameters>
List parseTemplateList(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText)
{
return parseContainer<List, ConType::LIST>(List(), [&](List& list)
{
if (nextTag == Tag::START_TUPLE)
list.add(funcTemplTupleRegular(params));
else if (nextTag == Tag::TEXT_TUPLE)
list.add(funcTemplTupleText(params));
else
throw runtime_error(ERROR_UNEXPECTED);
});
}
Tuple parseTemplateTupleStandard(const TemplateHeadStandard::Parameters& params)
{
Tuple tuple(params.getSharedKeys());
Tuple::size_type index = 0;
ContainerSwitcher switcher(*this, ConType::TUPLE, true);
if (!containerEmpty())
{
do
{
switch (nextTag)
{
case Tag::SEPARATOR: //void
break;
case Tag::NAME_START:
{
auto nameType = parseNameType();
if (nameType.type == NameType::NAME)
{
nextTag = getTag(it);
tuple.at(nameType.name) = parseTemplateContainer(params, params.at(nameType.name));
}
else
{
if (params.at(index).hasTemplateHead())
throw runtime_error(ERROR_UNEXPECTED);
switch (nameType.type)
{
case NameType::KEYWORD:
tuple.at(index) = move(nameType.keyword);
break;
case NameType::ENTITY_ABSTRACT:
{
auto otherValue = checkAbstractEntity(nameType.entity);
if (otherValue.type != OtherValue::VALUE_ONLY)
throw runtime_error(ERROR_UNEXPECTED);
tuple.at(index) = move(otherValue.value);
break;
}
case NameType::ENTITY_CONCRETE:
tuple.at(index) = move(nameType.entity);
break;
}
}
break;
}
case Tag::EXPLICIT_NAME:
{
auto name = parseNameExplicit();
nextTag = getTag(it);
tuple.at(name) = parseTemplateContainer(params, params.at(name));
}
default:
tuple.at(index) = parseTemplateContainer(params, params.at(index));
break;
}
++index;
} while (checkNextElement());
}
checkDefaultValues(tuple, params);
return tuple;
}
template <class Parameters>
Tuple parseTemplateTupleText(const Parameters& params)
{
Tuple tuple(params.getSharedKeys());
Tuple::size_type index = 0;
ContainerSwitcher switcher(*this, ConType::TUPLE, true);
if (!containerEmpty())
do
tuple.at(index++) = parseLineString();
while (checkNextElement());
checkDefaultValues(tuple, params);
return tuple;
}
};
Webss Parser::parseTemplate()
{
auto headWebss = parseTemplateHead();
switch (headWebss.getType())
{
case WebssType::BLOCK_HEAD:
nextTag = getTag(it);
return Block(move(headWebss.getBlockHead()), parseValueOnly());
case WebssType::TEMPLATE_HEAD_BINARY:
{
auto head = move(headWebss.getTemplateHeadBinary());
auto body = parseTemplateBodyBinary(head.getParameters());
return{ move(head), move(body) };
}
case WebssType::TEMPLATE_HEAD_SCOPED:
{
auto head = move(headWebss.getTemplateHeadScoped());
auto body = parseTemplateBodyScoped(head.getParameters());
return TemplateScoped(move(head), move(body));
}
case WebssType::TEMPLATE_HEAD_SELF:
throw runtime_error("self in a thead must be within a non-empty thead");
case WebssType::TEMPLATE_HEAD_STANDARD:
{
auto head = move(headWebss.getTemplateHeadStandard());
auto body = parseTemplateBodyStandard(head.getParameters());
return{ move(head), move(body) };
}
case WebssType::TEMPLATE_HEAD_TEXT:
{
auto head = move(headWebss.getTemplateHeadStandard());
auto body = parseTemplateBodyText(head.getParameters());
return{ move(head), move(body), true };
}
}
}
Webss Parser::parseTemplateText()
{
auto head = parseTemplateHeadText();
auto body = parseTemplateBodyText(head.getParameters());
return{ move(head), move(body), true };
}
Webss Parser::parseTemplateBodyBinary(const TemplateHeadBinary::Parameters& params)
{
return static_cast<ParserTemplates*>(this)->parseTemplateBody<TemplateHeadBinary::Parameters>(params, [&](const TemplateHeadBinary::Parameters& params) { return parseTemplateTupleBinary(params); }, [&](const TemplateHeadBinary::Parameters& params) -> Webss { throw runtime_error(ERROR_UNEXPECTED); });
}
Webss Parser::parseTemplateBodyScoped(const TemplateHeadScoped::Parameters& params)
{
ParamDocumentIncluder includer(ents, params);
nextTag = getTag(it);
return parseValueOnly();
}
Webss Parser::parseTemplateBodyStandard(const TemplateHeadStandard::Parameters& params)
{
return static_cast<ParserTemplates*>(this)->parseTemplateBodyStandard(params);
}
Webss Parser::parseTemplateBodyText(const TemplateHeadStandard::Parameters& params)
{
return static_cast<ParserTemplates*>(this)->parseTemplateBodyText(params);
}
Webss Parser::parseTemplateContainer(const TemplateHeadStandard::Parameters& params, const ParamStandard& defaultValue)
{
switch (defaultValue.getTypeThead())
{
case WebssType::TEMPLATE_HEAD_BINARY:
return parseTemplateBodyBinary(defaultValue.getTemplateHeadBinary().getParameters());
case WebssType::TEMPLATE_HEAD_SCOPED:
return parseTemplateBodyScoped(defaultValue.getTemplateHeadScoped().getParameters());
case WebssType::TEMPLATE_HEAD_SELF:
return parseTemplateBodyStandard(params);
case WebssType::TEMPLATE_HEAD_STANDARD:
return parseTemplateBodyStandard(defaultValue.getTemplateHeadStandard().getParameters());
case WebssType::TEMPLATE_HEAD_TEXT:
return parseTemplateBodyText(defaultValue.getTemplateHeadStandard().getParameters());
default:
return parseValueOnly();
}
}<commit_msg>Bugfix<commit_after>//MIT License
//Copyright(c) 2017 Patrick Laughrea
#include "parser.h"
#include "errors.h"
#include "patternsContainers.h"
#include "WebssonUtils/utilsWebss.h"
using namespace std;
using namespace webss;
const char ERROR_NO_DEFAULT[] = "no default value, so value must be implemented";
void setDefaultValue(Webss& value, const ParamStandard& defaultValue);
template <class Parameters>
Tuple makeDefaultTuple(const Parameters& params)
{
Tuple tuple(params.getSharedKeys());
for (Tuple::size_type i = 0; i < params.size(); ++i)
setDefaultValue(tuple[i], params[i]);
return tuple;
}
void setDefaultValue(Webss& value, const ParamStandard& defaultValue)
{
if (defaultValue.hasTemplateHead())
value = makeDefaultTuple(defaultValue.getTemplateHeadStandard().getParameters());
else if (!defaultValue.hasDefaultValue())
throw runtime_error(ERROR_NO_DEFAULT);
else
value = Webss(defaultValue.getDefaultPointer());
}
template <class Parameters>
void checkDefaultValues(Tuple& tuple, const Parameters& params)
{
for (Tuple::size_type index = 0; index < tuple.size(); ++index)
if (tuple.at(index).getType() == WebssType::NONE)
setDefaultValue(tuple[index], params[index]);
}
class ParserTemplates : public Parser
{
public:
Webss parseTemplateBodyStandard(const TemplateHeadStandard::Parameters& params)
{
return parseTemplateBody<TemplateHeadStandard::Parameters>(params, [&](const TemplateHeadStandard::Parameters& params) { return Webss(parseTemplateTupleStandard(params)); }, [&](const TemplateHeadStandard::Parameters& params) { return Webss(parseTemplateTupleText(params), true); });
}
Webss parseTemplateBodyText(const TemplateHeadStandard::Parameters& params)
{
return parseTemplateBody<TemplateHeadStandard::Parameters>(params, [&](const TemplateHeadStandard::Parameters& params) { return Webss(parseTemplateTupleText(params), true); }, [&](const TemplateHeadStandard::Parameters& params) { return Webss(parseTemplateTupleText(params), true); });
}
template <class Parameters>
Webss parseTemplateBody(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText)
{
switch (nextTag = getTag(it))
{
case Tag::START_DICTIONARY:
return parseTemplateDictionary<Parameters>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
case Tag::START_LIST:
return parseTemplateList<Parameters>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
case Tag::START_TUPLE:
return funcTemplTupleRegular(params);
case Tag::TEXT_TUPLE:
return funcTemplTupleText(params);
default:
throw runtime_error(ERROR_UNEXPECTED);
}
}
private:
template <class Parameters>
Dictionary parseTemplateDictionary(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText)
{
return parseContainer<Dictionary, ConType::DICTIONARY>(Dictionary(), [&](Dictionary& dict)
{
string name;
if (nextTag == Tag::NAME_START)
name = parseNameSafe();
else if (nextTag == Tag::EXPLICIT_NAME)
name = parseNameExplicit();
else
throw runtime_error(ERROR_UNEXPECTED);
switch (nextTag = getTag(it))
{
case Tag::START_LIST:
dict.addSafe(move(name), parseTemplateList<Parameters>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)));
break;
case Tag::START_TUPLE:
dict.addSafe(move(name), funcTemplTupleRegular(params));
break;
case Tag::TEXT_TUPLE:
dict.addSafe(move(name), funcTemplTupleText(params));
break;
default:
throw runtime_error(ERROR_UNEXPECTED);
}
});
}
template <class Parameters>
List parseTemplateList(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText)
{
return parseContainer<List, ConType::LIST>(List(), [&](List& list)
{
if (nextTag == Tag::START_TUPLE)
list.add(funcTemplTupleRegular(params));
else if (nextTag == Tag::TEXT_TUPLE)
list.add(funcTemplTupleText(params));
else
throw runtime_error(ERROR_UNEXPECTED);
});
}
Tuple parseTemplateTupleStandard(const TemplateHeadStandard::Parameters& params)
{
Tuple tuple(params.getSharedKeys());
Tuple::size_type index = 0;
ContainerSwitcher switcher(*this, ConType::TUPLE, true);
if (!containerEmpty())
{
do
{
switch (nextTag)
{
case Tag::SEPARATOR: //void
break;
case Tag::NAME_START:
{
auto nameType = parseNameType();
if (nameType.type == NameType::NAME)
{
nextTag = getTag(it);
tuple.at(nameType.name) = parseTemplateContainer(params, params.at(nameType.name));
}
else
{
if (params.at(index).hasTemplateHead())
throw runtime_error(ERROR_UNEXPECTED);
switch (nameType.type)
{
case NameType::KEYWORD:
tuple.at(index) = move(nameType.keyword);
break;
case NameType::ENTITY_ABSTRACT:
{
auto otherValue = checkAbstractEntity(nameType.entity);
if (otherValue.type != OtherValue::VALUE_ONLY)
throw runtime_error(ERROR_UNEXPECTED);
tuple.at(index) = move(otherValue.value);
break;
}
case NameType::ENTITY_CONCRETE:
tuple.at(index) = move(nameType.entity);
break;
}
}
break;
}
case Tag::EXPLICIT_NAME:
{
auto name = parseNameExplicit();
nextTag = getTag(it);
tuple.at(name) = parseTemplateContainer(params, params.at(name));
break;
}
default:
tuple.at(index) = parseTemplateContainer(params, params.at(index));
break;
}
++index;
} while (checkNextElement());
}
checkDefaultValues(tuple, params);
return tuple;
}
template <class Parameters>
Tuple parseTemplateTupleText(const Parameters& params)
{
Tuple tuple(params.getSharedKeys());
Tuple::size_type index = 0;
ContainerSwitcher switcher(*this, ConType::TUPLE, true);
if (!containerEmpty())
do
tuple.at(index++) = parseLineString();
while (checkNextElement());
checkDefaultValues(tuple, params);
return tuple;
}
};
Webss Parser::parseTemplate()
{
auto headWebss = parseTemplateHead();
switch (headWebss.getType())
{
case WebssType::BLOCK_HEAD:
nextTag = getTag(it);
return Block(move(headWebss.getBlockHead()), parseValueOnly());
case WebssType::TEMPLATE_HEAD_BINARY:
{
auto head = move(headWebss.getTemplateHeadBinary());
auto body = parseTemplateBodyBinary(head.getParameters());
return{ move(head), move(body) };
}
case WebssType::TEMPLATE_HEAD_SCOPED:
{
auto head = move(headWebss.getTemplateHeadScoped());
auto body = parseTemplateBodyScoped(head.getParameters());
return TemplateScoped(move(head), move(body));
}
case WebssType::TEMPLATE_HEAD_SELF:
throw runtime_error("self in a thead must be within a non-empty thead");
case WebssType::TEMPLATE_HEAD_STANDARD:
{
auto head = move(headWebss.getTemplateHeadStandard());
auto body = parseTemplateBodyStandard(head.getParameters());
return{ move(head), move(body) };
}
case WebssType::TEMPLATE_HEAD_TEXT:
{
auto head = move(headWebss.getTemplateHeadStandard());
auto body = parseTemplateBodyText(head.getParameters());
return{ move(head), move(body), true };
}
}
}
Webss Parser::parseTemplateText()
{
auto head = parseTemplateHeadText();
auto body = parseTemplateBodyText(head.getParameters());
return{ move(head), move(body), true };
}
Webss Parser::parseTemplateBodyBinary(const TemplateHeadBinary::Parameters& params)
{
return static_cast<ParserTemplates*>(this)->parseTemplateBody<TemplateHeadBinary::Parameters>(params, [&](const TemplateHeadBinary::Parameters& params) { return parseTemplateTupleBinary(params); }, [&](const TemplateHeadBinary::Parameters& params) -> Webss { throw runtime_error(ERROR_UNEXPECTED); });
}
Webss Parser::parseTemplateBodyScoped(const TemplateHeadScoped::Parameters& params)
{
ParamDocumentIncluder includer(ents, params);
nextTag = getTag(it);
return parseValueOnly();
}
Webss Parser::parseTemplateBodyStandard(const TemplateHeadStandard::Parameters& params)
{
return static_cast<ParserTemplates*>(this)->parseTemplateBodyStandard(params);
}
Webss Parser::parseTemplateBodyText(const TemplateHeadStandard::Parameters& params)
{
return static_cast<ParserTemplates*>(this)->parseTemplateBodyText(params);
}
Webss Parser::parseTemplateContainer(const TemplateHeadStandard::Parameters& params, const ParamStandard& defaultValue)
{
switch (defaultValue.getTypeThead())
{
case WebssType::TEMPLATE_HEAD_BINARY:
return parseTemplateBodyBinary(defaultValue.getTemplateHeadBinary().getParameters());
case WebssType::TEMPLATE_HEAD_SCOPED:
return parseTemplateBodyScoped(defaultValue.getTemplateHeadScoped().getParameters());
case WebssType::TEMPLATE_HEAD_SELF:
return parseTemplateBodyStandard(params);
case WebssType::TEMPLATE_HEAD_STANDARD:
return parseTemplateBodyStandard(defaultValue.getTemplateHeadStandard().getParameters());
case WebssType::TEMPLATE_HEAD_TEXT:
return parseTemplateBodyText(defaultValue.getTemplateHeadStandard().getParameters());
default:
return parseValueOnly();
}
}<|endoftext|>
|
<commit_before>/**
* Copyright 2008 Matthew Graham
* 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 <testpp/test.h>
#include "default_output.h"
#include <memory>
#include <algorithm>
#include <ctime>
testpp_c::testpp_c()
: m_result( NULL )
{}
void testpp_c::set_result( testpp_result_c &result )
{
m_result = &result;
}
void testpp_c::not_implemented()
{
m_result->set_test_not_implemented();
}
void testpp_c::not_implemented( short year, short month, short day )
{
if ( is_before( year, month, day ) ) {
m_result->set_test_not_implemented();
}
m_result->fail( "not implemented" );
}
void testpp_c::ignore_until( short year, short month, short day )
{
if ( is_before( year, month, day ) ) {
m_result->set_ignore_failures();
}
}
bool testpp_c::is_before( short year, short month, short day )
{
tm t = { 0 };
t.tm_year = year - 1900;
t.tm_mon = month - 1;
t.tm_mday = day;
t.tm_isdst = -1;
time_t then( mktime( &t ) );
time_t now( time( NULL ) );
return ( now < then );
}
void testpp_c::fail( const std::string &msg, const char *filename, int line )
{
m_result->fail( msg, filename, line );
}
testpp_set_c::~testpp_set_c()
{
std::list< testpp_type_i * >::iterator it;
for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) {
delete *it;
}
m_tests.clear();
m_files.clear();
m_suites.clear();
}
void testpp_set_c::run_test( testpp_c & test, testpp_result_c &result )
{
test.set_result( result );
try {
test.setup();
test.test();
test.teardown();
} catch (...) {
std::cerr << "catch...\n";
}
}
void testpp_set_c::run( testpp_output_i &out )
{
std::list< testpp_type_i * >::const_iterator it;
int passed( 0 );
int failed( 0 );
int ignored( 0 );
int not_implemented( 0 );
for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) {
testpp_type_i &type( **it );
out.begin( type.id() );
std::auto_ptr< testpp_c > test( type.create_test() );
testpp_result_c result;
run_test( *test, result );
if ( result.failure() ) {
++failed;
} else if ( result.ignore_failures() ) {
++ignored;
} else if ( result.test_not_implemented() ) {
++not_implemented;
} else {
++passed;
}
out.complete( type.id(), result );
}
out.summarize( passed, failed );
}
void testpp_set_c::run( testpp_output_i &out, const std::string &test_name )
{
std::list< testpp_type_i * >::iterator it;
int passed( 0 );
int failed( 0 );
for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) {
if ( ! (*it)->id().in_suite( test_name ) ) {
continue;
}
out.begin( (*it)->id() );
std::auto_ptr< testpp_c > test( (*it)->create_test() );
testpp_result_c result;
run_test( *test, result );
if ( result.failure() ) {
++failed;
} else {
++passed;
}
out.complete( (*it)->id(), result );
}
out.summarize( passed, failed );
}
testpp_set_c & testpp_tests()
{
static testpp_set_c static_set;
return static_set;
}
<commit_msg>set the filtered testpp_set run() function to also count ignores & not implemented<commit_after>/**
* Copyright 2008 Matthew Graham
* 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 <testpp/test.h>
#include "default_output.h"
#include <memory>
#include <algorithm>
#include <ctime>
testpp_c::testpp_c()
: m_result( NULL )
{}
void testpp_c::set_result( testpp_result_c &result )
{
m_result = &result;
}
void testpp_c::not_implemented()
{
m_result->set_test_not_implemented();
}
void testpp_c::not_implemented( short year, short month, short day )
{
if ( is_before( year, month, day ) ) {
m_result->set_test_not_implemented();
}
m_result->fail( "not implemented" );
}
void testpp_c::ignore_until( short year, short month, short day )
{
if ( is_before( year, month, day ) ) {
m_result->set_ignore_failures();
}
}
bool testpp_c::is_before( short year, short month, short day )
{
tm t = { 0 };
t.tm_year = year - 1900;
t.tm_mon = month - 1;
t.tm_mday = day;
t.tm_isdst = -1;
time_t then( mktime( &t ) );
time_t now( time( NULL ) );
return ( now < then );
}
void testpp_c::fail( const std::string &msg, const char *filename, int line )
{
m_result->fail( msg, filename, line );
}
testpp_set_c::~testpp_set_c()
{
std::list< testpp_type_i * >::iterator it;
for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) {
delete *it;
}
m_tests.clear();
m_files.clear();
m_suites.clear();
}
void testpp_set_c::run_test( testpp_c & test, testpp_result_c &result )
{
test.set_result( result );
try {
test.setup();
test.test();
test.teardown();
} catch (...) {
std::cerr << "catch...\n";
}
}
void testpp_set_c::run( testpp_output_i &out )
{
std::list< testpp_type_i * >::const_iterator it;
int passed( 0 );
int failed( 0 );
int ignored( 0 );
int not_implemented( 0 );
for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) {
testpp_type_i &type( **it );
out.begin( type.id() );
std::auto_ptr< testpp_c > test( type.create_test() );
testpp_result_c result;
run_test( *test, result );
if ( result.failure() ) {
++failed;
} else if ( result.ignore_failures() ) {
++ignored;
} else if ( result.test_not_implemented() ) {
++not_implemented;
} else {
++passed;
}
out.complete( type.id(), result );
}
out.summarize( passed, failed );
}
void testpp_set_c::run( testpp_output_i &out, const std::string &test_name )
{
std::list< testpp_type_i * >::iterator it;
int passed( 0 );
int failed( 0 );
int ignored( 0 );
int not_implemented( 0 );
for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) {
if ( ! (*it)->id().in_suite( test_name ) ) {
continue;
}
out.begin( (*it)->id() );
std::auto_ptr< testpp_c > test( (*it)->create_test() );
testpp_result_c result;
run_test( *test, result );
if ( result.failure() ) {
++failed;
} else if ( result.ignore_failures() ) {
++ignored;
} else if ( result.test_not_implemented() ) {
++not_implemented;
} else {
++passed;
}
out.complete( (*it)->id(), result );
}
out.summarize( passed, failed );
}
testpp_set_c & testpp_tests()
{
static testpp_set_c static_set;
return static_set;
}
<|endoftext|>
|
<commit_before>// The MIT License (MIT)
// Copyright (c) 2013 lailongwei<[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "core/utils/TestCase_Core_Utils_Algorithm.h"
int TestCase_Core_Utils_Algorithm::Run(int argc, char *argv[])
{
LLBC_PrintLine("llbc library core/utils/Util_Algorithm test");
LLBC_PrintLine("flow check test:");
LLBC_PrintLine("3 + 4: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseAdd(3, 4)));
LLBC_PrintLine("(sint16)32767 + (sint16)2: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseAdd( (sint16)32767, (sint16)2)));
LLBC_PrintLine("(sint16)-32768 + (sint16)-2: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseAdd( (sint16)-32768, (sint16)-2)));
LLBC_PrintLine("2 - 1: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseSub(2, 1)));
LLBC_PrintLine("(sint16)-32768 - (sing16)1: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseSub( (sint16)-32768, (sint16)1)));
LLBC_PrintLine("(sint16)32767 - (sint16)-2: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseSub( (sint16)32767, (sint16)-2)));
LLBC_PrintLine("");
LLBC_PrintLine("NOFLOW string: %s", LLBC_FlowType::Type2Str(LLBC_FlowType::NoFlow));
LLBC_PrintLine("UNDERFLOW string: %s", LLBC_FlowType::Type2Str(LLBC_FlowType::UnderFlow));
LLBC_PrintLine("OVERFLOW string: %s", LLBC_FlowType::Type2Str(LLBC_FlowType::OverFlow));
LLBC_PrintLine("UNKNOWN string: %s", LLBC_FlowType::Type2Str(LLBC_FlowType::Unknown));
LLBC_PrintLine("0xff3d string: %s", LLBC_FlowType::Type2Str(0xff3d));
LLBC_PrintLine("test completed, press any key to exit");
LLBC_String willEscape = ".#=";
const static int nEscapeTestNum = 100000;
std::vector<LLBC_String> t1;
std::vector<LLBC_String> t2;
t1.resize(nEscapeTestNum, "\\abcdefghijklmn.abcdefghijklmn=abcdefghijklmn#abcdefghijklmn.\\abcdefghijklmn.abcdefghijklmn=abcdefghijklmn#abcdefghijklmn.");
t2.resize(nEscapeTestNum, "\\abcdefghijklmn.abcdefghijklmn=abcdefghijklmn#abcdefghijklmn.\\abcdefghijklmn.abcdefghijklmn=abcdefghijklmn#abcdefghijklmn.");
LLBC_Time begTestTime = LLBC_Time::Now();
for (int i = 0; i < nEscapeTestNum; ++i)
{
t1[i].escape(willEscape, '\\');
}
LLBC_PrintLine("LLBC_String escape test used time(ms): %lld",
(LLBC_Time::Now() - begTestTime).GetTotalMilliSeconds());
begTestTime = LLBC_Time::Now();
for (int i = 0; i < nEscapeTestNum; ++i)
{
LLBC_StringEscape(t2[i], willEscape, '\\');
}
LLBC_PrintLine("Algorithm LLBC_String escape test used time(ms): %lld",
(LLBC_Time::Now() - begTestTime).GetTotalMilliSeconds());
getchar();
return 0;
}
<commit_msg>add string escape algorithm<commit_after>// The MIT License (MIT)
// Copyright (c) 2013 lailongwei<[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "core/utils/TestCase_Core_Utils_Algorithm.h"
int TestCase_Core_Utils_Algorithm::Run(int argc, char *argv[])
{
LLBC_PrintLine("llbc library core/utils/Util_Algorithm test");
LLBC_PrintLine("flow check test:");
LLBC_PrintLine("3 + 4: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseAdd(3, 4)));
LLBC_PrintLine("(sint16)32767 + (sint16)2: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseAdd( (sint16)32767, (sint16)2)));
LLBC_PrintLine("(sint16)-32768 + (sint16)-2: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseAdd( (sint16)-32768, (sint16)-2)));
LLBC_PrintLine("2 - 1: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseSub(2, 1)));
LLBC_PrintLine("(sint16)-32768 - (sing16)1: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseSub( (sint16)-32768, (sint16)1)));
LLBC_PrintLine("(sint16)32767 - (sint16)-2: %s",
LLBC_FlowType::Type2Str( LLBC_CheckFlowUseSub( (sint16)32767, (sint16)-2)));
LLBC_PrintLine("");
LLBC_PrintLine("NOFLOW string: %s", LLBC_FlowType::Type2Str(LLBC_FlowType::NoFlow));
LLBC_PrintLine("UNDERFLOW string: %s", LLBC_FlowType::Type2Str(LLBC_FlowType::UnderFlow));
LLBC_PrintLine("OVERFLOW string: %s", LLBC_FlowType::Type2Str(LLBC_FlowType::OverFlow));
LLBC_PrintLine("UNKNOWN string: %s", LLBC_FlowType::Type2Str(LLBC_FlowType::Unknown));
LLBC_PrintLine("0xff3d string: %s", LLBC_FlowType::Type2Str(0xff3d));
LLBC_String willEscape = ".#=";
const static int nEscapeTestNum = 100000;
std::vector<LLBC_String> t1;
std::vector<LLBC_String> t2;
t1.resize(nEscapeTestNum,
"\\abcdefghijklmn.abcdefghijklmn=abcdefghijklmn#abcdefghijklmn.\\abcdefghijklmn.abcdefghijklmn="
"abcdefghijklmn#abcdefghijklmn.");
t2.resize(nEscapeTestNum,
"\\abcdefghijklmn.abcdefghijklmn=abcdefghijklmn#abcdefghijklmn.\\abcdefghijklmn.abcdefghijklmn="
"abcdefghijklmn#abcdefghijklmn.");
LLBC_Time begTestTime = LLBC_Time::Now();
for (int i = 0; i < nEscapeTestNum; ++i)
{
t1[i].escape(willEscape, '\\');
}
LLBC_PrintLine("LLBC_String escape test used time(ms): %lld",
(LLBC_Time::Now() - begTestTime).GetTotalMilliSeconds());
begTestTime = LLBC_Time::Now();
for (int i = 0; i < nEscapeTestNum; ++i)
{
LLBC_StringEscape(t2[i], willEscape, '\\');
}
LLBC_PrintLine("Algorithm LLBC_String escape test used time(ms): %lld",
(LLBC_Time::Now() - begTestTime).GetTotalMilliSeconds());
LLBC_PrintLine("test completed, press any key to exit");
getchar();
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>Ensure that vectorized algorithm are correct<commit_after><|endoftext|>
|
<commit_before>#include "Course.h"
#include "Assignment.h"
#include "Category.h"
#include "Database.h"
#include "Student.h"
#include "Submitted.h"
#include <iostream>
#include <string>
using namespace std;
Course::Course() {}
Course::Course(string name) { load(name); }
void Course::load(string name) {
this->name = name;
db.load(name.append(".sqlite"));
Assignment::create(db);
Category::create(db);
Student::create(db);
Submitted::create(db);
assignments = Assignment::read(db);
categories = Category::read(db);
students = Student::read(db);
submitted = Submitted::read(db);
}
string Course::getName() const { return name; }
Database &Course::getDb() { return db; }
void Course::addAssignment(int categoryId, string name, int pointsPossible) {
Assignment *assignment =
new Assignment(0, categoryId, name, pointsPossible, db);
assignment->insert();
int id = assignment->getId();
assignments[id] = assignment;
}
void Course::updateAssignment(int id, int categoryId, string name,
int pointsPossible) {
if (categoryId != -1)
assignments[id]->setCategoryId(categoryId);
if (name.size() != 0)
assignments[id]->setName(name);
if (pointsPossible != -1)
assignments[id]->setPointsPossible(pointsPossible);
assignments[id]->update();
}
void Course::deleteAssignment(int id) {
assignments[id]->remove();
assignments.erase(id);
}
void Course::printAssignment(int id) { cout << assignments[id] << "\n"; }
void Course::printAssignments() {
for (auto const &item : assignments) {
cout << *item.second << "\n";
}
}
void Course::addCategory(string name, int weight) {
Category *category = new Category(0, name, weight, db);
category->insert();
int id = category->getId();
categories[id] = category;
}
void Course::updateCategory(int id, string name, int weight) {
if (name.size() != 0)
categories[id]->setName(name);
if (weight != -1)
categories[id]->setWeight(weight);
categories[id]->update();
}
void Course::deleteCategory(int id) {
categories[id]->remove();
categories.erase(id);
}
void Course::printCategory(int id) { cout << categories[id] << "\n"; }
void Course::printCategories() {
for (auto const &item : categories) {
cout << *item.second << "\n";
}
}
void Course::addStudent(string id, string firstName, string lastName) {
Student *student = new Student(id, firstName, lastName, db);
students[id] = student;
student->insert();
}
void Course::updateStudent(string id, string firstName, string lastName) {
if (firstName.size() != 0)
students[id]->setFirstName(firstName);
if (lastName.size() != 0)
students[id]->setLastName(lastName);
students[id]->update();
}
void Course::deleteStudent(string id) {
students[id]->remove();
students.erase(id);
}
void Course::printStudent(string id) { cout << students[id] << "\n"; }
void Course::printStudents() {
for (auto const &item : students) {
cout << *item.second << "\n";
}
}
void Course::addSubmitted(int assignmentId, string studentId,
double pointsEarned) {
Submitted *submitted =
new Submitted(0, assignmentId, studentId, pointsEarned, db);
submitted->insert();
int id = submitted->getId();
this->submitted[id] = submitted;
}
void Course::updateSubmitted(int id, int assignmentId, string studentId,
double pointsEarned) {
if (assignmentId != -1)
submitted[id]->setAssignmentId(assignmentId);
if (studentId.size() != 0)
submitted[id]->setStudentId(studentId);
if (pointsEarned != -1)
submitted[id]->setPointsEarned(pointsEarned);
submitted[id]->update();
}
void Course::deleteSubmitted(int id) {
submitted[id]->remove();
submitted.erase(id);
}
void Course::printSubmitted(int id) { cout << submitted[id] << "\n"; }
void Course::printSubmitted() {
for (auto const &item : submitted) {
cout << *item.second << "\n";
}
}
<commit_msg>Add comments to Course.cpp for presentation<commit_after>#include "Course.h"
#include "Assignment.h"
#include "Category.h"
#include "Database.h"
#include "Student.h"
#include "Submitted.h"
#include <iostream>
#include <string>
using namespace std;
// parametized construction - c++11 shortcut
Course::Course() {}
// Course constructor loads the course by that name
Course::Course(string name) { load(name); }
// load function calls db load
void Course::load(string name) {
this->name = name;
db.load(name.append(".sqlite"));
// calls the other class create functions
Assignment::create(db);
Category::create(db);
Student::create(db);
Submitted::create(db);
// calls each class' read function pointing to the database
// loads the members into memory
assignments = Assignment::read(db);
categories = Category::read(db);
students = Student::read(db);
submitted = Submitted::read(db);
}
// name getter - principle of least privelige
string Course::getName() const { return name; }
// Returns the Database
Database &Course::getDb() { return db; }
// utility function to create a new assignment in the course
void Course::addAssignment(int categoryId, string name, int pointsPossible) {
Assignment *assignment =
new Assignment(0, categoryId, name, pointsPossible, db);
assignment->insert();
int id = assignment->getId();
assignments[id] = assignment;
}
// utility function to update existing assignment in the course
void Course::updateAssignment(int id, int categoryId, string name,
int pointsPossible) {
if (categoryId != -1)
assignments[id]->setCategoryId(categoryId);
if (name.size() != 0)
assignments[id]->setName(name);
if (pointsPossible != -1)
assignments[id]->setPointsPossible(pointsPossible);
assignments[id]->update();
}
// utility function to delete assignment in the course
void Course::deleteAssignment(int id) {
assignments[id]->remove();
assignments.erase(id);
}
// utility function to print all the assignments
void Course::printAssignment(int id) { cout << assignments[id] << "\n"; }
void Course::printAssignments() {
for (auto const &item : assignments) {
cout << *item.second << "\n";
}
}
// utility function creates a new category for assignments
void Course::addCategory(string name, int weight) {
Category *category = new Category(0, name, weight, db);
category->insert();
int id = category->getId();
categories[id] = category;
}
// utility function to update an existing category of assignments
void Course::updateCategory(int id, string name, int weight) {
if (name.size() != 0)
categories[id]->setName(name);
if (weight != -1)
categories[id]->setWeight(weight);
categories[id]->update();
}
// utility function to delete a category of assignments
void Course::deleteCategory(int id) {
categories[id]->remove();
categories.erase(id);
}
// utility function prints one assignment category
void Course::printCategory(int id) { cout << categories[id] << "\n"; }
// utility function to print all the assignment categories
void Course::printCategories() {
for (auto const &item : categories) {
cout << *item.second << "\n";
}
}
// utility function to add a new sutdent to the course
void Course::addStudent(string id, string firstName, string lastName) {
Student *student = new Student(id, firstName, lastName, db);
students[id] = student;
student->insert();
}
// update the information of a specific student
void Course::updateStudent(string id, string firstName, string lastName) {
if (firstName.size() != 0)
students[id]->setFirstName(firstName);
if (lastName.size() != 0)
students[id]->setLastName(lastName);
students[id]->update();
}
// delete an existing student
void Course::deleteStudent(string id) {
students[id]->remove();
students.erase(id);
}
// print all the information for a student
void Course::printStudent(string id) { cout << students[id] << "\n"; }
// print all the information for all students
void Course::printStudents() {
for (auto const &item : students) {
cout << *item.second << "\n";
}
}
// create a new assignment to be assigned to students
void Course::addSubmitted(int assignmentId, string studentId,
double pointsEarned) {
Submitted *submitted =
new Submitted(0, assignmentId, studentId, pointsEarned, db);
submitted->insert();
int id = submitted->getId();
this->submitted[id] = submitted;
}
// update an existing assignment
void Course::updateSubmitted(int id, int assignmentId, string studentId,
double pointsEarned) {
if (assignmentId != -1)
submitted[id]->setAssignmentId(assignmentId);
if (studentId.size() != 0)
submitted[id]->setStudentId(studentId);
if (pointsEarned != -1)
submitted[id]->setPointsEarned(pointsEarned);
submitted[id]->update();
}
// deletes an existing assignment
void Course::deleteSubmitted(int id) {
submitted[id]->remove();
submitted.erase(id);
}
// prints a specific assigned assignment
void Course::printSubmitted(int id) { cout << submitted[id] << "\n"; }
// print all assigned assignments
void Course::printSubmitted() {
for (auto const &item : submitted) {
cout << *item.second << "\n";
}
}
<|endoftext|>
|
<commit_before>/**
* @file gaussian_distribution.hpp
* @author Ryan Curtin
*
* Implementation of the Gaussian distribution.
*/
#ifndef __MLPACK_METHODS_HMM_DISTRIBUTIONS_GAUSSIAN_DISTRIBUTION_HPP
#define __MLPACK_METHODS_HMM_DISTRIBUTIONS_GAUSSIAN_DISTRIBUTION_HPP
#include <mlpack/core.hpp>
// Should be somewhere else, maybe in core.
#include <mlpack/methods/gmm/phi.hpp>
namespace mlpack {
namespace distribution {
/**
* A single multivariate Gaussian distribution.
*/
class GaussianDistribution
{
private:
//! Mean of the distribution.
arma::vec mean;
//! Covariance of the distribution.
arma::mat covariance;
public:
/**
* Default constructor, which creates a Gaussian with zero dimension.
*/
GaussianDistribution() { /* nothing to do */ }
/**
* Create a Gaussian distribution with zero mean and identity covariance with
* the given dimensionality.
*/
GaussianDistribution(const size_t dimension) :
mean(arma::zeros<arma::vec>(dimension)),
covariance(arma::eye<arma::mat>(dimension, dimension))
{ /* Nothing to do. */ }
/**
* Create a Gaussian distribution with the given mean and covariance.
*/
GaussianDistribution(const arma::vec& mean, const arma::mat& covariance) :
mean(mean), covariance(covariance) { /* Nothing to do. */ }
//! Return the dimensionality of this distribution.
size_t Dimensionality() const { return mean.n_elem; }
/**
* Return the probability of the given observation.
*/
double Probability(const arma::vec& observation) const
{
return mlpack::gmm::phi(observation, mean, covariance);
}
/**
* Return a randomly generated observation according to the probability
* distribution defined by this object.
*
* @return Random observation from this Gaussian distribution.
*/
arma::vec Random() const;
/**
* Estimate the Gaussian distribution directly from the given observations.
*
* @param observations List of observations.
*/
void Estimate(const arma::mat& observations);
/**
* Estimate the Gaussian distribution from the given observations, taking into
* account the probability of each observation actually being from this
* distribution.
*/
void Estimate(const arma::mat& observations,
const arma::vec& probabilities);
/**
* Return the mean.
*/
const arma::vec& Mean() const { return mean; }
/**
* Return a modifiable copy of the mean.
*/
arma::vec& Mean() { return mean; }
/**
* Return the covariance matrix.
*/
const arma::mat& Covariance() const { return covariance; }
/**
* Return a modifiable copy of the covariance.
*/
arma::mat& Covariance() { return covariance; }
/**
* Returns a string representation of this object.
*/
std::string ToString() const;
};
}; // namespace distribution
}; // namespace mlpack
#endif
<commit_msg>Minor refactoring for brevity.<commit_after>/**
* @file gaussian_distribution.hpp
* @author Ryan Curtin
*
* Implementation of the Gaussian distribution.
*/
#ifndef __MLPACK_METHODS_HMM_DISTRIBUTIONS_GAUSSIAN_DISTRIBUTION_HPP
#define __MLPACK_METHODS_HMM_DISTRIBUTIONS_GAUSSIAN_DISTRIBUTION_HPP
#include <mlpack/core.hpp>
// Should be somewhere else, maybe in core.
#include <mlpack/methods/gmm/phi.hpp>
namespace mlpack {
namespace distribution {
/**
* A single multivariate Gaussian distribution.
*/
class GaussianDistribution
{
private:
//! Mean of the distribution.
arma::vec mean;
//! Covariance of the distribution.
arma::mat covariance;
public:
/**
* Default constructor, which creates a Gaussian with zero dimension.
*/
GaussianDistribution() { /* nothing to do */ }
/**
* Create a Gaussian distribution with zero mean and identity covariance with
* the given dimensionality.
*/
GaussianDistribution(const size_t dimension) :
mean(arma::zeros<arma::vec>(dimension)),
covariance(arma::eye<arma::mat>(dimension, dimension))
{ /* Nothing to do. */ }
/**
* Create a Gaussian distribution with the given mean and covariance.
*/
GaussianDistribution(const arma::vec& mean, const arma::mat& covariance) :
mean(mean), covariance(covariance) { /* Nothing to do. */ }
//! Return the dimensionality of this distribution.
size_t Dimensionality() const { return mean.n_elem; }
/**
* Return the probability of the given observation.
*/
double Probability(const arma::vec& observation) const
{
return mlpack::gmm::phi(observation, mean, covariance);
}
/**
* Return a randomly generated observation according to the probability
* distribution defined by this object.
*
* @return Random observation from this Gaussian distribution.
*/
arma::vec Random() const;
/**
* Estimate the Gaussian distribution directly from the given observations.
*
* @param observations List of observations.
*/
void Estimate(const arma::mat& observations);
/**
* Estimate the Gaussian distribution from the given observations, taking into
* account the probability of each observation actually being from this
* distribution.
*/
void Estimate(const arma::mat& observations,
const arma::vec& probabilities);
//! Return the mean.
const arma::vec& Mean() const { return mean; }
//! Return a modifiable copy of the mean.
arma::vec& Mean() { return mean; }
//! Return the covariance matrix.
const arma::mat& Covariance() const { return covariance; }
//! Return a modifiable copy of the covariance.
arma::mat& Covariance() { return covariance; }
/**
* Returns a string representation of this object.
*/
std::string ToString() const;
};
}; // namespace distribution
}; // namespace mlpack
#endif
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkPropertyPersistence.h"
#include "mitkTestFixture.h"
#include "mitkTestingMacros.h"
#include "mitkStringProperty.h"
#include "mitkIOMimeTypes.h"
#include <mitkNumericConstants.h>
#include <mitkEqual.h>
#include <algorithm>
#include <limits>
class mitkPropertyPersistenceTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkPropertyPersistenceTestSuite);
MITK_TEST(AddInfo);
MITK_TEST(GetInfo);
MITK_TEST(GetInfo_mime);
MITK_TEST(GetInfoByKey);
MITK_TEST(HasInfo);
MITK_TEST(RemoveAllInfo);
MITK_TEST(RemoveInfo);
MITK_TEST(RemoveInfo_withMime);
CPPUNIT_TEST_SUITE_END();
private:
mitk::PropertyPersistenceInfo::Pointer info1;
mitk::PropertyPersistenceInfo::Pointer info2;
mitk::PropertyPersistenceInfo::Pointer info3;
mitk::PropertyPersistenceInfo::Pointer info4;
mitk::PropertyPersistenceInfo::Pointer info5;
mitk::PropertyPersistenceInfo::Pointer info6;
mitk::PropertyPersistenceInfo::Pointer infoX;
mitk::PropertyPersistenceInfo::Pointer infoX2;
std::string prop1;
std::string prop2;
std::string prop3;
std::string prop4;
std::string prop5;
std::string prop6;
std::string propX;
std::string keyX;
std::string propXTemplate;
std::string keyXTemplate;
std::string propX2;
mitk::IPropertyPersistence* service;
static bool checkExistance(const mitk::PropertyPersistence::InfoResultType& infos, const mitk::PropertyPersistenceInfo* info)
{
auto predicate = [info](const mitk::PropertyPersistenceInfo::ConstPointer& x){return infosAreEqual(info, x); };
auto finding = std::find_if(infos.begin(), infos.end(), predicate);
bool result = finding != infos.end();
return result;
}
static bool infosAreEqual(const mitk::PropertyPersistenceInfo* ref, const mitk::PropertyPersistenceInfo* info)
{
bool result = true;
if (!info || !ref)
{
return false;
}
result = result && ref->GetName() == info->GetName();
result = result && ref->GetKey() == info->GetKey();
result = result && ref->GetMimeTypeName() == info->GetMimeTypeName();
return result;
}
public:
void setUp() override
{
service = mitk::CreateTestInstancePropertyPersistence();
prop1 = "prop1";
prop2 = "prop1";
prop3 = "prop1";
prop4 = "prop4";
prop5 = "prop5";
propX = "prop(\\d*)";
keyX = "key(\\d*)";
propXTemplate = "prop$1";
keyXTemplate = "key.$1";
propX2 = "otherprop(\\d*)";
info1 = mitk::PropertyPersistenceInfo::New();
info1->SetNameAndKey(prop1, "key1");
info2 = mitk::PropertyPersistenceInfo::New(prop2, "mime2");
info2->SetNameAndKey(prop2, "key2");
info3 = mitk::PropertyPersistenceInfo::New(prop3, "mime3");
info3->SetNameAndKey(prop3, "key3");
info4 = mitk::PropertyPersistenceInfo::New(prop4, "mime2");
info4->SetNameAndKey(prop4, "key2");
info5 = mitk::PropertyPersistenceInfo::New(prop5, "mime5");
info5->SetNameAndKey(prop5, "key5");
infoX = mitk::PropertyPersistenceInfo::New("","mimeX");
infoX->UseRegEx(propX, propXTemplate, keyX, keyXTemplate);
infoX2 = mitk::PropertyPersistenceInfo::New();
infoX2->UseRegEx(propX2, propXTemplate);
service->AddInfo(info1, false);
service->AddInfo(info2, false);
service->AddInfo(info3, false);
service->AddInfo(info4, false);
service->AddInfo(info5, false);
service->AddInfo(infoX, false);
service->AddInfo(infoX2, false);
}
void tearDown() override
{
delete service;
}
void AddInfo()
{
mitk::PropertyPersistenceInfo::Pointer info2_new = mitk::PropertyPersistenceInfo::New(prop2, "otherMime");
info2_new->SetNameAndKey(prop2, "newKey");
mitk::PropertyPersistenceInfo::Pointer info2_otherKey = mitk::PropertyPersistenceInfo::New("prop2", "mime2");
info2_otherKey->SetNameAndKey(prop2, "otherKey");
mitk::PropertyPersistenceInfo::Pointer info_newPropNKey = mitk::PropertyPersistenceInfo::New("", "otherMime");
info_newPropNKey->SetNameAndKey("newProp", "newKey");
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> no adding", !service->AddInfo(info2_otherKey, false));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> no adding -> key should not be changed.", service->GetInfo(prop2, "mime2", false).front()->GetKey() == "key2");
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (overwrite) -> adding", service->AddInfo(info2_otherKey, true));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> adding -> key should be changed.", service->GetInfo(prop2, "mime2", false).front()->GetKey() == "otherKey");
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (other mime type; no overwrite) -> adding", service->AddInfo(info2_new, false));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (other mime type; no overwrite) -> adding -> info exists.", !service->GetInfo(prop2, "otherMime", false).empty());
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (new prop name; no overwrite) -> adding", service->AddInfo(info_newPropNKey, false));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (new prop name; no overwrite) -> adding ->info exists.", !service->GetInfo("newProp", "otherMime", false).empty());
}
void GetInfo()
{
mitk::PropertyPersistence::InfoResultType infos = service->GetInfo(prop1, false);
CPPUNIT_ASSERT(infos.size() == 3);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info1));
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info2));
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info3));
infos = service->GetInfo(prop4, false);
CPPUNIT_ASSERT(infos.size() == 1);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info4));
infos = service->GetInfo("unkown", false);
CPPUNIT_ASSERT_MESSAGE("Check size of result for unkown prop.", infos.empty());
infos = service->GetInfo("prop101", false);
CPPUNIT_ASSERT(infos.empty());
infos = service->GetInfo("prop101", true);
CPPUNIT_ASSERT(infos.size() == 1);
CPPUNIT_ASSERT_MESSAGE("Check Name of expected element 1.", infos.front()->GetName() == "prop101");
CPPUNIT_ASSERT_MESSAGE("Check Key of expected element 1.", infos.front()->GetKey() == "key.101");
CPPUNIT_ASSERT_MESSAGE("Check MimeTypeName of expected element 1.", infos.front()->GetMimeTypeName() == "mimeX");
}
void GetInfoByKey()
{
mitk::PropertyPersistence::InfoResultType infos = service->GetInfoByKey("key2", false);
CPPUNIT_ASSERT(infos.size() == 2);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info2));
CPPUNIT_ASSERT_MESSAGE("Check expected element 2.", checkExistance(infos, info4));
infos = service->GetInfoByKey("key5", false);
CPPUNIT_ASSERT(infos.size() == 1);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info5));
infos = service->GetInfoByKey("unkownkey", false);
CPPUNIT_ASSERT_MESSAGE("Check size of result for unkown key.", infos.empty());
infos = service->GetInfoByKey("key101", false);
CPPUNIT_ASSERT_MESSAGE("Check size of result for key101.", infos.empty());
infos = service->GetInfoByKey("key101", true);
CPPUNIT_ASSERT(infos.size() == 1);
CPPUNIT_ASSERT_MESSAGE("Check Name of expected element 1.", infos.front()->GetName() == "prop101");
CPPUNIT_ASSERT_MESSAGE("Check Key of expected element 1.", infos.front()->GetKey() == "key101");
CPPUNIT_ASSERT_MESSAGE("Check MimeTypeName of expected element 1.", infos.front()->GetMimeTypeName() == "mimeX");
}
void GetInfo_mime()
{
mitk::PropertyPersistence::InfoResultType infos = service->GetInfo(prop1, "mime2", false, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (existing element, no wildcard allowed, wildcard exists).", infosAreEqual(info2, infos.front()));
infos = service->GetInfo(prop1, "mime2", true, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (existing element, wildcard allowed, wildcard exists).", infosAreEqual(info2, infos.front()));
infos = service->GetInfo(prop1, "unknownmime", false, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, no wildcard allowed, wildcard exists).", infos.empty());
infos = service->GetInfo(prop1, "unknownmime", true, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, wildcard allowed, wildcard exists).", infosAreEqual(info1, infos.front()));
infos = service->GetInfo(prop4, "unknownmime", false, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, no wildcard allowed).", infos.empty());
infos = service->GetInfo(prop4, "unknownmime", true, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, wildcard allowed).", infos.empty());
infos = service->GetInfo("prop101", "unknownmime", false, true);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, no wildcard allowed, regex allowed).", infos.empty());
infos = service->GetInfo("prop101", "mimeX", false, true);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (existing mime, no wildcard allowed, regex allowed).", infos.size() == 1);
infos = service->GetInfo("otherprop", "unknownmime", false, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, no wildcard allowed, no regex allowed).", infos.empty());
infos = service->GetInfo("otherprop", "unknownmime", true, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, wildcard allowed, no regex allowed).", infos.empty());
infos = service->GetInfo("otherprop", "unknownmime", false, true);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, no wildcard allowed, regex allowed).", infos.empty());
infos = service->GetInfo("otherprop", "unknownmime", true, true);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, wildcard allowed, regex allowed).", infos.size() == 1);
}
void HasInfo()
{
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", service->HasInfo(prop1));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", service->HasInfo(prop4));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (unkown prop)", !service->HasInfo("unkownProp"));
}
void RemoveAllInfo()
{
CPPUNIT_ASSERT_NO_THROW(service->RemoveAllInfo());
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", !service->HasInfo(prop1));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", !service->HasInfo(prop4));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", !service->HasInfo(prop5));
}
void RemoveInfo()
{
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop1));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", !service->HasInfo(prop1,false));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", service->HasInfo(prop4, false));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", service->HasInfo(prop5, false));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop4));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", !service->HasInfo(prop4, false));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", service->HasInfo(prop5, false));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop5));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", !service->HasInfo(prop5, false));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo("unknown_prop"));
}
void RemoveInfo_withMime()
{
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop1, "mime2"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos if info was removed",service->GetInfo(prop1, "mime2", false).empty());
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if other info of same property name still exists", !service->GetInfo(prop1, "mime3", false).empty());
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if other info of other property name but same mime still exists", !service->GetInfo(prop4, "mime2", false).empty());
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop5, "wrongMime"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos on prop 5 with wrong mime", service->HasInfo(prop5, false));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop5, "mime5"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos on prop 5", !service->HasInfo(prop5, false));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo("unkown_prop", "mime2"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if unkown property name but exting mime was used", service->HasInfo(prop4, false));
}
};
MITK_TEST_SUITE_REGISTRATION(mitkPropertyPersistence)
<commit_msg>added missing header to avoid compile errors for linux<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <cmath>
#include <algorithm>
#include <limits>
#include "mitkPropertyPersistence.h"
#include "mitkTestFixture.h"
#include "mitkTestingMacros.h"
#include "mitkStringProperty.h"
#include "mitkIOMimeTypes.h"
#include <mitkNumericConstants.h>
#include <mitkEqual.h>
class mitkPropertyPersistenceTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkPropertyPersistenceTestSuite);
MITK_TEST(AddInfo);
MITK_TEST(GetInfo);
MITK_TEST(GetInfo_mime);
MITK_TEST(GetInfoByKey);
MITK_TEST(HasInfo);
MITK_TEST(RemoveAllInfo);
MITK_TEST(RemoveInfo);
MITK_TEST(RemoveInfo_withMime);
CPPUNIT_TEST_SUITE_END();
private:
mitk::PropertyPersistenceInfo::Pointer info1;
mitk::PropertyPersistenceInfo::Pointer info2;
mitk::PropertyPersistenceInfo::Pointer info3;
mitk::PropertyPersistenceInfo::Pointer info4;
mitk::PropertyPersistenceInfo::Pointer info5;
mitk::PropertyPersistenceInfo::Pointer info6;
mitk::PropertyPersistenceInfo::Pointer infoX;
mitk::PropertyPersistenceInfo::Pointer infoX2;
std::string prop1;
std::string prop2;
std::string prop3;
std::string prop4;
std::string prop5;
std::string prop6;
std::string propX;
std::string keyX;
std::string propXTemplate;
std::string keyXTemplate;
std::string propX2;
mitk::IPropertyPersistence* service;
static bool checkExistance(const mitk::PropertyPersistence::InfoResultType& infos, const mitk::PropertyPersistenceInfo* info)
{
auto predicate = [info](const mitk::PropertyPersistenceInfo::ConstPointer& x){return infosAreEqual(info, x); };
auto finding = std::find_if(infos.begin(), infos.end(), predicate);
bool result = finding != infos.end();
return result;
}
static bool infosAreEqual(const mitk::PropertyPersistenceInfo* ref, const mitk::PropertyPersistenceInfo* info)
{
bool result = true;
if (!info || !ref)
{
return false;
}
result = result && ref->GetName() == info->GetName();
result = result && ref->GetKey() == info->GetKey();
result = result && ref->GetMimeTypeName() == info->GetMimeTypeName();
return result;
}
public:
void setUp() override
{
service = mitk::CreateTestInstancePropertyPersistence();
prop1 = "prop1";
prop2 = "prop1";
prop3 = "prop1";
prop4 = "prop4";
prop5 = "prop5";
propX = "prop(\\d*)";
keyX = "key(\\d*)";
propXTemplate = "prop$1";
keyXTemplate = "key.$1";
propX2 = "otherprop(\\d*)";
info1 = mitk::PropertyPersistenceInfo::New();
info1->SetNameAndKey(prop1, "key1");
info2 = mitk::PropertyPersistenceInfo::New(prop2, "mime2");
info2->SetNameAndKey(prop2, "key2");
info3 = mitk::PropertyPersistenceInfo::New(prop3, "mime3");
info3->SetNameAndKey(prop3, "key3");
info4 = mitk::PropertyPersistenceInfo::New(prop4, "mime2");
info4->SetNameAndKey(prop4, "key2");
info5 = mitk::PropertyPersistenceInfo::New(prop5, "mime5");
info5->SetNameAndKey(prop5, "key5");
infoX = mitk::PropertyPersistenceInfo::New("","mimeX");
infoX->UseRegEx(propX, propXTemplate, keyX, keyXTemplate);
infoX2 = mitk::PropertyPersistenceInfo::New();
infoX2->UseRegEx(propX2, propXTemplate);
service->AddInfo(info1, false);
service->AddInfo(info2, false);
service->AddInfo(info3, false);
service->AddInfo(info4, false);
service->AddInfo(info5, false);
service->AddInfo(infoX, false);
service->AddInfo(infoX2, false);
}
void tearDown() override
{
delete service;
}
void AddInfo()
{
mitk::PropertyPersistenceInfo::Pointer info2_new = mitk::PropertyPersistenceInfo::New(prop2, "otherMime");
info2_new->SetNameAndKey(prop2, "newKey");
mitk::PropertyPersistenceInfo::Pointer info2_otherKey = mitk::PropertyPersistenceInfo::New("prop2", "mime2");
info2_otherKey->SetNameAndKey(prop2, "otherKey");
mitk::PropertyPersistenceInfo::Pointer info_newPropNKey = mitk::PropertyPersistenceInfo::New("", "otherMime");
info_newPropNKey->SetNameAndKey("newProp", "newKey");
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> no adding", !service->AddInfo(info2_otherKey, false));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> no adding -> key should not be changed.", service->GetInfo(prop2, "mime2", false).front()->GetKey() == "key2");
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (overwrite) -> adding", service->AddInfo(info2_otherKey, true));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> adding -> key should be changed.", service->GetInfo(prop2, "mime2", false).front()->GetKey() == "otherKey");
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (other mime type; no overwrite) -> adding", service->AddInfo(info2_new, false));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (other mime type; no overwrite) -> adding -> info exists.", !service->GetInfo(prop2, "otherMime", false).empty());
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (new prop name; no overwrite) -> adding", service->AddInfo(info_newPropNKey, false));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (new prop name; no overwrite) -> adding ->info exists.", !service->GetInfo("newProp", "otherMime", false).empty());
}
void GetInfo()
{
mitk::PropertyPersistence::InfoResultType infos = service->GetInfo(prop1, false);
CPPUNIT_ASSERT(infos.size() == 3);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info1));
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info2));
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info3));
infos = service->GetInfo(prop4, false);
CPPUNIT_ASSERT(infos.size() == 1);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info4));
infos = service->GetInfo("unkown", false);
CPPUNIT_ASSERT_MESSAGE("Check size of result for unkown prop.", infos.empty());
infos = service->GetInfo("prop101", false);
CPPUNIT_ASSERT(infos.empty());
infos = service->GetInfo("prop101", true);
CPPUNIT_ASSERT(infos.size() == 1);
CPPUNIT_ASSERT_MESSAGE("Check Name of expected element 1.", infos.front()->GetName() == "prop101");
CPPUNIT_ASSERT_MESSAGE("Check Key of expected element 1.", infos.front()->GetKey() == "key.101");
CPPUNIT_ASSERT_MESSAGE("Check MimeTypeName of expected element 1.", infos.front()->GetMimeTypeName() == "mimeX");
}
void GetInfoByKey()
{
mitk::PropertyPersistence::InfoResultType infos = service->GetInfoByKey("key2", false);
CPPUNIT_ASSERT(infos.size() == 2);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info2));
CPPUNIT_ASSERT_MESSAGE("Check expected element 2.", checkExistance(infos, info4));
infos = service->GetInfoByKey("key5", false);
CPPUNIT_ASSERT(infos.size() == 1);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info5));
infos = service->GetInfoByKey("unkownkey", false);
CPPUNIT_ASSERT_MESSAGE("Check size of result for unkown key.", infos.empty());
infos = service->GetInfoByKey("key101", false);
CPPUNIT_ASSERT_MESSAGE("Check size of result for key101.", infos.empty());
infos = service->GetInfoByKey("key101", true);
CPPUNIT_ASSERT(infos.size() == 1);
CPPUNIT_ASSERT_MESSAGE("Check Name of expected element 1.", infos.front()->GetName() == "prop101");
CPPUNIT_ASSERT_MESSAGE("Check Key of expected element 1.", infos.front()->GetKey() == "key101");
CPPUNIT_ASSERT_MESSAGE("Check MimeTypeName of expected element 1.", infos.front()->GetMimeTypeName() == "mimeX");
}
void GetInfo_mime()
{
mitk::PropertyPersistence::InfoResultType infos = service->GetInfo(prop1, "mime2", false, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (existing element, no wildcard allowed, wildcard exists).", infosAreEqual(info2, infos.front()));
infos = service->GetInfo(prop1, "mime2", true, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (existing element, wildcard allowed, wildcard exists).", infosAreEqual(info2, infos.front()));
infos = service->GetInfo(prop1, "unknownmime", false, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, no wildcard allowed, wildcard exists).", infos.empty());
infos = service->GetInfo(prop1, "unknownmime", true, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, wildcard allowed, wildcard exists).", infosAreEqual(info1, infos.front()));
infos = service->GetInfo(prop4, "unknownmime", false, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, no wildcard allowed).", infos.empty());
infos = service->GetInfo(prop4, "unknownmime", true, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, wildcard allowed).", infos.empty());
infos = service->GetInfo("prop101", "unknownmime", false, true);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, no wildcard allowed, regex allowed).", infos.empty());
infos = service->GetInfo("prop101", "mimeX", false, true);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (existing mime, no wildcard allowed, regex allowed).", infos.size() == 1);
infos = service->GetInfo("otherprop", "unknownmime", false, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, no wildcard allowed, no regex allowed).", infos.empty());
infos = service->GetInfo("otherprop", "unknownmime", true, false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, wildcard allowed, no regex allowed).", infos.empty());
infos = service->GetInfo("otherprop", "unknownmime", false, true);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, no wildcard allowed, regex allowed).", infos.empty());
infos = service->GetInfo("otherprop", "unknownmime", true, true);
CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, wildcard allowed, regex allowed).", infos.size() == 1);
}
void HasInfo()
{
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", service->HasInfo(prop1));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", service->HasInfo(prop4));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (unkown prop)", !service->HasInfo("unkownProp"));
}
void RemoveAllInfo()
{
CPPUNIT_ASSERT_NO_THROW(service->RemoveAllInfo());
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", !service->HasInfo(prop1));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", !service->HasInfo(prop4));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", !service->HasInfo(prop5));
}
void RemoveInfo()
{
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop1));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", !service->HasInfo(prop1,false));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", service->HasInfo(prop4, false));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", service->HasInfo(prop5, false));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop4));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", !service->HasInfo(prop4, false));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", service->HasInfo(prop5, false));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop5));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", !service->HasInfo(prop5, false));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo("unknown_prop"));
}
void RemoveInfo_withMime()
{
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop1, "mime2"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos if info was removed",service->GetInfo(prop1, "mime2", false).empty());
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if other info of same property name still exists", !service->GetInfo(prop1, "mime3", false).empty());
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if other info of other property name but same mime still exists", !service->GetInfo(prop4, "mime2", false).empty());
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop5, "wrongMime"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos on prop 5 with wrong mime", service->HasInfo(prop5, false));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop5, "mime5"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos on prop 5", !service->HasInfo(prop5, false));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo("unkown_prop", "mime2"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if unkown property name but exting mime was used", service->HasInfo(prop4, false));
}
};
MITK_TEST_SUITE_REGISTRATION(mitkPropertyPersistence)
<|endoftext|>
|
<commit_before>#include <ObjectAllocationModel.hpp>
#include <b9/interpreter.hpp>
#include <b9/loader.hpp>
#include <b9/objects.hpp>
#include <b9/objects.inl.hpp>
// #include <omrgcallocate.hpp>
#include <b9/allocator.hpp>
#include <b9/context.hpp>
#include <b9/runtime.hpp>
#include <b9/allocator.inl.hpp>
#include <b9/memorymanager.inl.hpp>
#include <b9/rooting.inl.hpp>
#include <omrgc.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <vector>
#include <gtest/gtest.h>
namespace b9 {
namespace test {
// clang-format off
const std::vector<const char*> TEST_NAMES = {
"test_return_true",
"test_return_false",
"test_add",
"test_sub",
// CASCON2017 add test_div and test_mul here
"test_equal",
"test_equal_1",
"test_greaterThan",
"test_greaterThan_1",
"test_greaterThanOrEqual",
"test_greaterThanOrEqual_1",
"test_greaterThanOrEqual_2",
"test_lessThan",
"test_lessThan_1",
"test_lessThan_2",
"test_lessThan_3",
"test_lessThanOrEqual",
"test_lessThanOrEqual_1",
"test_call",
"test_string_declare_string_var",
"helper_test_string_return_string",
"test_string_return_string",
"test_while"
};
// clang-format on
Object* newObject(Context& cx, Map* map) {
return nullptr;
// ObjectInitializer init(map, sizeof(Object), 0);
// auto p = OMR_GC_Allocate(cx.omrEnv(), init);
// return (Object*)p;
}
ProcessRuntime runtime;
TEST(MemoryManagerTest, startUpAndShutDown) {
MemoryManager manager(runtime);
EXPECT_NE(manager.globals().metaMap, nullptr);
EXPECT_NE(manager.globals().emptyObjectMap, nullptr);
Context cx(manager);
EXPECT_NE(cx.globals().metaMap, nullptr);
EXPECT_NE(cx.globals().emptyObjectMap, nullptr);
MetaMap* metaMap = allocateMetaMap(cx);
EXPECT_EQ(metaMap, metaMap->map());
}
TEST(MemoryManagerTest, startUpAContext) {
MemoryManager manager(runtime);
Context cx(manager);
EXPECT_NE(cx.globals().metaMap, nullptr);
EXPECT_NE(cx.globals().emptyObjectMap, nullptr);
}
TEST(MemoryManagerTest, allocateTheMetaMap) {
MemoryManager manager(runtime);
Context cx(manager);
MetaMap* metaMap = allocateMetaMap(cx);
EXPECT_EQ(metaMap, metaMap->map());
}
TEST(MemoryManagerTest, loseAnObjects) {
MemoryManager manager(runtime);
Context cx(manager);
Object* object = allocateEmptyObject(cx);
EXPECT_EQ(object->map(), cx.globals().emptyObjectMap);
OMR_GC_SystemCollect(cx.omrVmThread(), 0);
// EXPECT_EQ(object->map(), (Map*)0x5e5e5e5e5e5e5e5eul);
}
TEST(MemoryManagerTest, keepAnObject) {
MemoryManager manager(runtime);
Context cx(manager);
RootRef<Object> object(cx, allocateEmptyObject(cx));
EXPECT_EQ(object->map(), cx.globals().emptyObjectMap);
OMR_GC_SystemCollect(cx.omrVmThread(), 0);
EXPECT_EQ(object->map(), cx.globals().emptyObjectMap);
}
class InterpreterTest : public ::testing::Test {
public:
std::shared_ptr<Module> module_;
virtual void SetUp() {
auto moduleName = getenv("B9_TEST_MODULE");
ASSERT_NE(moduleName, nullptr);
module_ = DlLoader{}.loadModule(moduleName);
}
};
TEST_F(InterpreterTest, interpreter) {
Config cfg;
VirtualMachine vm{runtime, cfg};
vm.load(module_);
for (auto test : TEST_NAMES) {
EXPECT_TRUE(vm.run(test, {}).getInteger()) << "Test Failed: " << test;
}
}
TEST_F(InterpreterTest, jit) {
Config cfg;
cfg.jit = true;
VirtualMachine vm{runtime, cfg};
vm.load(module_);
vm.generateAllCode();
for (auto test : TEST_NAMES) {
EXPECT_TRUE(vm.run(test, {}).getInteger()) << "Test Failed: " << test;
}
}
TEST_F(InterpreterTest, jit_dc) {
Config cfg;
cfg.jit = true;
cfg.directCall = true;
VirtualMachine vm{runtime, cfg};
vm.load(module_);
vm.generateAllCode();
for (auto test : TEST_NAMES) {
EXPECT_TRUE(vm.run(test, {}).getInteger()) << "Test Failed: " << test;
}
}
TEST_F(InterpreterTest, jit_pp) {
Config cfg;
cfg.jit = true;
cfg.directCall = true;
cfg.passParam = true;
VirtualMachine vm{runtime, cfg};
vm.load(module_);
vm.generateAllCode();
for (auto test : TEST_NAMES) {
EXPECT_TRUE(vm.run(test, {}).getInteger()) << "Test Failed: " << test;
}
}
TEST_F(InterpreterTest, jit_lvms) {
Config cfg;
cfg.jit = true;
cfg.directCall = true;
cfg.passParam = true;
cfg.lazyVmState = true;
VirtualMachine vm{runtime, cfg};
vm.load(module_);
vm.generateAllCode();
for (auto test : TEST_NAMES) {
EXPECT_TRUE(vm.run(test, {}).getInteger()) << "Test Failed: " << test;
}
}
TEST(MyTest, arguments) {
b9::VirtualMachine vm{runtime, {}};
auto m = std::make_shared<Module>();
Instruction i[] = {{ByteCode::PUSH_FROM_VAR, 0},
{ByteCode::PUSH_FROM_VAR, 1},
{ByteCode::INT_ADD},
{ByteCode::FUNCTION_RETURN},
END_SECTION};
m->functions.push_back(b9::FunctionSpec{"add_args", i, 2, 0});
vm.load(m);
auto r = vm.run("add_args", {{Value::integer, 1}, {Value::integer, 2}});
EXPECT_EQ(r, Value(Value::integer, 3));
}
extern "C" void b9_prim_print_string(ExecutionContext* context);
TEST(ObjectTest, allocateSomething) {
b9::VirtualMachine vm{runtime, {}};
auto m = std::make_shared<Module>();
Instruction i[] = {
{ByteCode::NEW_OBJECT}, // new object
{ByteCode::POP_INTO_VAR, 0}, // store object into var0
{ByteCode::STR_PUSH_CONSTANT, 0}, // push "voila"
{ByteCode::PUSH_FROM_VAR, 0}, // push var0 aka object
{ByteCode::POP_INTO_OBJECT, 0}, // pop "voila" into object at slot 0
{ByteCode::SYSTEM_COLLECT}, // GC. Object is kept alive by var0
{ByteCode::PUSH_FROM_VAR, 0}, // push object
{ByteCode::PUSH_FROM_OBJECT, 0}, // get the string back
{ByteCode::PRIMITIVE_CALL,
0}, // call b9_prim_print_string, output is "voila"
{ByteCode::FUNCTION_RETURN}, // finish with constant 0
END_SECTION};
m->strings.push_back("voila");
m->functions.push_back(b9::FunctionSpec{"allocate_object", i, 0, 1});
m->primitives.push_back(b9_prim_print_string);
vm.load(m);
auto r = vm.run("allocate_object", {});
EXPECT_EQ(r, 0);
}
} // namespace test
} // namespace b9
<commit_msg>Add tests for values and doubles<commit_after>#include <ObjectAllocationModel.hpp>
#include <b9/interpreter.hpp>
#include <b9/loader.hpp>
#include <b9/objects.hpp>
#include <b9/objects.inl.hpp>
// #include <omrgcallocate.hpp>
#include <b9/allocator.hpp>
#include <b9/context.hpp>
#include <b9/runtime.hpp>
#include <b9/allocator.inl.hpp>
#include <b9/memorymanager.inl.hpp>
#include <b9/rooting.inl.hpp>
#include <omrgc.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <vector>
#include <gtest/gtest.h>
namespace b9 {
namespace test {
// clang-format off
const std::vector<const char*> TEST_NAMES = {
"test_return_true",
"test_return_false",
"test_add",
"test_sub",
// CASCON2017 add test_div and test_mul here
"test_equal",
"test_equal_1",
"test_greaterThan",
"test_greaterThan_1",
"test_greaterThanOrEqual",
"test_greaterThanOrEqual_1",
"test_greaterThanOrEqual_2",
"test_lessThan",
"test_lessThan_1",
"test_lessThan_2",
"test_lessThan_3",
"test_lessThanOrEqual",
"test_lessThanOrEqual_1",
"test_call",
"test_string_declare_string_var",
"helper_test_string_return_string",
"test_string_return_string",
"test_while"
};
// clang-format on
ProcessRuntime runtime;
TEST(MemoryManagerTest, startUpAndShutDown) {
MemoryManager manager(runtime);
EXPECT_NE(manager.globals().metaMap, nullptr);
EXPECT_NE(manager.globals().emptyObjectMap, nullptr);
Context cx(manager);
EXPECT_NE(cx.globals().metaMap, nullptr);
EXPECT_NE(cx.globals().emptyObjectMap, nullptr);
MetaMap* metaMap = allocateMetaMap(cx);
EXPECT_EQ(metaMap, metaMap->map());
}
TEST(MemoryManagerTest, startUpAContext) {
MemoryManager manager(runtime);
Context cx(manager);
EXPECT_NE(cx.globals().metaMap, nullptr);
EXPECT_NE(cx.globals().emptyObjectMap, nullptr);
}
TEST(MemoryManagerTest, allocateTheMetaMap) {
MemoryManager manager(runtime);
Context cx(manager);
MetaMap* metaMap = allocateMetaMap(cx);
EXPECT_EQ(metaMap, metaMap->map());
}
TEST(MemoryManagerTest, loseAnObjects) {
MemoryManager manager(runtime);
Context cx(manager);
Object* object = allocateEmptyObject(cx);
EXPECT_EQ(object->map(), cx.globals().emptyObjectMap);
OMR_GC_SystemCollect(cx.omrVmThread(), 0);
// EXPECT_EQ(object->map(), (Map*)0x5e5e5e5e5e5e5e5eul);
}
TEST(MemoryManagerTest, keepAnObject) {
MemoryManager manager(runtime);
Context cx(manager);
RootRef<Object> object(cx, allocateEmptyObject(cx));
EXPECT_EQ(object->map(), cx.globals().emptyObjectMap);
OMR_GC_SystemCollect(cx.omrVmThread(), 0);
EXPECT_EQ(object->map(), cx.globals().emptyObjectMap);
}
class InterpreterTest : public ::testing::Test {
public:
std::shared_ptr<Module> module_;
virtual void SetUp() {
auto moduleName = getenv("B9_TEST_MODULE");
ASSERT_NE(moduleName, nullptr);
module_ = DlLoader{}.loadModule(moduleName);
}
};
TEST_F(InterpreterTest, interpreter) {
Config cfg;
VirtualMachine vm{runtime, cfg};
vm.load(module_);
for (auto test : TEST_NAMES) {
EXPECT_TRUE(vm.run(test, {}).getInteger()) << "Test Failed: " << test;
}
}
TEST_F(InterpreterTest, jit) {
Config cfg;
cfg.jit = true;
VirtualMachine vm{runtime, cfg};
vm.load(module_);
vm.generateAllCode();
for (auto test : TEST_NAMES) {
EXPECT_TRUE(vm.run(test, {}).getInteger()) << "Test Failed: " << test;
}
}
TEST_F(InterpreterTest, jit_dc) {
Config cfg;
cfg.jit = true;
cfg.directCall = true;
VirtualMachine vm{runtime, cfg};
vm.load(module_);
vm.generateAllCode();
for (auto test : TEST_NAMES) {
EXPECT_TRUE(vm.run(test, {}).getInteger()) << "Test Failed: " << test;
}
}
TEST_F(InterpreterTest, jit_pp) {
Config cfg;
cfg.jit = true;
cfg.directCall = true;
cfg.passParam = true;
VirtualMachine vm{runtime, cfg};
vm.load(module_);
vm.generateAllCode();
for (auto test : TEST_NAMES) {
EXPECT_TRUE(vm.run(test, {}).getInteger()) << "Test Failed: " << test;
}
}
TEST_F(InterpreterTest, jit_lvms) {
Config cfg;
cfg.jit = true;
cfg.directCall = true;
cfg.passParam = true;
cfg.lazyVmState = true;
VirtualMachine vm{runtime, cfg};
vm.load(module_);
vm.generateAllCode();
for (auto test : TEST_NAMES) {
EXPECT_TRUE(vm.run(test, {}).getInteger()) << "Test Failed: " << test;
}
}
TEST(MyTest, arguments) {
b9::VirtualMachine vm{runtime, {}};
auto m = std::make_shared<Module>();
Instruction i[] = {{ByteCode::PUSH_FROM_VAR, 0},
{ByteCode::PUSH_FROM_VAR, 1},
{ByteCode::INT_ADD},
{ByteCode::FUNCTION_RETURN},
END_SECTION};
m->functions.push_back(b9::FunctionSpec{"add_args", i, 2, 0});
vm.load(m);
auto r = vm.run("add_args", {{Value::integer, 1}, {Value::integer, 2}});
EXPECT_EQ(r, Value(Value::integer, 3));
}
extern "C" void b9_prim_print_string(ExecutionContext* context);
TEST(ObjectTest, allocateSomething) {
b9::VirtualMachine vm{runtime, {}};
auto m = std::make_shared<Module>();
Instruction i[] = {
{ByteCode::NEW_OBJECT}, // new object
{ByteCode::POP_INTO_VAR, 0}, // store object into var0
{ByteCode::STR_PUSH_CONSTANT, 0}, // push "voila"
{ByteCode::PUSH_FROM_VAR, 0}, // push var0 aka object
{ByteCode::POP_INTO_OBJECT, 0}, // pop "voila" into object at slot 0
{ByteCode::SYSTEM_COLLECT}, // GC. Object is kept alive by var0
{ByteCode::PUSH_FROM_VAR, 0}, // push object
{ByteCode::PUSH_FROM_OBJECT, 0}, // get the string back
{ByteCode::PRIMITIVE_CALL, 0}, // call b9_prim_print_string
{ByteCode::FUNCTION_RETURN}, // finish with constant 0
END_SECTION};
m->strings.push_back("Hello, World");
m->functions.push_back(b9::FunctionSpec{"allocate_object", i, 0, 1});
m->primitives.push_back(b9_prim_print_string);
vm.load(m);
Value r = vm.run("allocate_object", {});
EXPECT_EQ(r, Value(Value::integer, 0));
}
// clang-format off
std::vector<std::int32_t> integers = {
0, 1, -1, 42, -42,
std::numeric_limits<std::int32_t>::max(),
std::numeric_limits<std::int32_t>::min()
};
// clang-format on
TEST(DoubleTest, canonicalNan) {
EXPECT_TRUE(std::isnan(makeDouble(CANONICAL_NAN)));
}
TEST(ValueTest, integerConstructorRoundTrip) {
for (auto i : integers) {
Value value(Value::integer, i);
auto i2 = value.getInteger();
EXPECT_EQ(i, i2);
}
}
TEST(ValueTest, setIntegerRoundTrip) {
for (auto i : integers) {
Value value;
value.setInteger(i);
auto i2 = value.getInteger();
EXPECT_EQ(i, i2);
}
}
TEST(ValueTest, canonicalNan) {
EXPECT_EQ((CANONICAL_NAN & Double::SIGN_MASK), 0);
EXPECT_NE((CANONICAL_NAN & BoxTag::MASK), BoxTag::VALUE);
EXPECT_NE(makeDouble(CANONICAL_NAN), makeDouble(CANONICAL_NAN));
}
TEST(ValueTest, doubleRoundTrip) {
const std::vector<double> doubles = //
{0.0,
1.0,
43.21,
std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::max(),
std::numeric_limits<double>::min()};
for (auto d : doubles) {
for (auto sign : {+1.0, -1.0}) {
d *= sign;
Value value;
value.setDouble(d);
EXPECT_EQ(d, value.getDouble());
EXPECT_FALSE(value.isBoxedValue());
EXPECT_TRUE(value.isDouble());
}
}
}
TEST(ValueTest, signalingNanDouble) {
Value value;
value.setDouble(std::numeric_limits<double>::signaling_NaN());
EXPECT_TRUE(std::isnan(value.getDouble()));
EXPECT_FALSE(value.isBoxedValue());
EXPECT_NE(value.getDouble(), makeDouble(CANONICAL_NAN));
EXPECT_EQ(value.raw(), CANONICAL_NAN);
}
TEST(ValueTest, quietNanDouble) {
Value value;
value.setDouble(std::numeric_limits<double>::quiet_NaN());
EXPECT_TRUE(std::isnan(value.getDouble()));
EXPECT_FALSE(value.isBoxedValue());
EXPECT_NE(value.getDouble(), makeDouble(CANONICAL_NAN));
EXPECT_EQ(value.raw(), CANONICAL_NAN);
}
TEST(ValueTest, pointerRoundTrip) {
for (void* p : {(void*)0, (void*)1, (void*)(-1 & VALUE_MASK)}) {
Value value;
value.setPtr(p);
EXPECT_EQ(p, value.getPtr());
EXPECT_TRUE(value.isBoxedValue());
EXPECT_TRUE(value.isPtr());
}
}
} // namespace test
} // namespace b9
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "coreplugin.h"
#include "basefilefilter.h"
#include "locatorfiltertest.h"
#include <coreplugin/testdatadir.h>
#include <utils/fileutils.h>
#include <QDir>
#include <QTextStream>
#include <QtTest>
using namespace Core::Tests;
namespace {
QTC_DECLARE_MYTESTDATADIR("../../../../tests/locators/")
class MyBaseFileFilter : public Core::BaseFileFilter
{
public:
MyBaseFileFilter(const QStringList &theFiles)
{
files().clear();
files().append(theFiles);
BaseFileFilter::generateFileNames();
}
void refresh(QFutureInterface<void> &) {}
protected:
void updateFiles() {}
};
inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }
class ReferenceData
{
public:
ReferenceData() {}
ReferenceData(const QString &searchText, const ResultDataList &results)
: searchText(searchText), results(results) {}
QString searchText;
ResultDataList results;
};
} // anonymous namespace
Q_DECLARE_METATYPE(ReferenceData)
Q_DECLARE_METATYPE(QList<ReferenceData>)
void Core::Internal::CorePlugin::test_basefilefilter()
{
QFETCH(QStringList, testFiles);
QFETCH(QList<ReferenceData>, referenceDataList);
MyBaseFileFilter filter(testFiles);
BasicLocatorFilterTest test(&filter);
foreach (const ReferenceData &reference, referenceDataList) {
const QList<LocatorFilterEntry> filterEntries = test.matchesFor(reference.searchText);
const ResultDataList results = ResultData::fromFilterEntryList(filterEntries);
// QTextStream(stdout) << "----" << endl;
// ResultData::printFilterEntries(results);
QCOMPARE(results, reference.results);
}
}
void Core::Internal::CorePlugin::test_basefilefilter_data()
{
QTest::addColumn<QStringList>("testFiles");
QTest::addColumn<QList<ReferenceData> >("referenceDataList");
const QChar pathSeparator = QDir::separator();
const MyTestDataDir testDir(QLatin1String("testdata_basic"));
const QStringList testFiles = QStringList()
<< QDir::toNativeSeparators(testDir.file(QLatin1String("file.cpp")))
<< QDir::toNativeSeparators(testDir.file(QLatin1String("main.cpp")))
<< QDir::toNativeSeparators(testDir.file(QLatin1String("subdir/main.cpp")));
QStringList testFilesShort;
foreach (const QString &file, testFiles)
testFilesShort << Utils::FileUtils::shortNativePath(Utils::FileName::fromString(file));
QTest::newRow("BaseFileFilter-EmptyInput")
<< testFiles
<< (QList<ReferenceData>()
<< ReferenceData(
QString(),
(QList<ResultData>()
<< ResultData(_("file.cpp"), testFilesShort.at(0))
<< ResultData(_("main.cpp"), testFilesShort.at(1))
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
);
QTest::newRow("BaseFileFilter-InputIsFileName")
<< testFiles
<< (QList<ReferenceData>()
<< ReferenceData(
_("main.cpp"),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(1))
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
);
QTest::newRow("BaseFileFilter-InputIsFilePath")
<< testFiles
<< (QList<ReferenceData>()
<< ReferenceData(
QString(_("subdir") + pathSeparator + _("main.cpp")),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
);
QTest::newRow("BaseFileFilter-InputIsDirIsPath")
<< testFiles
<< (QList<ReferenceData>()
<< ReferenceData( _("subdir"), QList<ResultData>())
<< ReferenceData(
QString(_("subdir") + pathSeparator + _("main.cpp")),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
);
QTest::newRow("BaseFileFilter-InputIsFileNameFilePathFileName")
<< testFiles
<< (QList<ReferenceData>()
<< ReferenceData(
_("main.cpp"),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(1))
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
<< ReferenceData(
QString(_("subdir") + pathSeparator + _("main.cpp")),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
<< ReferenceData(
_("main.cpp"),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(1))
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
);
}
<commit_msg>Core: Buildfix for locator test<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "../coreplugin.h"
#include "basefilefilter.h"
#include "locatorfiltertest.h"
#include <coreplugin/testdatadir.h>
#include <utils/fileutils.h>
#include <QDir>
#include <QTextStream>
#include <QtTest>
using namespace Core::Tests;
namespace {
QTC_DECLARE_MYTESTDATADIR("../../../../tests/locators/")
class MyBaseFileFilter : public Core::BaseFileFilter
{
public:
MyBaseFileFilter(const QStringList &theFiles)
{
files().clear();
files().append(theFiles);
BaseFileFilter::generateFileNames();
}
void refresh(QFutureInterface<void> &) {}
protected:
void updateFiles() {}
};
inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }
class ReferenceData
{
public:
ReferenceData() {}
ReferenceData(const QString &searchText, const ResultDataList &results)
: searchText(searchText), results(results) {}
QString searchText;
ResultDataList results;
};
} // anonymous namespace
Q_DECLARE_METATYPE(ReferenceData)
Q_DECLARE_METATYPE(QList<ReferenceData>)
void Core::Internal::CorePlugin::test_basefilefilter()
{
QFETCH(QStringList, testFiles);
QFETCH(QList<ReferenceData>, referenceDataList);
MyBaseFileFilter filter(testFiles);
BasicLocatorFilterTest test(&filter);
foreach (const ReferenceData &reference, referenceDataList) {
const QList<LocatorFilterEntry> filterEntries = test.matchesFor(reference.searchText);
const ResultDataList results = ResultData::fromFilterEntryList(filterEntries);
// QTextStream(stdout) << "----" << endl;
// ResultData::printFilterEntries(results);
QCOMPARE(results, reference.results);
}
}
void Core::Internal::CorePlugin::test_basefilefilter_data()
{
QTest::addColumn<QStringList>("testFiles");
QTest::addColumn<QList<ReferenceData> >("referenceDataList");
const QChar pathSeparator = QDir::separator();
const MyTestDataDir testDir(QLatin1String("testdata_basic"));
const QStringList testFiles = QStringList()
<< QDir::toNativeSeparators(testDir.file(QLatin1String("file.cpp")))
<< QDir::toNativeSeparators(testDir.file(QLatin1String("main.cpp")))
<< QDir::toNativeSeparators(testDir.file(QLatin1String("subdir/main.cpp")));
QStringList testFilesShort;
foreach (const QString &file, testFiles)
testFilesShort << Utils::FileUtils::shortNativePath(Utils::FileName::fromString(file));
QTest::newRow("BaseFileFilter-EmptyInput")
<< testFiles
<< (QList<ReferenceData>()
<< ReferenceData(
QString(),
(QList<ResultData>()
<< ResultData(_("file.cpp"), testFilesShort.at(0))
<< ResultData(_("main.cpp"), testFilesShort.at(1))
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
);
QTest::newRow("BaseFileFilter-InputIsFileName")
<< testFiles
<< (QList<ReferenceData>()
<< ReferenceData(
_("main.cpp"),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(1))
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
);
QTest::newRow("BaseFileFilter-InputIsFilePath")
<< testFiles
<< (QList<ReferenceData>()
<< ReferenceData(
QString(_("subdir") + pathSeparator + _("main.cpp")),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
);
QTest::newRow("BaseFileFilter-InputIsDirIsPath")
<< testFiles
<< (QList<ReferenceData>()
<< ReferenceData( _("subdir"), QList<ResultData>())
<< ReferenceData(
QString(_("subdir") + pathSeparator + _("main.cpp")),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
);
QTest::newRow("BaseFileFilter-InputIsFileNameFilePathFileName")
<< testFiles
<< (QList<ReferenceData>()
<< ReferenceData(
_("main.cpp"),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(1))
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
<< ReferenceData(
QString(_("subdir") + pathSeparator + _("main.cpp")),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
<< ReferenceData(
_("main.cpp"),
(QList<ResultData>()
<< ResultData(_("main.cpp"), testFilesShort.at(1))
<< ResultData(_("main.cpp"), testFilesShort.at(2))))
);
}
<|endoftext|>
|
<commit_before>// Copyright 2015 Alessio Sclocco <[email protected]>
//
// 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 <string>
#ifndef BITS_HPP
#define BITS_HPP
namespace isa {
namespace OpenCL {
inline void getBit(std::string & code, const std::string & value, const std::string & bit);
inline void setBit(std::string & code, const std::string & value, const std::string & newBit, const std::string & bit);
// Implementations
inline void getBit(std::string & code, const std::string & value, const std::string & bit) {
code += "convert_uchar((" + value + " >> (" + bit + ")) & 1)";
}
inline void setBit(std::string & code, const std::string & value, const std::string & newBit, const std::string & bit) {
code += value + " ^= (-(" + newBit + ") ^ " + value + ") & (1 << (" + bit + "));\n";
}
} // OpenCL
} // isa
#endif // BITS_HPP
<commit_msg>Decided that is better to have getBit() and setBit() to return a function instead of modifying one, to have more flexibility.<commit_after>// Copyright 2015 Alessio Sclocco <[email protected]>
//
// 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 <string>
#ifndef BITS_HPP
#define BITS_HPP
namespace isa {
namespace OpenCL {
inline std::string getBit(const std::string & value, const std::string & bit);
inline std::string setBit(const std::string & value, const std::string & newBit, const std::string & bit);
// Implementations
inline std::string getBit(const std::string & value, const std::string & bit) {
return "convert_uchar((" + value + " >> (" + bit + ")) & 1)";
}
inline std::string setBit(const std::string & value, const std::string & newBit, const std::string & bit) {
return value + " ^= (-(" + newBit + ") ^ " + value + ") & (1 << (" + bit + "));\n";
}
} // OpenCL
} // isa
#endif // BITS_HPP
<|endoftext|>
|
<commit_before>#include "control/ControlSystem.hpp"
#include "safety/DeltaSafetyProperties.hpp"
#include "sequencer/MoveBlockSequence.hpp"
#include "sequencer/MainSequence.hpp"
#include <eeros/hal/HAL.hpp>
#include <eeros/safety/SafetySystem.hpp>
#include <eeros/logger/Logger.hpp>
#include <eeros/logger/StreamLogWriter.hpp>
#include <eeros/logger/SysLogWriter.hpp>
#include <eeros/sequencer/Sequencer.hpp>
#include <iostream>
#include <unistd.h>
#include <signal.h>
using namespace eeduro;
using namespace eeduro::delta;
using namespace eeros;
using namespace eeros::logger;
using namespace eeros::hal;
using namespace eeros::safety;
using namespace eeros::sequencer;
volatile bool running = true;
void signalHandler(int signum) {
running = false;
}
int main(int argc, char* argv[]) {
signal(SIGINT, signalHandler);
StreamLogWriter w(std::cout);
SysLogWriter s("delta");
w.show();
s.show();
Logger<LogWriter>::setDefaultWriter(&w);
// Logger<LogWriter>::setDefaultWriter(&s);
Logger<LogWriter> log('M');
log.trace() << "Application eeduro-delta started...";
// create control system
ControlSystem controlSys;
// initialize hardware
controlSys.initBoard();
controlSys.mouse.j.on_button([&](int x, bool value) {
if (x == BTN_LEFT || x == BTN_RIGHT)
controlSys.board.power_out[0] = value;
controlSys.board.power_out[1] = value;
});
// create safety system
DeltaSafetyProperties safetyProperties(&controlSys);
SafetySystem safetySys(safetyProperties, dt);
// create sequencer
Sequencer sequencer;
MainSequence mainSequence(&sequencer, &controlSys, &safetySys);
sequencer.start(&mainSequence);
// constexpr int nofpos = 6;
// double x[nofpos] = {0.01, 0.01, -0.01, -0.01, 0.0, 0.0};
// double y[nofpos] = {-0.01, 0.01, 0.01, -0.01, 0.0, 0.0};
// double z[nofpos] = {-0.01, -0.02, -0.01, -0.05, -0.06, -0.05};
// double phi[nofpos] = {0.1, 0.5, 0.1, 0.5, 0.1, 0.5};
// int i = 0;
// AxisVector limit = {0, 100, 100, 100};
// controlSys.forceLimitation.setLimit(-limit, limit);
while(running && sequencer.getState() != state::terminated) {
// std::cout << "TCP z: " << controlSys.pathPlanner.getPosOut().getSignal().getValue()[2] << std::endl;
// std::cout << controlSys.joystick.getOut().getSignal().getValue() << std::endl;
// std::cout << controlSys.inputSwitch.getOut().getSignal().getValue() << std::endl;
std::cout << controlSys.inputSwitch.getOut().getSignal().getValue() << " | ";
std::cout << controlSys.directKin.getOut().getSignal().getValue() << " | ";
std::cout << controlSys.angleGear.getOut().getSignal().getValue() << std::endl;
// if(controlSys.axisHomed()) {
// controlSys.goToPos(0, 0, z[i], 0.2);
// controlSys.forceLimitation.enable();
// controlSys.goToPos(0, 0, -0.03, 0.5);
// i = (i + 1) % nofpos;
// }
usleep(1000000);
}
log.info() << "Shuting down...";
safetySys.triggerEvent(doParking);
safetySys.shutdown();
controlSys.disableAxis();
controlSys.stop();
return 0;
}
<commit_msg>debug output removed<commit_after>#include "control/ControlSystem.hpp"
#include "safety/DeltaSafetyProperties.hpp"
#include "sequencer/MoveBlockSequence.hpp"
#include "sequencer/MainSequence.hpp"
#include <eeros/hal/HAL.hpp>
#include <eeros/safety/SafetySystem.hpp>
#include <eeros/logger/Logger.hpp>
#include <eeros/logger/StreamLogWriter.hpp>
#include <eeros/logger/SysLogWriter.hpp>
#include <eeros/sequencer/Sequencer.hpp>
#include <iostream>
#include <unistd.h>
#include <signal.h>
using namespace eeduro;
using namespace eeduro::delta;
using namespace eeros;
using namespace eeros::logger;
using namespace eeros::hal;
using namespace eeros::safety;
using namespace eeros::sequencer;
volatile bool running = true;
void signalHandler(int signum) {
running = false;
}
int main(int argc, char* argv[]) {
signal(SIGINT, signalHandler);
StreamLogWriter w(std::cout);
SysLogWriter s("delta");
w.show();
s.show();
Logger<LogWriter>::setDefaultWriter(&w);
// Logger<LogWriter>::setDefaultWriter(&s);
Logger<LogWriter> log('M');
log.trace() << "Application eeduro-delta started...";
// create control system
ControlSystem controlSys;
// initialize hardware
controlSys.initBoard();
controlSys.mouse.j.on_button([&](int x, bool value) {
if (x == BTN_LEFT || x == BTN_RIGHT)
controlSys.board.power_out[0] = value;
controlSys.board.power_out[1] = value;
});
// create safety system
DeltaSafetyProperties safetyProperties(&controlSys);
SafetySystem safetySys(safetyProperties, dt);
// create sequencer
Sequencer sequencer;
MainSequence mainSequence(&sequencer, &controlSys, &safetySys);
sequencer.start(&mainSequence);
while(running && sequencer.getState() != state::terminated) {
usleep(1000000);
}
log.info() << "Shuting down...";
safetySys.triggerEvent(doParking);
safetySys.shutdown();
controlSys.disableAxis();
controlSys.stop();
return 0;
}
<|endoftext|>
|
<commit_before>#include "Dictionary.h"
#include <string>
#include <vector>
#include <map>
#include "WordNoun.h"
#include "WordAdjunct.h"
#include "WordModifier.h"
#include "Grammar.h"
// We will never instantiate you
Dictionary::Dictionary() {}
// =====
// Nouns
// =====
// Vector
std::vector<WordNoun*> Dictionary::registeredNouns;
// Add
gmr::NounId Dictionary::addNoun(WordNoun* newNoun)
{
registeredNouns.push_back(newNoun);
return registeredNouns.size() - 1;
}
// Get
WordNoun* Dictionary::getNoun(gmr::NounId nounId)
{
return registeredNouns.at(nounId);
}
// Number of
std::size_t Dictionary::numNouns()
{
return registeredNouns.size();
}
// ========
// Adjuncts
// ========
// Vector
std::vector<WordAdjunct*> Dictionary::registeredAdjuncts;
// Add
gmr::AdjunctId Dictionary::addAdjunct(WordAdjunct* newAdjunct)
{
registeredAdjuncts.push_back(newAdjunct);
return registeredAdjuncts.size() - 1;
}
// Get
WordAdjunct* Dictionary::getAdjunct(gmr::AdjunctId adjunctId)
{
return registeredAdjuncts.at(adjunctId);
}
// Number of
std::size_t Dictionary::numAdjuncts()
{
return registeredAdjuncts.size();
}
// =========
// Modifiers
// =========
// Vector
std::vector<WordModifier*> Dictionary::registeredModifiers;
// Add
gmr::ModifierId Dictionary::addModifier(WordModifier* newModifier)
{
registeredModifiers.push_back(newModifier);
return registeredModifiers.size() - 1;
}
// Get
WordModifier* Dictionary::getModifier(gmr::ModifierId modifierId)
{
return registeredModifiers.at(modifierId);
}
// Number of
std::size_t Dictionary::numModifiers()
{
return registeredModifiers.size();
}
// ========
// Articles
// ========
// I'm different!
// Vector
std::map<std::string, gmr::ArticleProperties> Dictionary::registeredArticles;
// Add by name
void Dictionary::addArticle(std::string name, gmr::ArticleType mtype, gmr::ArticleQuantity mquantity)
{
gmr::ArticleProperties a;
a.type = mtype;
a.quantity = mquantity;
registeredArticles.insert(std::pair<std::string, gmr::ArticleProperties>(name, a));
}
// Get by name
gmr::ArticleProperties Dictionary::getArticle(std::string name)
{
std::map<std::string, gmr::ArticleProperties>::iterator focus = registeredArticles.find(name);
if(focus == registeredArticles.end())
{
// Dis is broken fix me
//return //
}
return focus->second;
}
<commit_msg>Added default return value<commit_after>#include "Dictionary.h"
#include <string>
#include <vector>
#include <map>
#include "WordNoun.h"
#include "WordAdjunct.h"
#include "WordModifier.h"
#include "Grammar.h"
// We will never instantiate you
Dictionary::Dictionary() {}
// =====
// Nouns
// =====
// Vector
std::vector<WordNoun*> Dictionary::registeredNouns;
// Add
gmr::NounId Dictionary::addNoun(WordNoun* newNoun)
{
registeredNouns.push_back(newNoun);
return registeredNouns.size() - 1;
}
// Get
WordNoun* Dictionary::getNoun(gmr::NounId nounId)
{
return registeredNouns.at(nounId);
}
// Number of
std::size_t Dictionary::numNouns()
{
return registeredNouns.size();
}
// ========
// Adjuncts
// ========
// Vector
std::vector<WordAdjunct*> Dictionary::registeredAdjuncts;
// Add
gmr::AdjunctId Dictionary::addAdjunct(WordAdjunct* newAdjunct)
{
registeredAdjuncts.push_back(newAdjunct);
return registeredAdjuncts.size() - 1;
}
// Get
WordAdjunct* Dictionary::getAdjunct(gmr::AdjunctId adjunctId)
{
return registeredAdjuncts.at(adjunctId);
}
// Number of
std::size_t Dictionary::numAdjuncts()
{
return registeredAdjuncts.size();
}
// =========
// Modifiers
// =========
// Vector
std::vector<WordModifier*> Dictionary::registeredModifiers;
// Add
gmr::ModifierId Dictionary::addModifier(WordModifier* newModifier)
{
registeredModifiers.push_back(newModifier);
return registeredModifiers.size() - 1;
}
// Get
WordModifier* Dictionary::getModifier(gmr::ModifierId modifierId)
{
return registeredModifiers.at(modifierId);
}
// Number of
std::size_t Dictionary::numModifiers()
{
return registeredModifiers.size();
}
// ========
// Articles
// ========
// I'm different!
// Vector
std::map<std::string, gmr::ArticleProperties> Dictionary::registeredArticles;
// Add by name
void Dictionary::addArticle(std::string name, gmr::ArticleType mtype, gmr::ArticleQuantity mquantity)
{
gmr::ArticleProperties a;
a.type = mtype;
a.quantity = mquantity;
registeredArticles.insert(std::pair<std::string, gmr::ArticleProperties>(name, a));
}
// Get by name
gmr::ArticleProperties Dictionary::getArticle(std::string name)
{
std::map<std::string, gmr::ArticleProperties>::iterator focus = registeredArticles.find(name);
if(focus == registeredArticles.end())
{
// Returns a default value
gmr::ArticleProperties erroneous;
erroneous.type = gmr::indefinite;
erroneous.quantity = gmr::mas;
return erroneous;
}
return focus->second;
}
<|endoftext|>
|
<commit_before>/*
* (C) Copyright 2013 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#include "HttpEndPoint.hpp"
#include "KmsMediaHttpEndPointType_constants.h"
#include "KmsMediaHttpEndPointType_types.h"
#include "KmsMediaDataType_constants.h"
#include "KmsMediaErrorCodes_constants.h"
#include "KmsMediaSessionEndPointType_constants.h"
#include "utils/utils.hpp"
#include "utils/marshalling.hpp"
#include "protocol/TBinaryProtocol.h"
#include "transport/TBufferTransports.h"
#define GST_CAT_DEFAULT kurento_http_end_point
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoHttpEndPoint"
#define DISCONNECTION_TIMEOUT 2 /* seconds */
#define REGISTER_TIMEOUT 3 /* seconds */
#define TERMINATE_ON_EOS_DEFAULT false;
using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::protocol::TBinaryProtocol;
namespace kurento
{
void
http_end_point_raise_petition_event (HttpEndPoint *httpEp, KmsHttpEndPointAction action)
{
if (!g_atomic_int_compare_and_exchange (& (httpEp->sessionStarted), 0, 1) )
return;
if (action == KMS_HTTP_END_POINT_ACTION_UNDEFINED) {
GST_ERROR ("Invalid or unexpected request received");
// TODO: Raise error to remote client
return;
}
httpEp->sendEvent (
g_KmsMediaSessionEndPointType_constants.EVENT_MEDIA_SESSION_START);
}
static void
action_requested_cb (KmsHttpEPServer *server, const gchar *uri,
KmsHttpEndPointAction action, gpointer data)
{
HttpEndPoint *httpEp = (HttpEndPoint *) data;
std::string uriStr = uri;
std::string url = httpEp->getUrl();
GST_DEBUG ("Action requested URI %s", uriStr.c_str() );
if (url.size() <= uriStr.size() )
return;
/* Remove the initial "http://host:port" to compare the uri */
std::string substr = url.substr (url.size() - uriStr.size(),
std::string::npos);
if (substr.compare (uriStr) != 0)
return;
http_end_point_raise_petition_event (httpEp, action);
}
static std::string
getUriFromUrl (std::string url)
{
std::string uri;
gboolean host_read = FALSE;
/* skip first 7 characters in the url regarding the protocol "http://" */
if (url.size() < 7) {
GST_ERROR ("Invalid URL %s", url.c_str() );
return NULL;
}
for ( guint i = 7; i < url.size(); i++) {
gchar c = url.at (i);
if (!host_read) {
if (c == '/') {
/* URL has no port */
uri = url.substr (i, std::string::npos);
break;
} else if (c == ':') {
/* skip port number */
host_read = TRUE;
continue;
} else
continue;
}
if (c != '/')
continue;
uri = url.substr (i, std::string::npos);
break;
}
return uri;
}
void
kurento_http_end_point_raise_session_terminated_event (HttpEndPoint *httpEp, const gchar *uri)
{
std::string uriStr = uri;
if (httpEp->url.size() <= uriStr.size() )
return;
/* Remove the initial "http://host:port" to compare the uri */
std::string substr = httpEp->url.substr (httpEp->url.size() - uriStr.size(),
std::string::npos);
if (substr.compare (uriStr) != 0)
return;
GST_DEBUG ("Session terminated URI %s", uriStr.c_str() );
if (!g_atomic_int_compare_and_exchange (& (httpEp->sessionStarted), 1, 0) )
return;
httpEp->sendEvent (
g_KmsMediaSessionEndPointType_constants.EVENT_MEDIA_SESSION_COMPLETE);
}
static void
url_removed_cb (KmsHttpEPServer *server, const gchar *uri, gpointer data)
{
kurento_http_end_point_raise_session_terminated_event ( (HttpEndPoint *) data,
uri);
}
static void
url_expired_cb (KmsHttpEPServer *server, const gchar *uri, gpointer data)
{
kurento_http_end_point_raise_session_terminated_event ( (HttpEndPoint *) data,
uri);
}
struct MainLoopData {
gpointer data;
GSourceFunc func;
GDestroyNotify destroy;
Glib::Mutex *mutex;
};
static gboolean
main_loop_wrapper_func (gpointer data)
{
struct MainLoopData *mdata = (struct MainLoopData *) data;
return mdata->func (mdata->data);
}
static void
main_loop_data_destroy (gpointer data)
{
struct MainLoopData *mdata = (struct MainLoopData *) data;
if (mdata->destroy != NULL)
mdata->destroy (mdata->data);
mdata->mutex->unlock();
g_slice_free (struct MainLoopData, mdata);
}
static void
operate_in_main_loop_context (GSourceFunc func, gpointer data,
GDestroyNotify destroy)
{
struct MainLoopData *mdata;
Glib::Mutex mutex;
mdata = g_slice_new (struct MainLoopData);
mdata->data = data;
mdata->func = func;
mdata->destroy = destroy;
mdata->mutex = &mutex;
mutex.lock ();
g_idle_add_full (G_PRIORITY_HIGH_IDLE, main_loop_wrapper_func, mdata,
main_loop_data_destroy);
mutex.lock ();
}
gboolean
init_http_end_point (gpointer data)
{
HttpEndPoint *httpEp = (HttpEndPoint *) data;
std::string uri;
const gchar *url;
gchar *c_uri;
gchar *addr;
guint port;
httpEp->actionRequestedHandlerId = g_signal_connect (httpepserver, "action-requested",
G_CALLBACK (action_requested_cb), httpEp);
httpEp->urlRemovedHandlerId = g_signal_connect (httpepserver, "url-removed",
G_CALLBACK (url_removed_cb), httpEp);
httpEp->urlExpiredHandlerId = g_signal_connect (httpepserver, "url-expired",
G_CALLBACK (url_expired_cb), httpEp);
url = kms_http_ep_server_register_end_point (httpepserver, httpEp->element,
httpEp->disconnectionTimeout);
if (url == NULL)
return FALSE;
g_object_get (G_OBJECT (httpepserver), "announced-address", &addr, "port", &port,
NULL);
c_uri = g_strdup_printf ("http://%s:%d%s", addr, port, url);
uri = c_uri;
g_free (addr);
g_free (c_uri);
httpEp->setUrl (uri);
httpEp->urlSet = true;
return FALSE;
}
gboolean
dispose_http_end_point (gpointer data)
{
HttpEndPoint *httpEp = (HttpEndPoint *) data;
g_signal_handler_disconnect (httpepserver, httpEp->actionRequestedHandlerId);
g_signal_handler_disconnect (httpepserver, httpEp->urlExpiredHandlerId);
g_signal_handler_disconnect (httpepserver, httpEp->urlRemovedHandlerId);
std::string uri = getUriFromUrl (httpEp->url);
if (!uri.empty() )
kms_http_ep_server_unregister_end_point (httpepserver, uri.c_str() );
return FALSE;
}
void
kurento_http_end_point_eos_detected_cb (GstElement *element, gpointer data)
{
HttpEndPoint *httpEp = (HttpEndPoint *) data;
httpEp->sendEvent (
g_KmsMediaHttpEndPointType_constants.EVENT_EOS_DETECTED);
}
void
HttpEndPoint::init (std::shared_ptr<MediaPipeline> parent,
guint disconnectionTimeout, bool terminateOnEOS,
KmsMediaProfile profile)
throw (KmsMediaServerException)
{
element = gst_element_factory_make ("httpendpoint", NULL);
g_object_set ( G_OBJECT (element), "accept-eos", terminateOnEOS, NULL);
switch (profile.mediaMuxer) {
case KmsMediaMuxer::WEBM:
//value 0 means KMS_RECORDING_PROFILE_WEBM
g_object_set ( G_OBJECT (element), "profile", 0, NULL);
GST_INFO ("Set WEBM profile");
break;
case KmsMediaMuxer::MP4:
//value 1 means KMS_RECORDING_PROFILE_MP4
g_object_set ( G_OBJECT (element), "profile", 1, NULL);
GST_INFO ("Set MP4 profile");
break;
}
g_object_ref (element);
gst_bin_add (GST_BIN (parent->pipeline), element);
gst_element_sync_state_with_parent (element);
g_signal_connect (element, "eos-detected",
G_CALLBACK (kurento_http_end_point_eos_detected_cb), this);
this->disconnectionTimeout = disconnectionTimeout;
operate_in_main_loop_context (init_http_end_point, this, NULL);
if (!urlSet) {
KmsMediaServerException except;
createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.HTTP_END_POINT_REGISTRATION_ERROR,
"Cannot register HttpEndPoint");
throw except;
}
}
KmsMediaHttpEndPointConstructorParams
unmarshalKmsMediaHttpEndPointConstructorParams (std::string data)
throw (KmsMediaServerException)
{
KmsMediaHttpEndPointConstructorParams params;
boost::shared_ptr<TMemoryBuffer> transport;
try {
transport = boost::shared_ptr<TMemoryBuffer> (new TMemoryBuffer ( (uint8_t *) data.data(), data.size () ) );
TBinaryProtocol protocol = TBinaryProtocol (transport);
params.read (&protocol);
} catch (...) {
KmsMediaServerException except;
createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.UNMARSHALL_ERROR,
"Cannot unmarshal KmsMediaHttpEndPointConstructorParams");
throw except;
}
return params;
}
HttpEndPoint::HttpEndPoint (MediaSet &mediaSet,
std::shared_ptr<MediaPipeline> parent,
const std::map<std::string, KmsMediaParam> ¶ms)
throw (KmsMediaServerException)
: EndPoint (mediaSet, parent, g_KmsMediaHttpEndPointType_constants.TYPE_NAME,
params)
{
const KmsMediaParam *p;
KmsMediaHttpEndPointConstructorParams httpEpParams;
guint disconnectionTimeout = DISCONNECTION_TIMEOUT;
bool terminateOnEOS = TERMINATE_ON_EOS_DEFAULT;
KmsMediaProfile profile;
profile.mediaMuxer = KmsMediaMuxer::WEBM;
p = getParam (params, g_KmsMediaHttpEndPointType_constants.CONSTRUCTOR_PARAMS_DATA_TYPE);
if (p != NULL) {
httpEpParams = unmarshalKmsMediaHttpEndPointConstructorParams (p->data);
if (httpEpParams.__isset.disconnectionTimeout) {
disconnectionTimeout = httpEpParams.disconnectionTimeout;
}
if (httpEpParams.__isset.terminateOnEOS)
terminateOnEOS = httpEpParams.terminateOnEOS;
if (httpEpParams.__isset.profileType)
profile = httpEpParams.profileType;
}
init (parent, disconnectionTimeout, terminateOnEOS, profile);
}
HttpEndPoint::~HttpEndPoint() throw ()
{
operate_in_main_loop_context (dispose_http_end_point, this, NULL);
gst_bin_remove (GST_BIN ( (
(std::shared_ptr<MediaPipeline> &) parent)->pipeline), element);
gst_element_set_state (element, GST_STATE_NULL);
g_object_unref (element);
}
std::string
HttpEndPoint::getUrl ()
{
return url;
}
void
HttpEndPoint::setUrl (const std::string &newUrl)
{
url = newUrl;
}
void
HttpEndPoint::invoke (KmsMediaInvocationReturn &_return,
const std::string &command,
const std::map<std::string, KmsMediaParam> ¶ms)
throw (KmsMediaServerException)
{
if (g_KmsMediaHttpEndPointType_constants.GET_URL.compare (command) == 0)
createStringInvocationReturn (_return, url);
else
EndPoint::invoke (_return, command, params);
}
void
HttpEndPoint::subscribe (std::string &_return, const std::string &eventType, const std::string &handlerAddress, const int32_t handlerPort)
throw (KmsMediaServerException)
{
if (g_KmsMediaSessionEndPointType_constants.EVENT_MEDIA_SESSION_START.compare (
eventType) == 0)
mediaHandlerManager.addMediaHandler (_return, eventType, handlerAddress,
handlerPort);
else if (g_KmsMediaSessionEndPointType_constants.EVENT_MEDIA_SESSION_COMPLETE.compare (
eventType) == 0)
mediaHandlerManager.addMediaHandler (_return, eventType, handlerAddress,
handlerPort);
else if (g_KmsMediaHttpEndPointType_constants.EVENT_EOS_DETECTED.compare (
eventType) == 0)
mediaHandlerManager.addMediaHandler (_return, eventType, handlerAddress,
handlerPort);
else
EndPoint::subscribe (_return, eventType, handlerAddress, handlerPort);
}
HttpEndPoint::StaticConstructor HttpEndPoint::staticConstructor;
HttpEndPoint::StaticConstructor::StaticConstructor()
{
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
} // kurento
<commit_msg>HttpEndPoint: Do not attach to eos-detected signal that has been removed<commit_after>/*
* (C) Copyright 2013 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#include "HttpEndPoint.hpp"
#include "KmsMediaHttpEndPointType_constants.h"
#include "KmsMediaHttpEndPointType_types.h"
#include "KmsMediaDataType_constants.h"
#include "KmsMediaErrorCodes_constants.h"
#include "KmsMediaSessionEndPointType_constants.h"
#include "utils/utils.hpp"
#include "utils/marshalling.hpp"
#include "protocol/TBinaryProtocol.h"
#include "transport/TBufferTransports.h"
#define GST_CAT_DEFAULT kurento_http_end_point
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoHttpEndPoint"
#define DISCONNECTION_TIMEOUT 2 /* seconds */
#define REGISTER_TIMEOUT 3 /* seconds */
#define TERMINATE_ON_EOS_DEFAULT false;
using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::protocol::TBinaryProtocol;
namespace kurento
{
void
http_end_point_raise_petition_event (HttpEndPoint *httpEp, KmsHttpEndPointAction action)
{
if (!g_atomic_int_compare_and_exchange (& (httpEp->sessionStarted), 0, 1) )
return;
if (action == KMS_HTTP_END_POINT_ACTION_UNDEFINED) {
GST_ERROR ("Invalid or unexpected request received");
// TODO: Raise error to remote client
return;
}
httpEp->sendEvent (
g_KmsMediaSessionEndPointType_constants.EVENT_MEDIA_SESSION_START);
}
static void
action_requested_cb (KmsHttpEPServer *server, const gchar *uri,
KmsHttpEndPointAction action, gpointer data)
{
HttpEndPoint *httpEp = (HttpEndPoint *) data;
std::string uriStr = uri;
std::string url = httpEp->getUrl();
GST_DEBUG ("Action requested URI %s", uriStr.c_str() );
if (url.size() <= uriStr.size() )
return;
/* Remove the initial "http://host:port" to compare the uri */
std::string substr = url.substr (url.size() - uriStr.size(),
std::string::npos);
if (substr.compare (uriStr) != 0)
return;
http_end_point_raise_petition_event (httpEp, action);
}
static std::string
getUriFromUrl (std::string url)
{
std::string uri;
gboolean host_read = FALSE;
/* skip first 7 characters in the url regarding the protocol "http://" */
if (url.size() < 7) {
GST_ERROR ("Invalid URL %s", url.c_str() );
return NULL;
}
for ( guint i = 7; i < url.size(); i++) {
gchar c = url.at (i);
if (!host_read) {
if (c == '/') {
/* URL has no port */
uri = url.substr (i, std::string::npos);
break;
} else if (c == ':') {
/* skip port number */
host_read = TRUE;
continue;
} else
continue;
}
if (c != '/')
continue;
uri = url.substr (i, std::string::npos);
break;
}
return uri;
}
void
kurento_http_end_point_raise_session_terminated_event (HttpEndPoint *httpEp, const gchar *uri)
{
std::string uriStr = uri;
if (httpEp->url.size() <= uriStr.size() )
return;
/* Remove the initial "http://host:port" to compare the uri */
std::string substr = httpEp->url.substr (httpEp->url.size() - uriStr.size(),
std::string::npos);
if (substr.compare (uriStr) != 0)
return;
GST_DEBUG ("Session terminated URI %s", uriStr.c_str() );
if (!g_atomic_int_compare_and_exchange (& (httpEp->sessionStarted), 1, 0) )
return;
httpEp->sendEvent (
g_KmsMediaSessionEndPointType_constants.EVENT_MEDIA_SESSION_COMPLETE);
}
static void
url_removed_cb (KmsHttpEPServer *server, const gchar *uri, gpointer data)
{
kurento_http_end_point_raise_session_terminated_event ( (HttpEndPoint *) data,
uri);
}
static void
url_expired_cb (KmsHttpEPServer *server, const gchar *uri, gpointer data)
{
kurento_http_end_point_raise_session_terminated_event ( (HttpEndPoint *) data,
uri);
}
struct MainLoopData {
gpointer data;
GSourceFunc func;
GDestroyNotify destroy;
Glib::Mutex *mutex;
};
static gboolean
main_loop_wrapper_func (gpointer data)
{
struct MainLoopData *mdata = (struct MainLoopData *) data;
return mdata->func (mdata->data);
}
static void
main_loop_data_destroy (gpointer data)
{
struct MainLoopData *mdata = (struct MainLoopData *) data;
if (mdata->destroy != NULL)
mdata->destroy (mdata->data);
mdata->mutex->unlock();
g_slice_free (struct MainLoopData, mdata);
}
static void
operate_in_main_loop_context (GSourceFunc func, gpointer data,
GDestroyNotify destroy)
{
struct MainLoopData *mdata;
Glib::Mutex mutex;
mdata = g_slice_new (struct MainLoopData);
mdata->data = data;
mdata->func = func;
mdata->destroy = destroy;
mdata->mutex = &mutex;
mutex.lock ();
g_idle_add_full (G_PRIORITY_HIGH_IDLE, main_loop_wrapper_func, mdata,
main_loop_data_destroy);
mutex.lock ();
}
gboolean
init_http_end_point (gpointer data)
{
HttpEndPoint *httpEp = (HttpEndPoint *) data;
std::string uri;
const gchar *url;
gchar *c_uri;
gchar *addr;
guint port;
httpEp->actionRequestedHandlerId = g_signal_connect (httpepserver, "action-requested",
G_CALLBACK (action_requested_cb), httpEp);
httpEp->urlRemovedHandlerId = g_signal_connect (httpepserver, "url-removed",
G_CALLBACK (url_removed_cb), httpEp);
httpEp->urlExpiredHandlerId = g_signal_connect (httpepserver, "url-expired",
G_CALLBACK (url_expired_cb), httpEp);
url = kms_http_ep_server_register_end_point (httpepserver, httpEp->element,
httpEp->disconnectionTimeout);
if (url == NULL)
return FALSE;
g_object_get (G_OBJECT (httpepserver), "announced-address", &addr, "port", &port,
NULL);
c_uri = g_strdup_printf ("http://%s:%d%s", addr, port, url);
uri = c_uri;
g_free (addr);
g_free (c_uri);
httpEp->setUrl (uri);
httpEp->urlSet = true;
return FALSE;
}
gboolean
dispose_http_end_point (gpointer data)
{
HttpEndPoint *httpEp = (HttpEndPoint *) data;
g_signal_handler_disconnect (httpepserver, httpEp->actionRequestedHandlerId);
g_signal_handler_disconnect (httpepserver, httpEp->urlExpiredHandlerId);
g_signal_handler_disconnect (httpepserver, httpEp->urlRemovedHandlerId);
std::string uri = getUriFromUrl (httpEp->url);
if (!uri.empty() )
kms_http_ep_server_unregister_end_point (httpepserver, uri.c_str() );
return FALSE;
}
void
HttpEndPoint::init (std::shared_ptr<MediaPipeline> parent,
guint disconnectionTimeout, bool terminateOnEOS,
KmsMediaProfile profile)
throw (KmsMediaServerException)
{
element = gst_element_factory_make ("httpendpoint", NULL);
g_object_set ( G_OBJECT (element), "accept-eos", terminateOnEOS, NULL);
switch (profile.mediaMuxer) {
case KmsMediaMuxer::WEBM:
//value 0 means KMS_RECORDING_PROFILE_WEBM
g_object_set ( G_OBJECT (element), "profile", 0, NULL);
GST_INFO ("Set WEBM profile");
break;
case KmsMediaMuxer::MP4:
//value 1 means KMS_RECORDING_PROFILE_MP4
g_object_set ( G_OBJECT (element), "profile", 1, NULL);
GST_INFO ("Set MP4 profile");
break;
}
g_object_ref (element);
gst_bin_add (GST_BIN (parent->pipeline), element);
gst_element_sync_state_with_parent (element);
this->disconnectionTimeout = disconnectionTimeout;
operate_in_main_loop_context (init_http_end_point, this, NULL);
if (!urlSet) {
KmsMediaServerException except;
createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.HTTP_END_POINT_REGISTRATION_ERROR,
"Cannot register HttpEndPoint");
throw except;
}
}
KmsMediaHttpEndPointConstructorParams
unmarshalKmsMediaHttpEndPointConstructorParams (std::string data)
throw (KmsMediaServerException)
{
KmsMediaHttpEndPointConstructorParams params;
boost::shared_ptr<TMemoryBuffer> transport;
try {
transport = boost::shared_ptr<TMemoryBuffer> (new TMemoryBuffer ( (uint8_t *) data.data(), data.size () ) );
TBinaryProtocol protocol = TBinaryProtocol (transport);
params.read (&protocol);
} catch (...) {
KmsMediaServerException except;
createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.UNMARSHALL_ERROR,
"Cannot unmarshal KmsMediaHttpEndPointConstructorParams");
throw except;
}
return params;
}
HttpEndPoint::HttpEndPoint (MediaSet &mediaSet,
std::shared_ptr<MediaPipeline> parent,
const std::map<std::string, KmsMediaParam> ¶ms)
throw (KmsMediaServerException)
: EndPoint (mediaSet, parent, g_KmsMediaHttpEndPointType_constants.TYPE_NAME,
params)
{
const KmsMediaParam *p;
KmsMediaHttpEndPointConstructorParams httpEpParams;
guint disconnectionTimeout = DISCONNECTION_TIMEOUT;
bool terminateOnEOS = TERMINATE_ON_EOS_DEFAULT;
KmsMediaProfile profile;
profile.mediaMuxer = KmsMediaMuxer::WEBM;
p = getParam (params, g_KmsMediaHttpEndPointType_constants.CONSTRUCTOR_PARAMS_DATA_TYPE);
if (p != NULL) {
httpEpParams = unmarshalKmsMediaHttpEndPointConstructorParams (p->data);
if (httpEpParams.__isset.disconnectionTimeout) {
disconnectionTimeout = httpEpParams.disconnectionTimeout;
}
if (httpEpParams.__isset.terminateOnEOS)
terminateOnEOS = httpEpParams.terminateOnEOS;
if (httpEpParams.__isset.profileType)
profile = httpEpParams.profileType;
}
init (parent, disconnectionTimeout, terminateOnEOS, profile);
}
HttpEndPoint::~HttpEndPoint() throw ()
{
operate_in_main_loop_context (dispose_http_end_point, this, NULL);
gst_bin_remove (GST_BIN ( (
(std::shared_ptr<MediaPipeline> &) parent)->pipeline), element);
gst_element_set_state (element, GST_STATE_NULL);
g_object_unref (element);
}
std::string
HttpEndPoint::getUrl ()
{
return url;
}
void
HttpEndPoint::setUrl (const std::string &newUrl)
{
url = newUrl;
}
void
HttpEndPoint::invoke (KmsMediaInvocationReturn &_return,
const std::string &command,
const std::map<std::string, KmsMediaParam> ¶ms)
throw (KmsMediaServerException)
{
if (g_KmsMediaHttpEndPointType_constants.GET_URL.compare (command) == 0)
createStringInvocationReturn (_return, url);
else
EndPoint::invoke (_return, command, params);
}
void
HttpEndPoint::subscribe (std::string &_return, const std::string &eventType, const std::string &handlerAddress, const int32_t handlerPort)
throw (KmsMediaServerException)
{
if (g_KmsMediaSessionEndPointType_constants.EVENT_MEDIA_SESSION_START.compare (
eventType) == 0)
mediaHandlerManager.addMediaHandler (_return, eventType, handlerAddress,
handlerPort);
else if (g_KmsMediaSessionEndPointType_constants.EVENT_MEDIA_SESSION_COMPLETE.compare (
eventType) == 0)
mediaHandlerManager.addMediaHandler (_return, eventType, handlerAddress,
handlerPort);
else if (g_KmsMediaHttpEndPointType_constants.EVENT_EOS_DETECTED.compare (
eventType) == 0)
mediaHandlerManager.addMediaHandler (_return, eventType, handlerAddress,
handlerPort);
else
EndPoint::subscribe (_return, eventType, handlerAddress, handlerPort);
}
HttpEndPoint::StaticConstructor HttpEndPoint::staticConstructor;
HttpEndPoint::StaticConstructor::StaticConstructor()
{
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
} // kurento
<|endoftext|>
|
<commit_before>#include "gru.h"
#include <sstream>
#include <gflags/gflags.h>
#include <boost/algorithm/string.hpp>
#include <vector>
#include "logging.h"
#include "util.h"
DECLARE_int32(galaxy_deploy_step);
DECLARE_string(minion_path);
DECLARE_string(nexus_server_list);
DECLARE_string(nexus_root_path);
DECLARE_string(master_path);
DECLARE_bool(enable_cpu_soft_limit);
DECLARE_bool(enable_memory_soft_limit);
DECLARE_string(galaxy_node_label);
DECLARE_string(galaxy_user);
DECLARE_string(galaxy_token);
DECLARE_string(galaxy_pool);
DECLARE_int32(max_minions_per_host);
namespace baidu {
namespace shuttle {
static const int64_t default_additional_map_memory = 1024l * 1024 * 1024;
static const int64_t default_additional_reduce_memory = 2048l * 1024 * 1024;
static const int default_map_additional_millicores = 0;
static const int default_reduce_additional_millicores = 500;
int Gru::additional_map_millicores = default_map_additional_millicores;
int Gru::additional_reduce_millicores = default_reduce_additional_millicores;
int64_t Gru::additional_map_memory = default_additional_map_memory;
int64_t Gru::additional_reduce_memory = default_additional_reduce_memory;
Gru::Gru(::baidu::galaxy::sdk::AppMaster* galaxy, JobDescriptor* job,
const std::string& job_id, WorkMode mode) :
galaxy_(galaxy), job_(job), job_id_(job_id), mode_(mode) {
mode_str_ = ((mode == kReduce) ? "reduce" : "map");
minion_name_ = job->name() + "_" + mode_str_;
}
Status Gru::Start() {
::baidu::galaxy::sdk::SubmitJobRequest galaxy_job;
galaxy_job.user.user = FLAGS_galaxy_user;
galaxy_job.user.token = FLAGS_galaxy_token;
galaxy_job.hostname = ::baidu::common::util::GetLocalHostName();
std::vector<std::string> pools;
boost::split(pools, FLAGS_galaxy_pool, boost::is_any_of(","));
galaxy_job.job.deploy.pools = pools;
galaxy_job.job.name = minion_name_ + "@minion";
galaxy_job.job.type = ::baidu::galaxy::sdk::kJobBatch;
galaxy_job.job.deploy.replica = (mode_ == kReduce) ? job_->reduce_capacity() : job_->map_capacity();
galaxy_job.job.deploy.step = std::min((int)FLAGS_galaxy_deploy_step, (int)galaxy_job.job.deploy.replica);
galaxy_job.job.deploy.interval = 1;
galaxy_job.job.deploy.max_per_host = FLAGS_max_minions_per_host;
galaxy_job.job.deploy.update_break_count = 0;
galaxy_job.job.version = "1.0.0";
galaxy_job.job.run_user = "galaxy";
if (!FLAGS_galaxy_node_label.empty()) {
galaxy_job.job.deploy.tag = FLAGS_galaxy_node_label;
}
::baidu::galaxy::sdk::PodDescription & pod_desc = galaxy_job.job.pod;
pod_desc.workspace_volum.size = (3L << 30);
pod_desc.workspace_volum.medium = ::baidu::galaxy::sdk::kDisk;
pod_desc.workspace_volum.exclusive = false;
pod_desc.workspace_volum.readonly = false;
pod_desc.workspace_volum.use_symlink = false;
pod_desc.workspace_volum.dest_path = "/home/shuttle";
pod_desc.workspace_volum.type = ::baidu::galaxy::sdk::kEmptyDir;
::baidu::galaxy::sdk::TaskDescription task_desc;
if (mode_str_ == "map") {
task_desc.cpu.milli_core = job_->millicores() + additional_map_millicores;
} else {
task_desc.cpu.milli_core = job_->millicores() + additional_reduce_millicores;
}
task_desc.memory.size = job_->memory() +
((mode_ == kReduce) ? additional_reduce_memory : additional_map_memory);
std::string app_package;
std::vector<std::string> cache_archive_list;
int file_size = job_->files().size();
for (int i = 0; i < file_size; ++i) {
const std::string& file = job_->files(i);
if (boost::starts_with(file, "hdfs://")) {
cache_archive_list.push_back(file);
} else {
app_package = file;
}
}
std::stringstream ss;
if (!job_->input_dfs().user().empty()) {
ss << "hadoop_job_ugi=" << job_->input_dfs().user()
<< "," << job_->input_dfs().password()
<< " fs_default_name=hdfs://" << job_->input_dfs().host()
<< ":" << job_->input_dfs().port() << " ";
}
for (size_t i = 0; i < cache_archive_list.size(); i++) {
ss << "cache_archive_" << i << "=" << cache_archive_list[i] << " ";
}
ss << "app_package=" << app_package
<< " ./minion_boot.sh -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_);
std::stringstream ss_stop;
ss_stop << "source ./hdfs_env.sh; ./minion -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_)
<< " -kill_task";
task_desc.exe_package.package.source_path = FLAGS_minion_path;
task_desc.exe_package.package.dest_path = ".";
task_desc.exe_package.package.version = "1.0";
task_desc.exe_package.start_cmd = ss.str();
task_desc.exe_package.stop_cmd = ss_stop.str().c_str();
task_desc.data_package.reload_cmd = ss.str();
task_desc.tcp_throt.recv_bps_quota = (80L << 20);
task_desc.tcp_throt.send_bps_quota = (80L << 20);
task_desc.blkio.weight = 50;
::baidu::galaxy::sdk::PortRequired port_req;
port_req.port = "dynamic";
port_req.port_name = "NFS_CLIENT_PORT";
task_desc.ports.push_back(port_req);
port_req.port = "dynamic";
port_req.port_name = "MINION_PORT";
task_desc.ports.push_back(port_req);
if (FLAGS_enable_cpu_soft_limit) {
task_desc.cpu.excess = true;
} else {
task_desc.cpu.excess = false;
}
if (FLAGS_enable_memory_soft_limit) {
task_desc.memory.excess = true;
} else {
task_desc.memory.excess = false;
}
pod_desc.tasks.push_back(task_desc);
std::string minion_id;
::baidu::galaxy::sdk::SubmitJobResponse rsps;
if (galaxy_->SubmitJob(galaxy_job, &rsps)) {
minion_id = rsps.jobid;
LOG(INFO, "galaxy job id: %s", minion_id.c_str());
minion_id_ = minion_id;
galaxy_job_ = galaxy_job;
if (minion_id_.empty()) {
LOG(INFO, "can not get galaxy job id");
return kGalaxyError;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Kill() {
LOG(INFO, "kill galaxy job: %s", minion_id_.c_str());
if (minion_id_.empty()) {
return kOk;
}
::baidu::galaxy::sdk::RemoveJobRequest rqst;
::baidu::galaxy::sdk::RemoveJobResponse rsps;
rqst.jobid = minion_id_;
rqst.user = galaxy_job_.user;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
if (galaxy_->RemoveJob(rqst, &rsps)) {
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Update(const std::string& priority,
int capacity) {
::baidu::galaxy::sdk::JobDescription job_desc = galaxy_job_.job;
if (!priority.empty()) {
//job_desc.priority = priority;
}
if (capacity != -1) {
job_desc.deploy.replica = capacity;
}
::baidu::galaxy::sdk::UpdateJobRequest rqst;
::baidu::galaxy::sdk::UpdateJobResponse rsps;
rqst.user = galaxy_job_.user;
rqst.job = job_desc;
rqst.jobid = minion_id_;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
rqst.operate = ::baidu::galaxy::sdk::kUpdateJobStart;
if (galaxy_->UpdateJob(rqst, &rsps)) {
if (!priority.empty()) {
//galaxy_job_.priority = priority;
}
if (capacity != -1) {
galaxy_job_.job.deploy.replica = capacity;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
}
}
<commit_msg>Use task total to limit capacity<commit_after>#include "gru.h"
#include <sstream>
#include <gflags/gflags.h>
#include <boost/algorithm/string.hpp>
#include <vector>
#include <cmath>
#include "logging.h"
#include "util.h"
DECLARE_int32(galaxy_deploy_step);
DECLARE_string(minion_path);
DECLARE_string(nexus_server_list);
DECLARE_string(nexus_root_path);
DECLARE_string(master_path);
DECLARE_bool(enable_cpu_soft_limit);
DECLARE_bool(enable_memory_soft_limit);
DECLARE_string(galaxy_node_label);
DECLARE_string(galaxy_user);
DECLARE_string(galaxy_token);
DECLARE_string(galaxy_pool);
DECLARE_int32(max_minions_per_host);
namespace baidu {
namespace shuttle {
static const int64_t default_additional_map_memory = 1024l * 1024 * 1024;
static const int64_t default_additional_reduce_memory = 2048l * 1024 * 1024;
static const int default_map_additional_millicores = 0;
static const int default_reduce_additional_millicores = 500;
int Gru::additional_map_millicores = default_map_additional_millicores;
int Gru::additional_reduce_millicores = default_reduce_additional_millicores;
int64_t Gru::additional_map_memory = default_additional_map_memory;
int64_t Gru::additional_reduce_memory = default_additional_reduce_memory;
Gru::Gru(::baidu::galaxy::sdk::AppMaster* galaxy, JobDescriptor* job,
const std::string& job_id, WorkMode mode) :
galaxy_(galaxy), job_(job), job_id_(job_id), mode_(mode) {
mode_str_ = ((mode == kReduce) ? "reduce" : "map");
minion_name_ = job->name() + "_" + mode_str_;
}
Status Gru::Start() {
::baidu::galaxy::sdk::SubmitJobRequest galaxy_job;
galaxy_job.user.user = FLAGS_galaxy_user;
galaxy_job.user.token = FLAGS_galaxy_token;
galaxy_job.hostname = ::baidu::common::util::GetLocalHostName();
std::vector<std::string> pools;
boost::split(pools, FLAGS_galaxy_pool, boost::is_any_of(","));
galaxy_job.job.deploy.pools = pools;
galaxy_job.job.name = minion_name_ + "@minion";
galaxy_job.job.type = ::baidu::galaxy::sdk::kJobBatch;
if (mode_ == kReduce) {
galaxy_job.job.deploy.replica = std::min(job_->reduce_capacity(),
std::min(job_->reduce_total() * 6 / 5, 20));
} else {
galaxy_job.job.deploy.replica = std::min(job_->map_capacity(),
std::min(job_->map_total() * 6 / 5, 20));
}
galaxy_job.job.deploy.step = std::min((int)FLAGS_galaxy_deploy_step, (int)galaxy_job.job.deploy.replica);
galaxy_job.job.deploy.interval = 1;
galaxy_job.job.deploy.max_per_host = FLAGS_max_minions_per_host;
galaxy_job.job.deploy.update_break_count = 0;
galaxy_job.job.version = "1.0.0";
galaxy_job.job.run_user = "galaxy";
if (!FLAGS_galaxy_node_label.empty()) {
galaxy_job.job.deploy.tag = FLAGS_galaxy_node_label;
}
::baidu::galaxy::sdk::PodDescription & pod_desc = galaxy_job.job.pod;
pod_desc.workspace_volum.size = (3L << 30);
pod_desc.workspace_volum.medium = ::baidu::galaxy::sdk::kDisk;
pod_desc.workspace_volum.exclusive = false;
pod_desc.workspace_volum.readonly = false;
pod_desc.workspace_volum.use_symlink = false;
pod_desc.workspace_volum.dest_path = "/home/shuttle";
pod_desc.workspace_volum.type = ::baidu::galaxy::sdk::kEmptyDir;
::baidu::galaxy::sdk::TaskDescription task_desc;
if (mode_str_ == "map") {
task_desc.cpu.milli_core = job_->millicores() + additional_map_millicores;
} else {
task_desc.cpu.milli_core = job_->millicores() + additional_reduce_millicores;
}
task_desc.memory.size = job_->memory() +
((mode_ == kReduce) ? additional_reduce_memory : additional_map_memory);
std::string app_package;
std::vector<std::string> cache_archive_list;
int file_size = job_->files().size();
for (int i = 0; i < file_size; ++i) {
const std::string& file = job_->files(i);
if (boost::starts_with(file, "hdfs://")) {
cache_archive_list.push_back(file);
} else {
app_package = file;
}
}
std::stringstream ss;
if (!job_->input_dfs().user().empty()) {
ss << "hadoop_job_ugi=" << job_->input_dfs().user()
<< "," << job_->input_dfs().password()
<< " fs_default_name=hdfs://" << job_->input_dfs().host()
<< ":" << job_->input_dfs().port() << " ";
}
for (size_t i = 0; i < cache_archive_list.size(); i++) {
ss << "cache_archive_" << i << "=" << cache_archive_list[i] << " ";
}
ss << "app_package=" << app_package
<< " ./minion_boot.sh -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_);
std::stringstream ss_stop;
ss_stop << "source ./hdfs_env.sh; ./minion -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_)
<< " -kill_task";
task_desc.exe_package.package.source_path = FLAGS_minion_path;
task_desc.exe_package.package.dest_path = ".";
task_desc.exe_package.package.version = "1.0";
task_desc.exe_package.start_cmd = ss.str();
task_desc.exe_package.stop_cmd = ss_stop.str().c_str();
task_desc.data_package.reload_cmd = ss.str();
task_desc.tcp_throt.recv_bps_quota = (80L << 20);
task_desc.tcp_throt.send_bps_quota = (80L << 20);
task_desc.blkio.weight = 50;
::baidu::galaxy::sdk::PortRequired port_req;
port_req.port = "dynamic";
port_req.port_name = "NFS_CLIENT_PORT";
task_desc.ports.push_back(port_req);
port_req.port = "dynamic";
port_req.port_name = "MINION_PORT";
task_desc.ports.push_back(port_req);
if (FLAGS_enable_cpu_soft_limit) {
task_desc.cpu.excess = true;
} else {
task_desc.cpu.excess = false;
}
if (FLAGS_enable_memory_soft_limit) {
task_desc.memory.excess = true;
} else {
task_desc.memory.excess = false;
}
pod_desc.tasks.push_back(task_desc);
std::string minion_id;
::baidu::galaxy::sdk::SubmitJobResponse rsps;
if (galaxy_->SubmitJob(galaxy_job, &rsps)) {
minion_id = rsps.jobid;
LOG(INFO, "galaxy job id: %s", minion_id.c_str());
minion_id_ = minion_id;
galaxy_job_ = galaxy_job;
if (minion_id_.empty()) {
LOG(INFO, "can not get galaxy job id");
return kGalaxyError;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Kill() {
LOG(INFO, "kill galaxy job: %s", minion_id_.c_str());
if (minion_id_.empty()) {
return kOk;
}
::baidu::galaxy::sdk::RemoveJobRequest rqst;
::baidu::galaxy::sdk::RemoveJobResponse rsps;
rqst.jobid = minion_id_;
rqst.user = galaxy_job_.user;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
if (galaxy_->RemoveJob(rqst, &rsps)) {
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Update(const std::string& priority,
int capacity) {
::baidu::galaxy::sdk::JobDescription job_desc = galaxy_job_.job;
if (!priority.empty()) {
//job_desc.priority = priority;
}
if (capacity != -1) {
job_desc.deploy.replica = capacity;
}
::baidu::galaxy::sdk::UpdateJobRequest rqst;
::baidu::galaxy::sdk::UpdateJobResponse rsps;
rqst.user = galaxy_job_.user;
rqst.job = job_desc;
rqst.jobid = minion_id_;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
rqst.operate = ::baidu::galaxy::sdk::kUpdateJobStart;
if (galaxy_->UpdateJob(rqst, &rsps)) {
if (!priority.empty()) {
//galaxy_job_.priority = priority;
}
if (capacity != -1) {
galaxy_job_.job.deploy.replica = capacity;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2004 Reinhold Kainhofer <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <qfile.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include <kdebug.h>
#include <kaction.h>
#include <kglobal.h>
//#include <korganizer/calendarviewbase.h">
#include "kotimespanview.h"
#include "timespanview.h"
using namespace KOrg;
#include "timespanview.moc"
class TimespanViewFactory : public KOrg::PartFactory {
public:
KOrg::Part *create( KOrg::MainWindow *parent, const char *name )
{
return new TimespanView( parent, name );
}
};
extern "C" {
void *init_libkorg_timespanview()
{
return ( new TimespanViewFactory );
}
}
TimespanView::TimespanView(KOrg::MainWindow *parent, const char *name) :
KOrg::Part(parent,name), mView(0)
{
setInstance( new KInstance( "korganizer" ) );
setXMLFile( "plugins/timespanviewui.rc" );
new KAction( i18n("&Timespan"), "timespan", 0, this, SLOT( showView() ),
actionCollection(), "view_timespan" );
}
TimespanView::~TimespanView()
{
}
QString TimespanView::info()
{
return i18n("This plugin provides a gantt-like Timespan view.");
}
QString TimespanView::shortInfo()
{
return i18n( "Timespan View Plugin" );
}
void TimespanView::showView()
{
if (!mView) {
mView = new KOTimeSpanView( mainWindow()->view()->calendar(),
mainWindow()->view() );
mainWindow()->view()->addView( mView );
}
mainWindow()->view()->showView( mView );
}
<commit_msg><commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2004 Reinhold Kainhofer <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <qfile.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include <kdebug.h>
#include <kaction.h>
#include <kglobal.h>
//#include <korganizer/calendarviewbase.h">
#include "kotimespanview.h"
#include "timespanview.h"
using namespace KOrg;
#include "timespanview.moc"
class TimespanViewFactory : public KOrg::PartFactory {
public:
KOrg::Part *create( KOrg::MainWindow *parent, const char *name )
{
return new TimespanView( parent, name );
}
};
extern "C" {
void *init_libkorg_timespanview()
{
return ( new TimespanViewFactory );
}
}
TimespanView::TimespanView(KOrg::MainWindow *parent, const char *name) :
KOrg::Part(parent,name), mView(0)
{
setInstance( new KInstance( "korganizer" ) );
setXMLFile( "plugins/timespanviewui.rc" );
new KAction( i18n("&Timespan"), "timespan", 0, this, SLOT( showView() ),
actionCollection(), "view_timespan" );
}
TimespanView::~TimespanView()
{
}
QString TimespanView::info()
{
return i18n("This plugin provides a Gantt-like Timespan view.");
}
QString TimespanView::shortInfo()
{
return i18n( "Timespan View Plugin" );
}
void TimespanView::showView()
{
if (!mView) {
mView = new KOTimeSpanView( mainWindow()->view()->calendar(),
mainWindow()->view() );
mainWindow()->view()->addView( mView );
}
mainWindow()->view()->showView( mView );
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativecamera_p.h"
#include "qdeclarativecameracapture_p.h"
#include "qdeclarativecamerapreviewprovider_p.h"
#include <qmetadatawritercontrol.h>
#include <QtCore/qurl.h>
QT_BEGIN_NAMESPACE
/*!
\qmlclass CameraCapture QDeclarativeCameraCapture
\brief The CameraCapture element provides an interface for capturing camera images
\ingroup multimedia_qml
\inqmlmodule QtMultimedia 5
\ingroup camera_qml
This element allows you to capture still images and be notified when they
are available or saved to disk. You can adjust the resolution of the captured
image and where the saved image should go.
This element is a child of a Camera element (as the
\l {Camera::imageCapture}{imageCapture} property) and cannot be created
directly.
\qml
import QtQuick 2.0
import QtMultimedia 5.0
Camera {
id: camera
imageCapture {
onImageCaptured: {
// Show the preview in an Image element
photoPreview.source = preview
}
}
}
VideoOutput {
source: camera
focus : visible // to receive focus and capture key events when visible
MouseArea {
anchors.fill: parent;
onClicked: camera.imageCapture.capture();
}
}
Image {
id: photoPreview
}
\endqml
*/
QDeclarativeCameraCapture::QDeclarativeCameraCapture(QCamera *camera, QObject *parent) :
QObject(parent),
m_camera(camera)
{
m_capture = new QCameraImageCapture(camera, this);
connect(m_capture, SIGNAL(readyForCaptureChanged(bool)), this, SIGNAL(readyForCaptureChanged(bool)));
connect(m_capture, SIGNAL(imageExposed(int)), this, SIGNAL(imageExposed()));
connect(m_capture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(_q_imageCaptured(int, QImage)));
connect(m_capture, SIGNAL(imageMetadataAvailable(int,QString,QVariant)), this,
SLOT(_q_imageMetadataAvailable(int,QString,QVariant)));
connect(m_capture, SIGNAL(imageSaved(int,QString)), this, SLOT(_q_imageSaved(int, QString)));
connect(m_capture, SIGNAL(error(int,QCameraImageCapture::Error,QString)),
this, SLOT(_q_captureFailed(int,QCameraImageCapture::Error,QString)));
QMediaService *service = camera->service();
m_metadataWriterControl = service ? service->requestControl<QMetaDataWriterControl*>() : 0;
}
QDeclarativeCameraCapture::~QDeclarativeCameraCapture()
{
}
/*!
\qmlproperty bool QtMultimedia5::CameraCapture::ready
\property QDeclarativeCameraCapture::ready
Indicates camera is ready to capture photo.
It's permissible to call capture() while the camera is active
regardless of isReadyForCapture property value.
If camera is not ready to capture image immediately,
the capture request is queued with all the related camera settings
to be executed as soon as possible.
*/
bool QDeclarativeCameraCapture::isReadyForCapture() const
{
return m_capture->isReadyForCapture();
}
/*!
\qmlmethod QtMultimedia5::CameraCapture::capture()
\fn QDeclarativeCameraCapture::capture()
Start image capture. The \l onImageCaptured() and \l onImageSaved() signals will
be emitted when the capture is complete.
The image will be captured to the default system location.
Camera saves all the capture parameters like exposure settings or
image processing parameters, so changes to camera paramaters after
capture() is called do not affect previous capture requests.
CameraCapture::capture returns the capture requestId parameter, used with
imageExposed(), imageCaptured(), imageMetadataAvailable() and imageSaved() signals.
*/
int QDeclarativeCameraCapture::capture()
{
return m_capture->capture();
}
/*!
\qmlmethod QtMultimedia5::CameraCapture::captureToLocation(location)
\fn QDeclarativeCameraCapture::captureToLocation(const QString &location)
Start image capture to specified \a location. The \l onImageCaptured() and \l onImageSaved() signals will
be emitted when the capture is complete.
CameraCapture::captureToLocation returns the capture requestId parameter, used with
imageExposed(), imageCaptured(), imageMetadataAvailable() and imageSaved() signals.
*/
int QDeclarativeCameraCapture::captureToLocation(const QString &location)
{
return m_capture->capture(location);
}
/*!
\qmlmethod QtMultimedia5::CameraCapture::cancelCapture()
\fn QDeclarativeCameraCapture::cancelCapture()
Cancel pending image capture requests.
*/
void QDeclarativeCameraCapture::cancelCapture()
{
m_capture->cancelCapture();
}
/*!
\qmlproperty string QtMultimedia5::CameraCapture::capturedImagePath
\property QDeclarativeCameraCapture::capturedImagePath
The path to the last captured image.
*/
QString QDeclarativeCameraCapture::capturedImagePath() const
{
return m_capturedImagePath;
}
void QDeclarativeCameraCapture::_q_imageCaptured(int id, const QImage &preview)
{
QString previewId = QString("preview_%1").arg(id);
QDeclarativeCameraPreviewProvider::registerPreview(previewId, preview);
emit imageCaptured(id, QLatin1String("image://camera/")+previewId);
}
void QDeclarativeCameraCapture::_q_imageSaved(int id, const QString &fileName)
{
m_capturedImagePath = fileName;
emit imageSaved(id, fileName);
}
void QDeclarativeCameraCapture::_q_imageMetadataAvailable(int id, const QString &key, const QVariant &value)
{
emit imageMetadataAvailable(id, key, value);
}
void QDeclarativeCameraCapture::_q_captureFailed(int id, QCameraImageCapture::Error error, const QString &message)
{
Q_UNUSED(error);
qWarning() << "QCameraImageCapture error:" << message;
emit captureFailed(id, message);
}
/*!
\qmlproperty size QtMultimedia5::CameraCapture::resolution
\property QDeclarativeCameraCapture::resolution
The resolution to capture the image at. If empty, the system will pick
a good size.
*/
QSize QDeclarativeCameraCapture::resolution()
{
return m_imageSettings.resolution();
}
void QDeclarativeCameraCapture::setResolution(const QSize &captureResolution)
{
if (captureResolution != resolution()) {
m_imageSettings.setResolution(captureResolution);
m_capture->setEncodingSettings(m_imageSettings);
emit resolutionChanged(captureResolution);
}
}
QCameraImageCapture::Error QDeclarativeCameraCapture::error() const
{
return m_capture->error();
}
/*!
\qmlproperty string QtMultimedia5::CameraCapture::errorString
\property QDeclarativeCameraCapture::errorString
The last capture related error message.
*/
QString QDeclarativeCameraCapture::errorString() const
{
return m_capture->errorString();
}
/*!
\qmlmethod QtMultimedia5::CameraCapture::setMetadata(key, value)
\fn QDeclarativeCameraCapture::setMetadata(const QString &key, const QVariant &value)
Sets a particular metadata \a key to \a value for the subsequent image captures.
*/
void QDeclarativeCameraCapture::setMetadata(const QString &key, const QVariant &value)
{
if (m_metadataWriterControl)
m_metadataWriterControl->setMetaData(key, value);
}
/*!
\qmlsignal QtMultimedia5::CameraCapture::onCaptureFailed(requestId, message)
\fn QDeclarativeCameraCapture::captureFailed(int requestId, const QString &message)
This handler is called when an error occurs during capture with \a requestId.
A descriptive message is available in \a message.
*/
/*!
\qmlsignal QtMultimedia5::CameraCapture::onImageCaptured(requestId, preview)
\fn QDeclarativeCameraCapture::imageCaptured(int requestId, const QString &preview)
This handler is called when an image with \a requestId has been captured
but not yet saved to the filesystem. The \a preview
parameter can be used as the URL supplied to an Image element.
\sa onImageSaved
*/
/*!
\qmlsignal QtMultimedia5::CameraCapture::onImageSaved(requestId, path)
\fn QDeclarativeCameraCapture::imageSaved(int requestId, const QString &path)
This handler is called after the image with \a requestId has been written to the filesystem.
The \a path is a local file path, not a URL.
\sa onImageCaptured
*/
/*!
\qmlsignal QtMultimedia5::CameraCapture::onImageMetadataAvailable(requestId, key, value)
\fn QDeclarativeCameraCapture::imageMetadataAvailable(int requestId, const QString &key, const QVariant &value);
This handler is called when the image with \a requestId has new metadata
available with the key \a key and value \a value.
\sa onImageCaptured
*/
QT_END_NAMESPACE
#include "moc_qdeclarativecameracapture_p.cpp"
<commit_msg>Fixed the qml Camera.imageCapture.imageExposed signal connection<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativecamera_p.h"
#include "qdeclarativecameracapture_p.h"
#include "qdeclarativecamerapreviewprovider_p.h"
#include <qmetadatawritercontrol.h>
#include <QtCore/qurl.h>
QT_BEGIN_NAMESPACE
/*!
\qmlclass CameraCapture QDeclarativeCameraCapture
\brief The CameraCapture element provides an interface for capturing camera images
\ingroup multimedia_qml
\inqmlmodule QtMultimedia 5
\ingroup camera_qml
This element allows you to capture still images and be notified when they
are available or saved to disk. You can adjust the resolution of the captured
image and where the saved image should go.
This element is a child of a Camera element (as the
\l {Camera::imageCapture}{imageCapture} property) and cannot be created
directly.
\qml
import QtQuick 2.0
import QtMultimedia 5.0
Camera {
id: camera
imageCapture {
onImageCaptured: {
// Show the preview in an Image element
photoPreview.source = preview
}
}
}
VideoOutput {
source: camera
focus : visible // to receive focus and capture key events when visible
MouseArea {
anchors.fill: parent;
onClicked: camera.imageCapture.capture();
}
}
Image {
id: photoPreview
}
\endqml
*/
QDeclarativeCameraCapture::QDeclarativeCameraCapture(QCamera *camera, QObject *parent) :
QObject(parent),
m_camera(camera)
{
m_capture = new QCameraImageCapture(camera, this);
connect(m_capture, SIGNAL(readyForCaptureChanged(bool)), this, SIGNAL(readyForCaptureChanged(bool)));
connect(m_capture, SIGNAL(imageExposed(int)), this, SIGNAL(imageExposed(int)));
connect(m_capture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(_q_imageCaptured(int, QImage)));
connect(m_capture, SIGNAL(imageMetadataAvailable(int,QString,QVariant)), this,
SLOT(_q_imageMetadataAvailable(int,QString,QVariant)));
connect(m_capture, SIGNAL(imageSaved(int,QString)), this, SLOT(_q_imageSaved(int, QString)));
connect(m_capture, SIGNAL(error(int,QCameraImageCapture::Error,QString)),
this, SLOT(_q_captureFailed(int,QCameraImageCapture::Error,QString)));
QMediaService *service = camera->service();
m_metadataWriterControl = service ? service->requestControl<QMetaDataWriterControl*>() : 0;
}
QDeclarativeCameraCapture::~QDeclarativeCameraCapture()
{
}
/*!
\qmlproperty bool QtMultimedia5::CameraCapture::ready
\property QDeclarativeCameraCapture::ready
Indicates camera is ready to capture photo.
It's permissible to call capture() while the camera is active
regardless of isReadyForCapture property value.
If camera is not ready to capture image immediately,
the capture request is queued with all the related camera settings
to be executed as soon as possible.
*/
bool QDeclarativeCameraCapture::isReadyForCapture() const
{
return m_capture->isReadyForCapture();
}
/*!
\qmlmethod QtMultimedia5::CameraCapture::capture()
\fn QDeclarativeCameraCapture::capture()
Start image capture. The \l onImageCaptured() and \l onImageSaved() signals will
be emitted when the capture is complete.
The image will be captured to the default system location.
Camera saves all the capture parameters like exposure settings or
image processing parameters, so changes to camera paramaters after
capture() is called do not affect previous capture requests.
CameraCapture::capture returns the capture requestId parameter, used with
imageExposed(), imageCaptured(), imageMetadataAvailable() and imageSaved() signals.
*/
int QDeclarativeCameraCapture::capture()
{
return m_capture->capture();
}
/*!
\qmlmethod QtMultimedia5::CameraCapture::captureToLocation(location)
\fn QDeclarativeCameraCapture::captureToLocation(const QString &location)
Start image capture to specified \a location. The \l onImageCaptured() and \l onImageSaved() signals will
be emitted when the capture is complete.
CameraCapture::captureToLocation returns the capture requestId parameter, used with
imageExposed(), imageCaptured(), imageMetadataAvailable() and imageSaved() signals.
*/
int QDeclarativeCameraCapture::captureToLocation(const QString &location)
{
return m_capture->capture(location);
}
/*!
\qmlmethod QtMultimedia5::CameraCapture::cancelCapture()
\fn QDeclarativeCameraCapture::cancelCapture()
Cancel pending image capture requests.
*/
void QDeclarativeCameraCapture::cancelCapture()
{
m_capture->cancelCapture();
}
/*!
\qmlproperty string QtMultimedia5::CameraCapture::capturedImagePath
\property QDeclarativeCameraCapture::capturedImagePath
The path to the last captured image.
*/
QString QDeclarativeCameraCapture::capturedImagePath() const
{
return m_capturedImagePath;
}
void QDeclarativeCameraCapture::_q_imageCaptured(int id, const QImage &preview)
{
QString previewId = QString("preview_%1").arg(id);
QDeclarativeCameraPreviewProvider::registerPreview(previewId, preview);
emit imageCaptured(id, QLatin1String("image://camera/")+previewId);
}
void QDeclarativeCameraCapture::_q_imageSaved(int id, const QString &fileName)
{
m_capturedImagePath = fileName;
emit imageSaved(id, fileName);
}
void QDeclarativeCameraCapture::_q_imageMetadataAvailable(int id, const QString &key, const QVariant &value)
{
emit imageMetadataAvailable(id, key, value);
}
void QDeclarativeCameraCapture::_q_captureFailed(int id, QCameraImageCapture::Error error, const QString &message)
{
Q_UNUSED(error);
qWarning() << "QCameraImageCapture error:" << message;
emit captureFailed(id, message);
}
/*!
\qmlproperty size QtMultimedia5::CameraCapture::resolution
\property QDeclarativeCameraCapture::resolution
The resolution to capture the image at. If empty, the system will pick
a good size.
*/
QSize QDeclarativeCameraCapture::resolution()
{
return m_imageSettings.resolution();
}
void QDeclarativeCameraCapture::setResolution(const QSize &captureResolution)
{
if (captureResolution != resolution()) {
m_imageSettings.setResolution(captureResolution);
m_capture->setEncodingSettings(m_imageSettings);
emit resolutionChanged(captureResolution);
}
}
QCameraImageCapture::Error QDeclarativeCameraCapture::error() const
{
return m_capture->error();
}
/*!
\qmlproperty string QtMultimedia5::CameraCapture::errorString
\property QDeclarativeCameraCapture::errorString
The last capture related error message.
*/
QString QDeclarativeCameraCapture::errorString() const
{
return m_capture->errorString();
}
/*!
\qmlmethod QtMultimedia5::CameraCapture::setMetadata(key, value)
\fn QDeclarativeCameraCapture::setMetadata(const QString &key, const QVariant &value)
Sets a particular metadata \a key to \a value for the subsequent image captures.
*/
void QDeclarativeCameraCapture::setMetadata(const QString &key, const QVariant &value)
{
if (m_metadataWriterControl)
m_metadataWriterControl->setMetaData(key, value);
}
/*!
\qmlsignal QtMultimedia5::CameraCapture::onCaptureFailed(requestId, message)
\fn QDeclarativeCameraCapture::captureFailed(int requestId, const QString &message)
This handler is called when an error occurs during capture with \a requestId.
A descriptive message is available in \a message.
*/
/*!
\qmlsignal QtMultimedia5::CameraCapture::onImageCaptured(requestId, preview)
\fn QDeclarativeCameraCapture::imageCaptured(int requestId, const QString &preview)
This handler is called when an image with \a requestId has been captured
but not yet saved to the filesystem. The \a preview
parameter can be used as the URL supplied to an Image element.
\sa onImageSaved
*/
/*!
\qmlsignal QtMultimedia5::CameraCapture::onImageSaved(requestId, path)
\fn QDeclarativeCameraCapture::imageSaved(int requestId, const QString &path)
This handler is called after the image with \a requestId has been written to the filesystem.
The \a path is a local file path, not a URL.
\sa onImageCaptured
*/
/*!
\qmlsignal QtMultimedia5::CameraCapture::onImageMetadataAvailable(requestId, key, value)
\fn QDeclarativeCameraCapture::imageMetadataAvailable(int requestId, const QString &key, const QVariant &value);
This handler is called when the image with \a requestId has new metadata
available with the key \a key and value \a value.
\sa onImageCaptured
*/
QT_END_NAMESPACE
#include "moc_qdeclarativecameracapture_p.cpp"
<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : B.cpp
* Author : Kazune Takahashi
* Created : 5/22/2019, 4:32:20 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N, K;
string S;
int main()
{
cin >> N >> S >> K;
K--;
char x = S[K];
for (auto i = 0; i < N; i++)
{
if (S[i] == x)
{
S[i] = '*';
}
}
cout << S << endl;
}<commit_msg>submit B.cpp to 'B - *e**** ********e* *e****e* ****e**' (tenka1-2019-beginner) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
* File : B.cpp
* Author : Kazune Takahashi
* Created : 5/22/2019, 4:32:20 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N, K;
string S;
int main()
{
cin >> N >> S >> K;
K--;
char x = S[K];
for (auto i = 0; i < N; i++)
{
if (S[i] != x)
{
S[i] = '*';
}
}
cout << S << endl;
}<|endoftext|>
|
<commit_before>#include "types.hpp"
#include <iostream>
#include <functional>
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
template <typename T>
using func_t = std::function<T(T)>;
template <typename T>
T numerical_diff(func_t<T> f, T x)
{
auto h = 1e-4;
return (f(x+h) - f(x-h)) / (2*h);
}
template <typename T>
T function_1(T x)
{
return 0.01*x*x + 0.1*x;
}
template <typename T1, typename T2>
func_t<T2> tangent_line(func_t<T1> f, T1 x)
{
T1 d = numerical_diff<T1>(f, x);
std::cout << d << std::endl;
T1 y = f(x) - d*x;
return [d,y](T2 t){ return d*t + y; };
}
int main(){
array_t<double> x = xt::arange(0.0, 20.0, 0.1);
auto y = function_1<array_t<double>>(x);
plt::xlabel("x");
plt::ylabel("f(x)");
auto tf = tangent_line<double, array_t<double>>(function_1<double>, 5.0);
auto y2 = tf(x);
auto vx = arr_to_vec(x);
auto vy = arr_to_vec(y);
auto vy2 = arr_to_vec(y2);
plt::plot(vx,vy);
plt::plot(vx,vy2);
plt::show();
return 0;
}
<commit_msg>refactor<commit_after>#include "types.hpp"
#include <iostream>
#include <functional>
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
template <typename T>
using func_t = std::function<T(T)>;
template <typename T>
T numerical_diff(func_t<T> f, T x)
{
auto h = 1e-4;
return (f(x+h) - f(x-h)) / (2*h);
}
template <typename T>
T function_1(T x)
{
return 0.01*x*x + 0.1*x;
}
template <typename T1, typename T2>
func_t<T2> tangent_line(func_t<T1> f, T1 x)
{
T1 d = numerical_diff<T1>(f, x);
std::cout << d << std::endl;
T1 y = f(x) - d*x;
return [d,y](T2 t){ return d*t + y; };
}
int main()
{
array_t<double> x = xt::arange(0.0, 20.0, 0.1);
auto y = function_1<array_t<double>>(x);
plt::xlabel("x");
plt::ylabel("f(x)");
auto tf = tangent_line<double, array_t<double>>(function_1<double>, 5.0);
auto y2 = tf(x);
auto vx = arr_to_vec(x);
auto vy = arr_to_vec(y);
auto vy2 = arr_to_vec(y2);
plt::plot(vx,vy);
plt::plot(vx,vy2);
plt::show();
return 0;
}
<|endoftext|>
|
<commit_before>#include "dreal/dreal_main.h"
#include <csignal>
#include <cstdlib>
#include <iostream>
#include "dreal/dr/run.h"
#include "dreal/smt2/run.h"
#include "dreal/solver/context.h"
#include "dreal/util/exception.h"
#include "dreal/util/filesystem.h"
#include "dreal/util/logging.h"
namespace dreal {
using std::cerr;
using std::endl;
using std::string;
using std::vector;
MainProgram::MainProgram(int argc, const char* argv[]) {
AddOptions();
opt_.parse(argc, argv); // Parse Options
is_options_all_valid_ = ValidateOptions();
}
void MainProgram::PrintUsage() {
string usage;
opt_.getUsage(usage);
cerr << usage;
}
void MainProgram::AddOptions() {
#ifndef NDEBUG
const string build_type{"Debug"};
#else
const string build_type{"Release"};
#endif
opt_.overview =
fmt::format("dReal v{} ({} Build) : delta-complete SMT solver",
Context::version(), build_type);
opt_.syntax = "dreal [OPTIONS] <input file> (.smt2 or .dr)";
// NOTE: Make sure to match the default values specified here with the ones
// specified in dreal/solver/config.h.
opt_.add("" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Display usage instructions.", "-h", "-help", "--help", "--usage");
const double d[1] = {0.0};
ez::ezOptionValidator* const precision_option_validator =
new ez::ezOptionValidator(ez::ezOptionValidator::D,
ez::ezOptionValidator::GT, d, 1);
opt_.add("0.001" /* Default */, false /* Required? */,
1 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Precision (default = 0.001)\n", "--precision",
precision_option_validator);
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Produce models if delta-sat\n", "--produce-models", "--model");
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Debug scanning/lexing\n", "--debug-scanning");
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */, "Debug parsing\n",
"--debug-parsing");
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Use polytope contractor.\n", "--polytope");
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Use polytope contractor in forall contractor.\n",
"--forall-polytope");
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Use worklist fixpoint algorithm in ICP.\n", "--worklist-fixpoint");
ez::ezOptionValidator* const verbose_option_validator =
new ez::ezOptionValidator(
"t", "in", "trace,debug,info,warning,error,critical,off", true);
opt_.add(
"error", // Default.
0, // Required?
1, // Number of args expected.
0, // Delimiter if expecting multiple args.
"Verbosity level. Either one of these (default = error):\n"
"trace, debug, info, warning, error, critical, off", // Help description.
"--verbose", // Flag token.
verbose_option_validator);
}
bool MainProgram::ValidateOptions() {
// Checks bad options and bad arguments.
vector<string> badOptions;
vector<string> badArgs;
if (!opt_.gotRequired(badOptions)) {
for (size_t i = 0; i < badOptions.size(); ++i)
cerr << "ERROR: Missing required option " << badOptions[i] << ".\n\n";
PrintUsage();
return false;
}
if (!opt_.gotExpected(badOptions)) {
for (size_t i = 0; i < badOptions.size(); ++i)
cerr << "ERROR: Got unexpected number of arguments for option "
<< badOptions[i] << ".\n\n";
PrintUsage();
return false;
}
if (!opt_.gotValid(badOptions, badArgs)) {
for (size_t i = 0; i < badOptions.size(); ++i)
cerr << "ERROR: Got invalid argument \"" << badArgs[i] << "\" for option "
<< badOptions[i] << ".\n\n";
PrintUsage();
return false;
}
// After filtering out bad options/arguments, save the valid ones in `args_`.
args_.insert(args_.end(), opt_.firstArgs.begin() + 1, opt_.firstArgs.end());
args_.insert(args_.end(), opt_.unknownArgs.begin(), opt_.unknownArgs.end());
args_.insert(args_.end(), opt_.lastArgs.begin(), opt_.lastArgs.end());
if (opt_.isSet("-h") || args_.size() != 1) {
PrintUsage();
return false;
}
return true;
}
void MainProgram::ExtractOptions() {
// Temporary variables used to set options.
string verbosity;
double precision{0.0};
opt_.get("--verbose")->getString(verbosity);
if (verbosity == "trace") {
log()->set_level(spdlog::level::trace);
} else if (verbosity == "debug") {
log()->set_level(spdlog::level::debug);
} else if (verbosity == "info") {
log()->set_level(spdlog::level::info);
} else if (verbosity == "warning") {
log()->set_level(spdlog::level::warn);
} else if (verbosity == "error") {
log()->set_level(spdlog::level::err);
} else if (verbosity == "critical") {
log()->set_level(spdlog::level::critical);
} else {
log()->set_level(spdlog::level::off);
}
// --precision
if (opt_.isSet("--precision")) {
opt_.get("--precision")->getDouble(precision);
config_.mutable_precision().set_from_command_line(precision);
DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --precision = {}",
config_.precision());
}
// --produce-model
if (opt_.isSet("--produce-models")) {
config_.mutable_produce_models().set_from_command_line(true);
DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --produce-models = {}",
config_.produce_models());
}
// --polytope
if (opt_.isSet("--polytope")) {
config_.mutable_use_polytope().set_from_command_line(true);
DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --polytope = {}",
config_.use_polytope());
}
// --forall-polytope
if (opt_.isSet("--forall-polytope")) {
config_.mutable_use_polytope_in_forall().set_from_command_line(true);
DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --forall-polytope = {}",
config_.use_polytope_in_forall());
}
// --worklist-fixpoint
if (opt_.isSet("--worklist-fixpoint")) {
config_.mutable_use_worklist_fixpoint().set_from_command_line(true);
DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --worklist-fixpoint = {}",
config_.use_worklist_fixpoint());
}
}
int MainProgram::Run() {
if (!is_options_all_valid_) {
return 1;
}
ExtractOptions();
const string& filename{*args_[0]};
if (!file_exists(filename)) {
cerr << "File not found: " << filename << "\n" << endl;
PrintUsage();
return 1;
}
const string extension{get_extension(filename)};
if (extension == "smt2") {
RunSmt2(filename, config_, opt_.isSet("--debug-scanning"),
opt_.isSet("--debug-parsing"));
} else if (extension == "dr") {
RunDr(filename, config_, opt_.isSet("--debug-scanning"),
opt_.isSet("--debug-parsing"));
} else {
cerr << "Unknown extension: " << filename << "\n" << endl;
PrintUsage();
return 1;
}
return 0;
}
} // namespace dreal
namespace {
void HandleSigInt(const int) {
// Properly exit so that we can see stat information produced by destructors
// even if a user press C-c.
std::exit(1);
}
} // namespace
int main(int argc, const char* argv[]) {
std::signal(SIGINT, HandleSigInt);
dreal::MainProgram main_program{argc, argv};
return main_program.Run();
}
<commit_msg>refactor(dreal): clang-tidy<commit_after>#include "dreal/dreal_main.h"
#include <csignal>
#include <cstdlib>
#include <iostream>
#include "dreal/dr/run.h"
#include "dreal/smt2/run.h"
#include "dreal/solver/context.h"
#include "dreal/util/exception.h"
#include "dreal/util/filesystem.h"
#include "dreal/util/logging.h"
namespace dreal {
using std::cerr;
using std::endl;
using std::string;
using std::vector;
MainProgram::MainProgram(int argc, const char* argv[]) {
AddOptions();
opt_.parse(argc, argv); // Parse Options
is_options_all_valid_ = ValidateOptions();
}
void MainProgram::PrintUsage() {
string usage;
opt_.getUsage(usage);
cerr << usage;
}
void MainProgram::AddOptions() {
#ifndef NDEBUG
const string build_type{"Debug"};
#else
const string build_type{"Release"};
#endif
opt_.overview =
fmt::format("dReal v{} ({} Build) : delta-complete SMT solver",
Context::version(), build_type);
opt_.syntax = "dreal [OPTIONS] <input file> (.smt2 or .dr)";
// NOTE: Make sure to match the default values specified here with the ones
// specified in dreal/solver/config.h.
opt_.add("" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Display usage instructions.", "-h", "-help", "--help", "--usage");
const double d[1] = {0.0};
auto* const precision_option_validator = new ez::ezOptionValidator(
ez::ezOptionValidator::D, ez::ezOptionValidator::GT, d, 1);
opt_.add("0.001" /* Default */, false /* Required? */,
1 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Precision (default = 0.001)\n", "--precision",
precision_option_validator);
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Produce models if delta-sat\n", "--produce-models", "--model");
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Debug scanning/lexing\n", "--debug-scanning");
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */, "Debug parsing\n",
"--debug-parsing");
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Use polytope contractor.\n", "--polytope");
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Use polytope contractor in forall contractor.\n",
"--forall-polytope");
opt_.add("false" /* Default */, false /* Required? */,
0 /* Number of args expected. */,
0 /* Delimiter if expecting multiple args. */,
"Use worklist fixpoint algorithm in ICP.\n", "--worklist-fixpoint");
auto* const verbose_option_validator = new ez::ezOptionValidator(
"t", "in", "trace,debug,info,warning,error,critical,off", true);
opt_.add(
"error", // Default.
0, // Required?
1, // Number of args expected.
0, // Delimiter if expecting multiple args.
"Verbosity level. Either one of these (default = error):\n"
"trace, debug, info, warning, error, critical, off", // Help description.
"--verbose", // Flag token.
verbose_option_validator);
}
bool MainProgram::ValidateOptions() {
// Checks bad options and bad arguments.
vector<string> bad_options;
vector<string> bad_args;
if (!opt_.gotRequired(bad_options)) {
for (const auto& bad_option : bad_options) {
cerr << "ERROR: Missing required option " << bad_option << ".\n\n";
}
PrintUsage();
return false;
}
if (!opt_.gotExpected(bad_options)) {
for (const auto& bad_option : bad_options) {
cerr << "ERROR: Got unexpected number of arguments for option "
<< bad_option << ".\n\n";
}
PrintUsage();
return false;
}
if (!opt_.gotValid(bad_options, bad_args)) {
for (size_t i = 0; i < bad_options.size(); ++i) {
cerr << "ERROR: Got invalid argument \"" << bad_args[i]
<< "\" for option " << bad_options[i] << ".\n\n";
}
PrintUsage();
return false;
}
// After filtering out bad options/arguments, save the valid ones in `args_`.
args_.insert(args_.end(), opt_.firstArgs.begin() + 1, opt_.firstArgs.end());
args_.insert(args_.end(), opt_.unknownArgs.begin(), opt_.unknownArgs.end());
args_.insert(args_.end(), opt_.lastArgs.begin(), opt_.lastArgs.end());
if (opt_.isSet("-h") || args_.size() != 1) {
PrintUsage();
return false;
}
return true;
}
void MainProgram::ExtractOptions() {
// Temporary variables used to set options.
string verbosity;
double precision{0.0};
opt_.get("--verbose")->getString(verbosity);
if (verbosity == "trace") {
log()->set_level(spdlog::level::trace);
} else if (verbosity == "debug") {
log()->set_level(spdlog::level::debug);
} else if (verbosity == "info") {
log()->set_level(spdlog::level::info);
} else if (verbosity == "warning") {
log()->set_level(spdlog::level::warn);
} else if (verbosity == "error") {
log()->set_level(spdlog::level::err);
} else if (verbosity == "critical") {
log()->set_level(spdlog::level::critical);
} else {
log()->set_level(spdlog::level::off);
}
// --precision
if (opt_.isSet("--precision")) {
opt_.get("--precision")->getDouble(precision);
config_.mutable_precision().set_from_command_line(precision);
DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --precision = {}",
config_.precision());
}
// --produce-model
if (opt_.isSet("--produce-models")) {
config_.mutable_produce_models().set_from_command_line(true);
DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --produce-models = {}",
config_.produce_models());
}
// --polytope
if (opt_.isSet("--polytope")) {
config_.mutable_use_polytope().set_from_command_line(true);
DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --polytope = {}",
config_.use_polytope());
}
// --forall-polytope
if (opt_.isSet("--forall-polytope")) {
config_.mutable_use_polytope_in_forall().set_from_command_line(true);
DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --forall-polytope = {}",
config_.use_polytope_in_forall());
}
// --worklist-fixpoint
if (opt_.isSet("--worklist-fixpoint")) {
config_.mutable_use_worklist_fixpoint().set_from_command_line(true);
DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --worklist-fixpoint = {}",
config_.use_worklist_fixpoint());
}
}
int MainProgram::Run() {
if (!is_options_all_valid_) {
return 1;
}
ExtractOptions();
const string& filename{*args_[0]};
if (!file_exists(filename)) {
cerr << "File not found: " << filename << "\n" << endl;
PrintUsage();
return 1;
}
const string extension{get_extension(filename)};
if (extension == "smt2") {
RunSmt2(filename, config_, opt_.isSet("--debug-scanning"),
opt_.isSet("--debug-parsing"));
} else if (extension == "dr") {
RunDr(filename, config_, opt_.isSet("--debug-scanning"),
opt_.isSet("--debug-parsing"));
} else {
cerr << "Unknown extension: " << filename << "\n" << endl;
PrintUsage();
return 1;
}
return 0;
}
} // namespace dreal
namespace {
void HandleSigInt(const int) {
// Properly exit so that we can see stat information produced by destructors
// even if a user press C-c.
std::exit(1);
}
} // namespace
int main(int argc, const char* argv[]) {
std::signal(SIGINT, HandleSigInt);
dreal::MainProgram main_program{argc, argv};
return main_program.Run();
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbGDALOverviewsBuilder.h"
#include <vector>
#include "gdal.h"
#include "otb_boost_string_header.h"
#include "otbGDALDriverManagerWrapper.h"
#include "otbSystem.h"
namespace otb
{
// Progress reporting functions compatible with GDAL C API
extern "C"
{
static int CPL_STDCALL otb_UpdateGDALProgress( double dfComplete,
const char * itkNotUsed( pszMessage ),
void * pProgressArg )
{
otb::GDALOverviewsBuilder* _this = (otb::GDALOverviewsBuilder*)pProgressArg;
_this->UpdateProgress(dfComplete);
return 1;
}
}
char const * const
GDAL_RESAMPLING_NAMES[ GDAL_RESAMPLING_COUNT ] =
{
"NONE",
"NEAREST",
"GAUSS",
"CUBIC",
"AVERAGE",
"MODE",
"AVERAGE_MAGPHASE"
};
char const * const
GDAL_COMPRESSION_NAMES[ GDAL_COMPRESSION_COUNT ] =
{
"",
"JPEG",
"LZW",
"PACKBITS",
"DEFLATE",
};
/***************************************************************************/
std::string
GetConfigOption( const char * key )
{
const char * value = CPLGetConfigOption( key, NULL );
return
value==NULL
? std::string()
: std::string( value );
}
/***************************************************************************/
GDALOverviewsBuilder
::GDALOverviewsBuilder() :
m_GdalDataset(),
m_InputFileName(),
m_NbResolutions( 1 ),
m_ResolutionFactor( 2 ),
m_ResamplingMethod( GDAL_RESAMPLING_NEAREST ),
m_CompressionMethod( GDAL_COMPRESSION_NONE ),
m_Format( GDAL_FORMAT_GEOTIFF )
{
Superclass::SetNumberOfRequiredInputs(0);
Superclass::SetNumberOfRequiredOutputs(0);
}
/***************************************************************************/
unsigned int
GDALOverviewsBuilder
::CountResolutions( unsigned int factor, unsigned int n ) const
{
assert( factor>1 );
if( factor<=1 )
return 0;
assert( !m_GdalDataset.IsNull() );
unsigned int minSize = static_cast< unsigned int >( pow( factor, n ) );
unsigned int count = 1;
unsigned int size =
std::min(
m_GdalDataset->GetWidth(),
m_GdalDataset->GetHeight()
);
while( size >= minSize )
{
++ count;
size /= factor;
}
return count;
}
/***************************************************************************/
unsigned int
GDALOverviewsBuilder
::CountResolutions() const
{
return CountResolutions( m_ResolutionFactor );
}
/***************************************************************************/
void
GDALOverviewsBuilder
::ListResolutions( SizeVector & sizes )
{
ListResolutions( sizes, m_ResolutionFactor, m_NbResolutions );
}
/***************************************************************************/
void
GDALOverviewsBuilder
::ListResolutions( SizeVector & sizes, unsigned int factor, unsigned int count )
{
assert( factor>1 );
if( factor<=1 )
return;
assert( !m_GdalDataset.IsNull() );
Size s;
s[ 0 ] = m_GdalDataset->GetWidth();
s[ 1 ] = m_GdalDataset->GetHeight();
unsigned int n = std::min( count, CountResolutions( factor, 0 ) );
for( unsigned int i=0; i<n; ++i )
{
sizes.push_back( s );
s[ 0 ] /= factor;
s[ 1 ] /= factor;
}
}
/***************************************************************************/
unsigned int
GDALOverviewsBuilder
::GetOverviewsCount() const
{
assert( !m_GdalDataset.IsNull() );
return m_GdalDataset->GetOverviewsCount();
}
/***************************************************************************/
GDALResampling
GDALOverviewsBuilder
::GetResamplingMethod() const
{
return m_ResamplingMethod;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetResamplingMethod( GDALResamplingType resampling )
{
m_ResamplingMethod = resampling;
};
/***************************************************************************/
GDALCompression
GDALOverviewsBuilder
::GetCompressionMethod() const
{
return m_CompressionMethod;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetCompressionMethod( GDALCompression compression )
{
m_CompressionMethod = compression;
}
/***************************************************************************/
GDALFormat
GDALOverviewsBuilder
::GetFormat() const
{
return m_Format;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetFormat( GDALFormat format )
{
m_Format = format;
}
/***************************************************************************/
unsigned int
GDALOverviewsBuilder
::GetNbResolutions() const
{
return m_NbResolutions;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetNbResolutions( unsigned int n )
{
m_NbResolutions = n;
};
/***************************************************************************/
unsigned int
GDALOverviewsBuilder
::GetResolutionFactor() const
{
return m_ResolutionFactor;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetResolutionFactor( unsigned int factor )
{
m_ResolutionFactor = factor;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetInputFileName( const std::string & filename )
{
try
{
OpenDataset( filename );
}
catch( ... )
{
throw;
}
m_InputFileName = filename;
};
/***************************************************************************/
void
GDALOverviewsBuilder
::PrintSelf( std::ostream& os, itk::Indent indent ) const
{
Superclass::PrintSelf(os,indent);
os << indent << "Input Filename: " << m_InputFileName << std::endl;
os << indent << "Number of Resolution requested: " << m_NbResolutions << std::endl;
os << indent << "Resampling method: " << m_ResamplingMethod << std::endl;
}
/***************************************************************************/
/*
void
GDALOverviewsBuilder
::GetGDALResamplingMethod( std::string & resamplingMethod )
{
resamplingMethod.clear();
switch(m_ResamplingMethod)
{
case GDAL_RESAMPLING_NONE:
resamplingMethod = "NONE";
break;
case GDAL_RESAMPLING_NEAREST:
resamplingMethod = "NEAREST";
break;
case GDAL_RESAMPLING_GAUSS:
resamplingMethod = "GAUSS";
break;
case GDAL_RESAMPLING_CUBIC:
resamplingMethod = "CUBIC";
break;
case GDAL_RESAMPLING_AVERAGE:
resamplingMethod = "AVERAGE";
break;
case GDAL_RESAMPLING_MODE:
resamplingMethod = "MODE";
break;
case GDAL_RESAMPLING_AVERAGE_MAGPHASE:
resamplingMethod = "AVERAGE_MAGPHASE";
break;
default:
resamplingMethod = "NONE";
break;
}
}
*/
/***************************************************************************/
void GDALOverviewsBuilder::Update()
{
// typedef itk::SmartPointer<GDALDatasetWrapper> GDALDatasetWrapperPointer;
// GDALDatasetWrapperPointer wrappedDataset =
// GDALDriverManagerWrapper::GetInstance().Open(m_InputFileName);
// if (wrappedDataset.IsNull())
// {
// itkExceptionMacro(<< "Error while opening the file "<< m_InputFileName.c_str() << ".");
// }
assert( !m_GdalDataset.IsNull() );
assert( m_NbResolutions>0 );
if( m_NbResolutions==0 )
{
itkExceptionMacro(
<< "Wrong number of resolutions: " << m_NbResolutions
);
}
// Build the overviews list from nb of resolution desired
std::vector< int > ovwlist;
unsigned int factor = 1;
for( unsigned int i = 1; i < m_NbResolutions; i++ )
{
factor*=m_ResolutionFactor;
ovwlist.push_back(factor);
}
/*std::cout << "list of overviews level= ";
for (unsigned int i = 0; i < ovwlist.size(); i++)
{
std::cout << ovwlist[i] << ",";
}
std::cout << std::endl; */
std::string erdas( GetConfigOption( "USE_RRD" ) );
CPLSetConfigOption(
"USE_RRD",
m_Format==GDAL_FORMAT_ERDAS
? "YES"
: "NO"
);
assert(
m_CompressionMethod>=GDAL_COMPRESSION_NONE &&
m_CompressionMethod<GDAL_COMPRESSION_COUNT
);
std::string compression( GetConfigOption( "COMPRESS_OVERVIEW" ) );
CPLSetConfigOption(
"COMPRESS_OVERVIEW",
GDAL_COMPRESSION_NAMES[ m_CompressionMethod ]
);
assert(
m_ResamplingMethod>=GDAL_RESAMPLING_NONE &&
m_ResamplingMethod<GDAL_RESAMPLING_COUNT
);
CPLErr lCrGdal =
m_GdalDataset->GetDataSet()->BuildOverviews(
GDAL_RESAMPLING_NAMES[ m_ResamplingMethod ],
static_cast< int >( m_NbResolutions - 1 ),
&ovwlist.front(),
0, // All bands
NULL, // All bands
( GDALProgressFunc )otb_UpdateGDALProgress,
this );
CPLSetConfigOption( "USE_RRD", erdas.c_str() );
CPLSetConfigOption( "COMPRESS_OVERVIEW", compression.c_str() );
if (lCrGdal == CE_Failure)
{
itkExceptionMacro(<< "Error while building the GDAL overviews from " << m_InputFileName.c_str() << ".");
}
}
/***************************************************************************/
void
GDALOverviewsBuilder
::OpenDataset( const std::string & filename )
{
GDALDatasetWrapper::Pointer dataset(
GDALDriverManagerWrapper::GetInstance().Open( filename )
);
if( dataset.IsNull() )
itkExceptionMacro(
<< "Error while opening file '"
<< filename.c_str()
<< "' as GDAL dataset."
);
m_GdalDataset = dataset;
}
} // end namespace otb
<commit_msg>ENH: Hardened GDALOverviewsBuilder::CountResolutions().<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbGDALOverviewsBuilder.h"
#include <vector>
#include "gdal.h"
#include "otb_boost_string_header.h"
#include "otbGDALDriverManagerWrapper.h"
#include "otbSystem.h"
namespace otb
{
// Progress reporting functions compatible with GDAL C API
extern "C"
{
static int CPL_STDCALL otb_UpdateGDALProgress( double dfComplete,
const char * itkNotUsed( pszMessage ),
void * pProgressArg )
{
otb::GDALOverviewsBuilder* _this = (otb::GDALOverviewsBuilder*)pProgressArg;
_this->UpdateProgress(dfComplete);
return 1;
}
}
char const * const
GDAL_RESAMPLING_NAMES[ GDAL_RESAMPLING_COUNT ] =
{
"NONE",
"NEAREST",
"GAUSS",
"CUBIC",
"AVERAGE",
"MODE",
"AVERAGE_MAGPHASE"
};
char const * const
GDAL_COMPRESSION_NAMES[ GDAL_COMPRESSION_COUNT ] =
{
"",
"JPEG",
"LZW",
"PACKBITS",
"DEFLATE",
};
/***************************************************************************/
std::string
GetConfigOption( const char * key )
{
const char * value = CPLGetConfigOption( key, NULL );
return
value==NULL
? std::string()
: std::string( value );
}
/***************************************************************************/
GDALOverviewsBuilder
::GDALOverviewsBuilder() :
m_GdalDataset(),
m_InputFileName(),
m_NbResolutions( 1 ),
m_ResolutionFactor( 2 ),
m_ResamplingMethod( GDAL_RESAMPLING_NEAREST ),
m_CompressionMethod( GDAL_COMPRESSION_NONE ),
m_Format( GDAL_FORMAT_GEOTIFF )
{
Superclass::SetNumberOfRequiredInputs(0);
Superclass::SetNumberOfRequiredOutputs(0);
}
/***************************************************************************/
unsigned int
GDALOverviewsBuilder
::CountResolutions( unsigned int factor, unsigned int n ) const
{
assert( factor>1 );
if( factor<=1 )
return 0;
assert( !m_GdalDataset.IsNull() );
unsigned int minSize = static_cast< unsigned int >( pow( factor, n ) );
unsigned int size =
std::min(
m_GdalDataset->GetWidth(),
m_GdalDataset->GetHeight()
);
if( size<minSize )
return 0;
unsigned int count = 0;
while( size >= minSize )
{
++ count;
size /= factor;
}
return count;
}
/***************************************************************************/
unsigned int
GDALOverviewsBuilder
::CountResolutions() const
{
return CountResolutions( m_ResolutionFactor );
}
/***************************************************************************/
void
GDALOverviewsBuilder
::ListResolutions( SizeVector & sizes )
{
ListResolutions( sizes, m_ResolutionFactor, m_NbResolutions );
}
/***************************************************************************/
void
GDALOverviewsBuilder
::ListResolutions( SizeVector & sizes, unsigned int factor, unsigned int count )
{
assert( factor>1 );
if( factor<=1 )
return;
assert( !m_GdalDataset.IsNull() );
Size s;
s[ 0 ] = m_GdalDataset->GetWidth();
s[ 1 ] = m_GdalDataset->GetHeight();
unsigned int n = std::min( count, CountResolutions( factor, 0 ) );
for( unsigned int i=0; i<n; ++i )
{
sizes.push_back( s );
s[ 0 ] /= factor;
s[ 1 ] /= factor;
}
}
/***************************************************************************/
unsigned int
GDALOverviewsBuilder
::GetOverviewsCount() const
{
assert( !m_GdalDataset.IsNull() );
return m_GdalDataset->GetOverviewsCount();
}
/***************************************************************************/
GDALResampling
GDALOverviewsBuilder
::GetResamplingMethod() const
{
return m_ResamplingMethod;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetResamplingMethod( GDALResamplingType resampling )
{
m_ResamplingMethod = resampling;
};
/***************************************************************************/
GDALCompression
GDALOverviewsBuilder
::GetCompressionMethod() const
{
return m_CompressionMethod;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetCompressionMethod( GDALCompression compression )
{
m_CompressionMethod = compression;
}
/***************************************************************************/
GDALFormat
GDALOverviewsBuilder
::GetFormat() const
{
return m_Format;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetFormat( GDALFormat format )
{
m_Format = format;
}
/***************************************************************************/
unsigned int
GDALOverviewsBuilder
::GetNbResolutions() const
{
return m_NbResolutions;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetNbResolutions( unsigned int n )
{
m_NbResolutions = n;
};
/***************************************************************************/
unsigned int
GDALOverviewsBuilder
::GetResolutionFactor() const
{
return m_ResolutionFactor;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetResolutionFactor( unsigned int factor )
{
m_ResolutionFactor = factor;
}
/***************************************************************************/
void
GDALOverviewsBuilder
::SetInputFileName( const std::string & filename )
{
try
{
OpenDataset( filename );
}
catch( ... )
{
throw;
}
m_InputFileName = filename;
};
/***************************************************************************/
void
GDALOverviewsBuilder
::PrintSelf( std::ostream& os, itk::Indent indent ) const
{
Superclass::PrintSelf(os,indent);
os << indent << "Input Filename: " << m_InputFileName << std::endl;
os << indent << "Number of Resolution requested: " << m_NbResolutions << std::endl;
os << indent << "Resampling method: " << m_ResamplingMethod << std::endl;
}
/***************************************************************************/
/*
void
GDALOverviewsBuilder
::GetGDALResamplingMethod( std::string & resamplingMethod )
{
resamplingMethod.clear();
switch(m_ResamplingMethod)
{
case GDAL_RESAMPLING_NONE:
resamplingMethod = "NONE";
break;
case GDAL_RESAMPLING_NEAREST:
resamplingMethod = "NEAREST";
break;
case GDAL_RESAMPLING_GAUSS:
resamplingMethod = "GAUSS";
break;
case GDAL_RESAMPLING_CUBIC:
resamplingMethod = "CUBIC";
break;
case GDAL_RESAMPLING_AVERAGE:
resamplingMethod = "AVERAGE";
break;
case GDAL_RESAMPLING_MODE:
resamplingMethod = "MODE";
break;
case GDAL_RESAMPLING_AVERAGE_MAGPHASE:
resamplingMethod = "AVERAGE_MAGPHASE";
break;
default:
resamplingMethod = "NONE";
break;
}
}
*/
/***************************************************************************/
void GDALOverviewsBuilder::Update()
{
// typedef itk::SmartPointer<GDALDatasetWrapper> GDALDatasetWrapperPointer;
// GDALDatasetWrapperPointer wrappedDataset =
// GDALDriverManagerWrapper::GetInstance().Open(m_InputFileName);
// if (wrappedDataset.IsNull())
// {
// itkExceptionMacro(<< "Error while opening the file "<< m_InputFileName.c_str() << ".");
// }
assert( !m_GdalDataset.IsNull() );
assert( m_NbResolutions>0 );
if( m_NbResolutions==0 )
{
itkExceptionMacro(
<< "Wrong number of resolutions: " << m_NbResolutions
);
}
// Build the overviews list from nb of resolution desired
std::vector< int > ovwlist;
unsigned int factor = 1;
for( unsigned int i = 1; i < m_NbResolutions; i++ )
{
factor*=m_ResolutionFactor;
ovwlist.push_back(factor);
}
/*std::cout << "list of overviews level= ";
for (unsigned int i = 0; i < ovwlist.size(); i++)
{
std::cout << ovwlist[i] << ",";
}
std::cout << std::endl; */
std::string erdas( GetConfigOption( "USE_RRD" ) );
CPLSetConfigOption(
"USE_RRD",
m_Format==GDAL_FORMAT_ERDAS
? "YES"
: "NO"
);
assert(
m_CompressionMethod>=GDAL_COMPRESSION_NONE &&
m_CompressionMethod<GDAL_COMPRESSION_COUNT
);
std::string compression( GetConfigOption( "COMPRESS_OVERVIEW" ) );
CPLSetConfigOption(
"COMPRESS_OVERVIEW",
GDAL_COMPRESSION_NAMES[ m_CompressionMethod ]
);
assert(
m_ResamplingMethod>=GDAL_RESAMPLING_NONE &&
m_ResamplingMethod<GDAL_RESAMPLING_COUNT
);
CPLErr lCrGdal =
m_GdalDataset->GetDataSet()->BuildOverviews(
GDAL_RESAMPLING_NAMES[ m_ResamplingMethod ],
static_cast< int >( m_NbResolutions - 1 ),
&ovwlist.front(),
0, // All bands
NULL, // All bands
( GDALProgressFunc )otb_UpdateGDALProgress,
this );
CPLSetConfigOption( "USE_RRD", erdas.c_str() );
CPLSetConfigOption( "COMPRESS_OVERVIEW", compression.c_str() );
if (lCrGdal == CE_Failure)
{
itkExceptionMacro(<< "Error while building the GDAL overviews from " << m_InputFileName.c_str() << ".");
}
}
/***************************************************************************/
void
GDALOverviewsBuilder
::OpenDataset( const std::string & filename )
{
GDALDatasetWrapper::Pointer dataset(
GDALDriverManagerWrapper::GetInstance().Open( filename )
);
if( dataset.IsNull() )
itkExceptionMacro(
<< "Error while opening file '"
<< filename.c_str()
<< "' as GDAL dataset."
);
m_GdalDataset = dataset;
}
} // end namespace otb
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2012, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
/*
* orr_octree_zprojection.cpp
*
* Created on: Nov 17, 2012
* Author: papazov
*/
#include <pcl/recognition/ransac_based/orr_octree_zprojection.h>
#include <vector>
using namespace std;
//=========================================================================================================================================
void
pcl::recognition::ORROctreeZProjection::clear ()
{
if ( pixels_ )
{
for ( int i = 0 ; i < num_pixels_x_ ; ++i )
{
// Delete pixel by pixel
for ( int j = 0 ; j < num_pixels_y_ ; ++j )
if ( pixels_[i][j] )
delete pixels_[i][j];
// Delete the whole row
delete[] pixels_[i];
}
delete[] pixels_;
pixels_ = NULL;
}
if ( sets_ )
{
for ( int i = 0 ; i < num_pixels_x_ ; ++i )
{
for ( int j = 0 ; j < num_pixels_y_ ; ++j )
if ( sets_[i][j] )
delete sets_[i][j];
delete[] sets_[i];
}
delete[] sets_;
sets_ = NULL;
}
full_sets_.clear ();
full_pixels_.clear ();
}
//=========================================================================================================================================
void
pcl::recognition::ORROctreeZProjection::build (const ORROctree& input, float eps_front, float eps_back)
{
this->clear();
// Compute the bounding box of the full leaves
const vector<ORROctree::Node*>& full_leaves = input.getFullLeaves ();
vector<ORROctree::Node*>::const_iterator fl_it = full_leaves.begin ();
float full_leaves_bounds[4];
if ( full_leaves.empty() )
return;
// The initialization run
full_leaves_bounds[0] = (*fl_it)->getBounds ()[0];
full_leaves_bounds[1] = (*fl_it)->getBounds ()[1];
full_leaves_bounds[2] = (*fl_it)->getBounds ()[2];
full_leaves_bounds[3] = (*fl_it)->getBounds ()[3];
for ( ++fl_it ; fl_it != full_leaves.end () ; ++fl_it )
{
if ( (*fl_it)->getBounds ()[0] < full_leaves_bounds[0] ) full_leaves_bounds[0] = (*fl_it)->getBounds ()[0];
if ( (*fl_it)->getBounds ()[1] > full_leaves_bounds[1] ) full_leaves_bounds[1] = (*fl_it)->getBounds ()[1];
if ( (*fl_it)->getBounds ()[2] < full_leaves_bounds[2] ) full_leaves_bounds[2] = (*fl_it)->getBounds ()[2];
if ( (*fl_it)->getBounds ()[3] > full_leaves_bounds[3] ) full_leaves_bounds[3] = (*fl_it)->getBounds ()[3];
}
// Make some initializations
pixel_size_ = input.getVoxelSize();
inv_pixel_size_ = 1.0f/pixel_size_;
bounds_[0] = full_leaves_bounds[0]; bounds_[1] = full_leaves_bounds[1];
bounds_[2] = full_leaves_bounds[2]; bounds_[3] = full_leaves_bounds[3];
extent_x_ = full_leaves_bounds[1] - full_leaves_bounds[0];
extent_y_ = full_leaves_bounds[3] - full_leaves_bounds[2];
num_pixels_x_ = static_cast<int> (extent_x_/pixel_size_ + 0.5f); // we do not need to round, but it's safer due to numerical errors
num_pixels_y_ = static_cast<int> (extent_y_/pixel_size_ + 0.5f);
num_pixels_ = num_pixels_x_*num_pixels_y_;
int i, j;
// Allocate and initialize memory for the pixels and the sets
pixels_ = new Pixel**[num_pixels_x_];
sets_ = new Set**[num_pixels_x_];
for ( i = 0 ; i < num_pixels_x_ ; ++i )
{
pixels_[i] = new Pixel*[num_pixels_y_];
sets_[i] = new Set*[num_pixels_y_];
for ( j = 0 ; j < num_pixels_y_ ; ++j )
{
pixels_[i][j] = NULL;
sets_[i][j] = NULL;
}
}
int pixel_id = 0;
// Project the octree full leaves onto the xy-plane
for ( fl_it = full_leaves.begin () ; fl_it != full_leaves.end () ; ++fl_it )
{
this->getPixelCoordinates ((*fl_it)->getCenter(), i, j);
// If there is no set/pixel and at this position -> create one
if ( sets_[i][j] == NULL )
{
pixels_[i][j] = new Pixel (pixel_id++);
sets_[i][j] = new Set (i, j);
full_pixels_.push_back (pixels_[i][j]);
full_sets_.push_back (sets_[i][j]);
}
// Insert the full octree leaf at the right position in the set
sets_[i][j]->insert (*fl_it);
}
int len, maxlen, id_z1, id_z2;
float cur_min, best_min, cur_max, best_max;
// Now, at each occupied (i, j) position, get the longest connected component consisting of neighboring full leaves
for ( list<Set*>::iterator current_set = full_sets_.begin () ; current_set != full_sets_.end () ; ++current_set )
{
// Get the first node in the set
set<ORROctree::Node*, bool(*)(ORROctree::Node*,ORROctree::Node*)>::iterator node = (*current_set)->get_nodes ().begin ();
// Initialize
cur_min = best_min = (*node)->getBounds ()[4];
cur_max = best_max = (*node)->getBounds ()[5];
id_z1 = (*node)->getData ()->get3dIdZ ();
maxlen = len = 1;
// Find the longest 1D "connected component" at the current (i, j) position
for ( ++node ; node != (*current_set)->get_nodes ().end () ; ++node, id_z1 = id_z2 )
{
id_z2 = (*node)->getData ()->get3dIdZ ();
cur_max = (*node)->getBounds()[5];
if ( id_z2 - id_z1 > 1 ) // This connected component is over
{
// Start a new connected component
cur_min = (*node)->getBounds ()[4];
len = 1;
}
else // This connected component is still ongoing
{
++len;
if ( len > maxlen )
{
// This connected component is the longest one
maxlen = len;
best_min = cur_min;
best_max = cur_max;
}
}
}
i = (*current_set)->get_x ();
j = (*current_set)->get_y ();
pixels_[i][j]->set_z1 (best_min - eps_front);
pixels_[i][j]->set_z2 (best_max + eps_back);
}
}
<commit_msg>Use range-based loop in ORROctreeZProjection::build<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2012, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
/*
* orr_octree_zprojection.cpp
*
* Created on: Nov 17, 2012
* Author: papazov
*/
#include <pcl/recognition/ransac_based/orr_octree_zprojection.h>
#include <array>
#include <vector>
using namespace std;
//=========================================================================================================================================
void
pcl::recognition::ORROctreeZProjection::clear ()
{
if ( pixels_ )
{
for ( int i = 0 ; i < num_pixels_x_ ; ++i )
{
// Delete pixel by pixel
for ( int j = 0 ; j < num_pixels_y_ ; ++j )
if ( pixels_[i][j] )
delete pixels_[i][j];
// Delete the whole row
delete[] pixels_[i];
}
delete[] pixels_;
pixels_ = NULL;
}
if ( sets_ )
{
for ( int i = 0 ; i < num_pixels_x_ ; ++i )
{
for ( int j = 0 ; j < num_pixels_y_ ; ++j )
if ( sets_[i][j] )
delete sets_[i][j];
delete[] sets_[i];
}
delete[] sets_;
sets_ = NULL;
}
full_sets_.clear ();
full_pixels_.clear ();
}
//=========================================================================================================================================
void
pcl::recognition::ORROctreeZProjection::build (const ORROctree& input, float eps_front, float eps_back)
{
this->clear();
// Compute the bounding box of the full leaves
const vector<ORROctree::Node*>& full_leaves = input.getFullLeaves ();
vector<ORROctree::Node*>::const_iterator fl_it = full_leaves.begin ();
std::array<float, 4> full_leaves_bounds;
if ( full_leaves.empty() )
return;
// The initialization run
full_leaves_bounds[0] = std::numeric_limits<float>::infinity();
full_leaves_bounds[1] = -std::numeric_limits<float>::infinity();
full_leaves_bounds[2] = std::numeric_limits<float>::infinity();
full_leaves_bounds[3] = -std::numeric_limits<float>::infinity();
for (const auto& leave : full_leaves)
{
const auto bounds = leave->getBounds ();
if ( bounds[0] < full_leaves_bounds[0] ) full_leaves_bounds[0] = bounds[0];
if ( bounds[1] > full_leaves_bounds[1] ) full_leaves_bounds[1] = bounds[1];
if ( bounds[2] < full_leaves_bounds[2] ) full_leaves_bounds[2] = bounds[2];
if ( bounds[3] > full_leaves_bounds[3] ) full_leaves_bounds[3] = bounds[3];
}
// Make some initializations
pixel_size_ = input.getVoxelSize();
inv_pixel_size_ = 1.0f/pixel_size_;
bounds_[0] = full_leaves_bounds[0]; bounds_[1] = full_leaves_bounds[1];
bounds_[2] = full_leaves_bounds[2]; bounds_[3] = full_leaves_bounds[3];
extent_x_ = full_leaves_bounds[1] - full_leaves_bounds[0];
extent_y_ = full_leaves_bounds[3] - full_leaves_bounds[2];
num_pixels_x_ = static_cast<int> (extent_x_/pixel_size_ + 0.5f); // we do not need to round, but it's safer due to numerical errors
num_pixels_y_ = static_cast<int> (extent_y_/pixel_size_ + 0.5f);
num_pixels_ = num_pixels_x_*num_pixels_y_;
int i, j;
// Allocate and initialize memory for the pixels and the sets
pixels_ = new Pixel**[num_pixels_x_];
sets_ = new Set**[num_pixels_x_];
for ( i = 0 ; i < num_pixels_x_ ; ++i )
{
pixels_[i] = new Pixel*[num_pixels_y_];
sets_[i] = new Set*[num_pixels_y_];
for ( j = 0 ; j < num_pixels_y_ ; ++j )
{
pixels_[i][j] = NULL;
sets_[i][j] = NULL;
}
}
int pixel_id = 0;
// Project the octree full leaves onto the xy-plane
for ( fl_it = full_leaves.begin () ; fl_it != full_leaves.end () ; ++fl_it )
{
this->getPixelCoordinates ((*fl_it)->getCenter(), i, j);
// If there is no set/pixel and at this position -> create one
if ( sets_[i][j] == NULL )
{
pixels_[i][j] = new Pixel (pixel_id++);
sets_[i][j] = new Set (i, j);
full_pixels_.push_back (pixels_[i][j]);
full_sets_.push_back (sets_[i][j]);
}
// Insert the full octree leaf at the right position in the set
sets_[i][j]->insert (*fl_it);
}
int len, maxlen, id_z1, id_z2;
float cur_min, best_min, cur_max, best_max;
// Now, at each occupied (i, j) position, get the longest connected component consisting of neighboring full leaves
for ( list<Set*>::iterator current_set = full_sets_.begin () ; current_set != full_sets_.end () ; ++current_set )
{
// Get the first node in the set
set<ORROctree::Node*, bool(*)(ORROctree::Node*,ORROctree::Node*)>::iterator node = (*current_set)->get_nodes ().begin ();
// Initialize
cur_min = best_min = (*node)->getBounds ()[4];
cur_max = best_max = (*node)->getBounds ()[5];
id_z1 = (*node)->getData ()->get3dIdZ ();
maxlen = len = 1;
// Find the longest 1D "connected component" at the current (i, j) position
for ( ++node ; node != (*current_set)->get_nodes ().end () ; ++node, id_z1 = id_z2 )
{
id_z2 = (*node)->getData ()->get3dIdZ ();
cur_max = (*node)->getBounds()[5];
if ( id_z2 - id_z1 > 1 ) // This connected component is over
{
// Start a new connected component
cur_min = (*node)->getBounds ()[4];
len = 1;
}
else // This connected component is still ongoing
{
++len;
if ( len > maxlen )
{
// This connected component is the longest one
maxlen = len;
best_min = cur_min;
best_max = cur_max;
}
}
}
i = (*current_set)->get_x ();
j = (*current_set)->get_y ();
pixels_[i][j]->set_z1 (best_min - eps_front);
pixels_[i][j]->set_z2 (best_max + eps_back);
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** Copyright (C) 2011 - 2013 Research In Motion
**
** Contact: Research In Motion ([email protected])
** Contact: KDAB ([email protected])
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "blackberrydeviceinformation.h"
namespace {
static const char PROCESS_NAME[] = "blackberry-deploy";
static const char ERR_NO_ROUTE_HOST[] = "Cannot connect";
static const char ERR_AUTH_FAILED[] = "Authentication failed";
static const char ERR_DEVELOPMENT_MODE_DISABLED[] = "Device is not in the Development Mode";
}
namespace Qnx {
namespace Internal {
BlackBerryDeviceInformation::BlackBerryDeviceInformation(QObject *parent) :
BlackBerryNdkProcess(QLatin1String(PROCESS_NAME), parent)
{
addErrorStringMapping(QLatin1String(ERR_NO_ROUTE_HOST), NoRouteToHost);
addErrorStringMapping(QLatin1String(ERR_AUTH_FAILED), AuthenticationFailed);
addErrorStringMapping(QLatin1String(ERR_DEVELOPMENT_MODE_DISABLED), DevelopmentModeDisabled);
}
void BlackBerryDeviceInformation::setDeviceTarget(const QString &deviceIp, const QString &devicePassword)
{
QStringList arguments;
arguments << QLatin1String("-listDeviceInfo")
<< QLatin1String("-device")
<< deviceIp
<< QLatin1String("-password")
<< devicePassword;
start(arguments);
}
void BlackBerryDeviceInformation::resetResults()
{
m_devicePin.clear();
m_deviceOS.clear();
m_hardwareId.clear();
m_debugTokenAuthor.clear();
m_scmBundle.clear();
m_hostName.clear();
m_debugTokenValid = false;
m_isSimulator = false;
}
QString BlackBerryDeviceInformation::devicePin() const
{
return m_devicePin;
}
QString BlackBerryDeviceInformation::deviceOS() const
{
return m_deviceOS;
}
QString BlackBerryDeviceInformation::hardwareId() const
{
return m_hardwareId;
}
QString BlackBerryDeviceInformation::debugTokenAuthor() const
{
return m_debugTokenAuthor;
}
QString BlackBerryDeviceInformation::scmBundle() const
{
return m_scmBundle;
}
QString BlackBerryDeviceInformation::hostName() const
{
return m_hostName;
}
bool BlackBerryDeviceInformation::debugTokenValid() const
{
return m_debugTokenValid;
}
bool BlackBerryDeviceInformation::isSimulator() const
{
return m_isSimulator;
}
void BlackBerryDeviceInformation::processData(const QString &line)
{
if (line.startsWith(QLatin1String("devicepin::0x")))
m_devicePin = line.mid(QLatin1String("devicepin::0x").size()).trimmed();
else if (line.startsWith(QLatin1String("device_os::")))
m_deviceOS = line.mid(QLatin1String("device_os::").size()).trimmed();
else if (line.startsWith(QLatin1String("hardwareid::")))
m_hardwareId = line.mid(QLatin1String("hardwareid::").size()).trimmed();
else if (line.startsWith(QLatin1String("debug_token_author::")))
m_debugTokenAuthor = line.mid(QLatin1String("debug_token_author::").size()).trimmed();
else if (line.startsWith(QLatin1String("debug_token_valid:b:")))
m_debugTokenValid = line.mid(QLatin1String("debug_token_valid:b:").size()).trimmed()
== QLatin1String("true");
else if (line.startsWith(QLatin1String("simulator:b:")))
m_isSimulator = line.mid(QLatin1String("simulator:b:").size()).trimmed()
== QLatin1String("true");
else if (line.startsWith(QLatin1String("scmbundle::")))
m_scmBundle = line.mid(QLatin1String("scmbundle::").size()).trimmed();
else if (line.startsWith(QLatin1String("hostname::")))
m_hostName = line.mid(QLatin1String("hostname::").size()).trimmed();
}
} // namespace Internal
} // namespace Qnx
<commit_msg>Fix compilation<commit_after>/**************************************************************************
**
** Copyright (C) 2011 - 2013 Research In Motion
**
** Contact: Research In Motion ([email protected])
** Contact: KDAB ([email protected])
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "blackberrydeviceinformation.h"
namespace {
static const char PROCESS_NAME[] = "blackberry-deploy";
static const char ERR_NO_ROUTE_HOST[] = "Cannot connect";
static const char ERR_AUTH_FAILED[] = "Authentication failed";
static const char ERR_DEVELOPMENT_MODE_DISABLED[] = "Device is not in the Development Mode";
}
namespace Qnx {
namespace Internal {
BlackBerryDeviceInformation::BlackBerryDeviceInformation(QObject *parent) :
BlackBerryNdkProcess(QLatin1String(PROCESS_NAME), parent)
{
addErrorStringMapping(QLatin1String(ERR_NO_ROUTE_HOST), NoRouteToHost);
addErrorStringMapping(QLatin1String(ERR_AUTH_FAILED), AuthenticationFailed);
addErrorStringMapping(QLatin1String(ERR_DEVELOPMENT_MODE_DISABLED), DevelopmentModeDisabled);
}
void BlackBerryDeviceInformation::setDeviceTarget(const QString &deviceIp, const QString &devicePassword)
{
QStringList arguments;
arguments << QLatin1String("-listDeviceInfo")
<< QLatin1String("-device")
<< deviceIp
<< QLatin1String("-password")
<< devicePassword;
start(arguments);
}
void BlackBerryDeviceInformation::resetResults()
{
m_devicePin.clear();
m_deviceOS.clear();
m_hardwareId.clear();
m_debugTokenAuthor.clear();
m_scmBundle.clear();
m_hostName.clear();
m_debugTokenValid = false;
m_isSimulator = false;
}
QString BlackBerryDeviceInformation::devicePin() const
{
return m_devicePin;
}
QString BlackBerryDeviceInformation::deviceOS() const
{
return m_deviceOS;
}
QString BlackBerryDeviceInformation::hardwareId() const
{
return m_hardwareId;
}
QString BlackBerryDeviceInformation::debugTokenAuthor() const
{
return m_debugTokenAuthor;
}
QString BlackBerryDeviceInformation::scmBundle() const
{
return m_scmBundle;
}
QString BlackBerryDeviceInformation::hostName() const
{
return m_hostName;
}
bool BlackBerryDeviceInformation::debugTokenValid() const
{
return m_debugTokenValid;
}
bool BlackBerryDeviceInformation::isSimulator() const
{
return m_isSimulator;
}
void BlackBerryDeviceInformation::processData(const QString &line)
{
static const QString devicepin = QLatin1String("devicepin::0x");
static const QString device_os = QLatin1String("device_os::");
static const QString hardwareid = QLatin1String("hardwareid::");
static const QString debug_token_author = QLatin1String("debug_token_author::");
static const QString debug_token_valid = QLatin1String("debug_token_valid:b:");
static const QString simulator = QLatin1String("simulator:b:");
static const QString scmbundle = QLatin1String("scmbundle::");
static const QString hostname = QLatin1String("hostname::");
if (line.startsWith(devicepin))
m_devicePin = line.mid(devicepin.size()).trimmed();
else if (line.startsWith(device_os))
m_deviceOS = line.mid(device_os.size()).trimmed();
else if (line.startsWith(hardwareid))
m_hardwareId = line.mid(hardwareid.size()).trimmed();
else if (line.startsWith(debug_token_author))
m_debugTokenAuthor = line.mid(debug_token_author.size()).trimmed();
else if (line.startsWith(debug_token_valid))
m_debugTokenValid = line.mid(debug_token_valid.size()).trimmed() == QLatin1String("true");
else if (line.startsWith(simulator))
m_isSimulator = line.mid(simulator.size()).trimmed() == QLatin1String("true");
else if (line.startsWith(scmbundle))
m_scmBundle = line.mid(scmbundle.size()).trimmed();
else if (line.startsWith(hostname))
m_hostName = line.mid(hostname.size()).trimmed();
}
} // namespace Internal
} // namespace Qnx
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "query_pagers.hh"
#include "query_pager.hh"
#include "cql3/selection/selection.hh"
#include "log.hh"
static logging::logger logger("paging");
class service::pager::query_pagers::impl : public query_pager {
public:
impl(schema_ptr s, ::shared_ptr<cql3::selection::selection> selection,
service::query_state& state,
const cql3::query_options& options,
lw_shared_ptr<query::read_command> cmd,
std::vector<query::partition_range> ranges)
: _has_clustering_keys(s->clustering_key_size() > 0)
, _max(cmd->row_limit)
, _schema(std::move(s))
, _selection(selection)
, _state(state)
, _options(options)
, _cmd(std::move(cmd))
, _ranges(std::move(ranges))
{}
private:
future<> fetch_page(cql3::selection::result_set_builder& builder, uint32_t page_size, db_clock::time_point now) override {
auto state = _options.get_paging_state();
if (!_last_pkey && state) {
_max = state->get_remaining();
_last_pkey = state->get_partition_key();
_last_ckey = state->get_clustering_key();
}
if (_last_pkey) {
auto dpk = dht::global_partitioner().decorate_key(*_schema, *_last_pkey);
dht::ring_position lo(dpk);
auto reversed = _cmd->slice.options.contains<query::partition_slice::option::reversed>();
logger.trace("PKey={}, CKey={}, reversed={}", dpk, *_last_ckey, reversed);
// Note: we're assuming both that the ranges are checked
// and "cql-compliant", and that storage_proxy will process
// the ranges in order
//
// If the original query has singular restrictions like "col in (x, y, z)",
// we will eventually generate an empty range. This is ok, because empty range == nothing,
// which is what we thus mean.
auto modify_ranges = [reversed](auto& ranges, auto& lo, bool inclusive, const auto& cmp) {
typedef typename std::remove_reference_t<decltype(ranges)>::value_type range_type;
typedef typename range_type::bound bound_type;
bool found = false;
auto i = ranges.begin();
while (i != ranges.end()) {
bool contains = i->contains(lo, cmp);
if (contains) {
found = true;
}
bool remove = !found
|| (contains && (i->is_singular() && !inclusive))
;
if (remove) {
logger.trace("Remove range {}", *i);
i = ranges.erase(i);
continue;
}
if (contains) {
auto r = reversed && !i->is_singular()
? range_type(i->start(), bound_type{ lo, inclusive })
: range_type( bound_type{ lo, inclusive }, i->end(), i->is_singular())
;
logger.trace("Modify range {} -> {}", *i, r);
*i = std::move(r);
}
++i;
}
logger.trace("Result ranges {}", ranges);
};
// last ck can be empty depending on whether we
// deserialized state or not. This case means "last page ended on
// something-not-bound-by-clustering" (i.e. a static row, alone)
const bool has_ck = _has_clustering_keys && _last_ckey;
// If we have no clustering keys, it should mean we only have one row
// per PK. Thus we can just bypass the last one.
modify_ranges(_ranges, lo, has_ck, dht::ring_position_comparator(*_schema));
if (has_ck) {
query::clustering_row_ranges row_ranges = _cmd->slice.default_row_ranges();
clustering_key_prefix ckp = clustering_key_prefix::from_exploded(*_schema, _last_ckey->explode(*_schema));
clustering_key_prefix::less_compare cmp_rt(*_schema);
modify_ranges(row_ranges, ckp, false, [&cmp_rt](auto& c1, auto c2) {
if (cmp_rt(c1, c2)) {
return -1;
} else if (cmp_rt(c2, c1)) {
return 1;
}
return 0;
});
_cmd->slice.set_range(*_schema, *_last_pkey, row_ranges);
}
}
auto max_rows = std::min(_max, page_size);
// We always need PK so we can determine where to start next.
_cmd->slice.options.set<query::partition_slice::option::send_partition_key>();
// don't add empty bytes (cks) unless we have to
if (_has_clustering_keys) {
_cmd->slice.options.set<
query::partition_slice::option::send_clustering_key>();
}
_cmd->row_limit = max_rows;
logger.debug("Fetching {}, page size={}, max_rows={}",
_cmd->cf_id, page_size, max_rows
);
auto ranges = _ranges;
return get_local_storage_proxy().query(_schema, _cmd, std::move(ranges),
_options.get_consistency()).then(
[this, &builder, page_size, now](foreign_ptr<lw_shared_ptr<query::result>> results) {
handle_result(builder, std::move(results), page_size, now);
});
}
future<std::unique_ptr<cql3::result_set>> fetch_page(uint32_t page_size,
db_clock::time_point now) override {
return do_with(
cql3::selection::result_set_builder(*_selection, now,
_options.get_serialization_format()),
[this, page_size, now](auto& builder) {
return this->fetch_page(builder, page_size, now).then([&builder] {
return builder.build();
});
});
}
void handle_result(
cql3::selection::result_set_builder& builder,
foreign_ptr<lw_shared_ptr<query::result>> results,
uint32_t page_size, db_clock::time_point now) {
class myvisitor : public cql3::selection::result_set_builder::visitor {
public:
impl& _impl;
uint32_t page_size;
uint32_t part_rows = 0;
uint32_t included_rows = 0;
uint32_t total_rows = 0;
std::experimental::optional<partition_key> last_pkey;
std::experimental::optional<clustering_key> last_ckey;
// just for verbosity
uint32_t part_ignored = 0;
clustering_key::less_compare _less;
bool include_row() {
++total_rows;
++part_rows;
if (included_rows >= page_size) {
++part_ignored;
return false;
}
++included_rows;
return true;
}
bool include_row(const clustering_key& key) {
if (!include_row()) {
return false;
}
if (included_rows == page_size) {
last_ckey = key;
}
return true;
}
myvisitor(impl& i, uint32_t ps,
cql3::selection::result_set_builder& builder,
const schema& s,
const cql3::selection::selection& selection)
: visitor(builder, s, selection), _impl(i), page_size(ps), _less(*_impl._schema) {
}
void accept_new_partition(uint32_t) {
throw std::logic_error("Should not reach!");
}
void accept_new_partition(const partition_key& key, uint32_t row_count) {
logger.trace("Begin partition: {} ({})", key, row_count);
part_rows = 0;
part_ignored = 0;
if (included_rows < page_size) {
last_pkey = key;
}
visitor::accept_new_partition(key, row_count);
}
void accept_new_row(const clustering_key& key,
const query::result_row_view& static_row,
const query::result_row_view& row) {
// TODO: should we use exception/long jump or introduce
// a "stop" condition to the calling result_view and
// avoid processing unneeded rows?
auto ok = include_row(key);
if (ok) {
visitor::accept_new_row(key, static_row, row);
}
}
void accept_new_row(const query::result_row_view& static_row,
const query::result_row_view& row) {
auto ok = include_row();
if (ok) {
visitor::accept_new_row(static_row, row);
}
}
void accept_partition_end(const query::result_row_view& static_row) {
// accept_partition_end with row_count == 0
// means we had an empty partition but live
// static columns, and since the fix,
// no CK restrictions.
// I.e. _row_count == 0 -> add a partially empty row
// So, treat this case as an accept_row variant
if (_row_count > 0 || include_row()) {
visitor::accept_partition_end(static_row);
}
logger.trace(
"End partition, included={}, ignored={}",
part_rows - part_ignored,
part_ignored);
}
};
myvisitor v(*this, std::min(page_size, _max), builder, *_schema, *_selection);
query::result_view::consume(results->buf(), _cmd->slice, v);
if (_last_pkey) {
// refs #752, when doing aggregate queries we will re-use same
// slice repeatedly. Since "specific ck ranges" only deal with
// a single extra range, we must clear out the old one
// Even if it was not so of course, leaving junk in the slice
// is bad.
_cmd->slice.clear_range(*_schema, *_last_pkey);
}
_max = _max - v.included_rows;
_exhausted = v.included_rows < page_size || _max == 0;
_last_pkey = v.last_pkey;
_last_ckey = v.last_ckey;
logger.debug("Fetched {}/{} rows, max_remain={} {}", v.included_rows, v.total_rows,
_max, _exhausted ? "(exh)" : "");
if (_last_pkey) {
logger.debug("Last partition key: {}", *_last_pkey);
}
if (_has_clustering_keys && _last_ckey) {
logger.debug("Last clustering key: {}", *_last_ckey);
}
}
bool is_exhausted() const override {
return _exhausted;
}
int max_remaining() const override {
return _max;
}
::shared_ptr<const service::pager::paging_state> state() const override {
return _exhausted ?
nullptr :
::make_shared<const paging_state>(*_last_pkey,
_last_ckey, _max);
}
private:
// remember if we use clustering. if not, each partition == one row
const bool _has_clustering_keys;
bool _exhausted = false;
uint32_t _rem = 0;
uint32_t _max;
std::experimental::optional<partition_key> _last_pkey;
std::experimental::optional<clustering_key> _last_ckey;
schema_ptr _schema;
::shared_ptr<cql3::selection::selection> _selection;
service::query_state& _state;
const cql3::query_options& _options;
lw_shared_ptr<query::read_command> _cmd;
std::vector<query::partition_range> _ranges;
};
bool service::pager::query_pagers::may_need_paging(uint32_t page_size,
const query::read_command& cmd,
const std::vector<query::partition_range>& ranges) {
auto est_max_rows =
[&] {
if (ranges.empty()) {
return cmd.row_limit;
}
uint32_t n = 0;
for (auto& r : ranges) {
if (r.is_singular() && cmd.slice.options.contains<query::partition_slice::option::distinct>()) {
++n;
continue;
}
return cmd.row_limit;
}
return n;
};
auto est = est_max_rows();
auto need_paging = est > page_size;
logger.debug("Query of {}, page_size={}, limit={} requires paging",
cmd.cf_id, page_size, cmd.row_limit);
return need_paging;
}
::shared_ptr<service::pager::query_pager> service::pager::query_pagers::pager(
schema_ptr s, ::shared_ptr<cql3::selection::selection> selection,
service::query_state& state, const cql3::query_options& options,
lw_shared_ptr<query::read_command> cmd,
std::vector<query::partition_range> ranges) {
return ::make_shared<impl>(std::move(s), std::move(selection), state,
options, std::move(cmd), std::move(ranges));
}
<commit_msg>query_pagers: fix log message in requires_paging<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "query_pagers.hh"
#include "query_pager.hh"
#include "cql3/selection/selection.hh"
#include "log.hh"
static logging::logger logger("paging");
class service::pager::query_pagers::impl : public query_pager {
public:
impl(schema_ptr s, ::shared_ptr<cql3::selection::selection> selection,
service::query_state& state,
const cql3::query_options& options,
lw_shared_ptr<query::read_command> cmd,
std::vector<query::partition_range> ranges)
: _has_clustering_keys(s->clustering_key_size() > 0)
, _max(cmd->row_limit)
, _schema(std::move(s))
, _selection(selection)
, _state(state)
, _options(options)
, _cmd(std::move(cmd))
, _ranges(std::move(ranges))
{}
private:
future<> fetch_page(cql3::selection::result_set_builder& builder, uint32_t page_size, db_clock::time_point now) override {
auto state = _options.get_paging_state();
if (!_last_pkey && state) {
_max = state->get_remaining();
_last_pkey = state->get_partition_key();
_last_ckey = state->get_clustering_key();
}
if (_last_pkey) {
auto dpk = dht::global_partitioner().decorate_key(*_schema, *_last_pkey);
dht::ring_position lo(dpk);
auto reversed = _cmd->slice.options.contains<query::partition_slice::option::reversed>();
logger.trace("PKey={}, CKey={}, reversed={}", dpk, *_last_ckey, reversed);
// Note: we're assuming both that the ranges are checked
// and "cql-compliant", and that storage_proxy will process
// the ranges in order
//
// If the original query has singular restrictions like "col in (x, y, z)",
// we will eventually generate an empty range. This is ok, because empty range == nothing,
// which is what we thus mean.
auto modify_ranges = [reversed](auto& ranges, auto& lo, bool inclusive, const auto& cmp) {
typedef typename std::remove_reference_t<decltype(ranges)>::value_type range_type;
typedef typename range_type::bound bound_type;
bool found = false;
auto i = ranges.begin();
while (i != ranges.end()) {
bool contains = i->contains(lo, cmp);
if (contains) {
found = true;
}
bool remove = !found
|| (contains && (i->is_singular() && !inclusive))
;
if (remove) {
logger.trace("Remove range {}", *i);
i = ranges.erase(i);
continue;
}
if (contains) {
auto r = reversed && !i->is_singular()
? range_type(i->start(), bound_type{ lo, inclusive })
: range_type( bound_type{ lo, inclusive }, i->end(), i->is_singular())
;
logger.trace("Modify range {} -> {}", *i, r);
*i = std::move(r);
}
++i;
}
logger.trace("Result ranges {}", ranges);
};
// last ck can be empty depending on whether we
// deserialized state or not. This case means "last page ended on
// something-not-bound-by-clustering" (i.e. a static row, alone)
const bool has_ck = _has_clustering_keys && _last_ckey;
// If we have no clustering keys, it should mean we only have one row
// per PK. Thus we can just bypass the last one.
modify_ranges(_ranges, lo, has_ck, dht::ring_position_comparator(*_schema));
if (has_ck) {
query::clustering_row_ranges row_ranges = _cmd->slice.default_row_ranges();
clustering_key_prefix ckp = clustering_key_prefix::from_exploded(*_schema, _last_ckey->explode(*_schema));
clustering_key_prefix::less_compare cmp_rt(*_schema);
modify_ranges(row_ranges, ckp, false, [&cmp_rt](auto& c1, auto c2) {
if (cmp_rt(c1, c2)) {
return -1;
} else if (cmp_rt(c2, c1)) {
return 1;
}
return 0;
});
_cmd->slice.set_range(*_schema, *_last_pkey, row_ranges);
}
}
auto max_rows = std::min(_max, page_size);
// We always need PK so we can determine where to start next.
_cmd->slice.options.set<query::partition_slice::option::send_partition_key>();
// don't add empty bytes (cks) unless we have to
if (_has_clustering_keys) {
_cmd->slice.options.set<
query::partition_slice::option::send_clustering_key>();
}
_cmd->row_limit = max_rows;
logger.debug("Fetching {}, page size={}, max_rows={}",
_cmd->cf_id, page_size, max_rows
);
auto ranges = _ranges;
return get_local_storage_proxy().query(_schema, _cmd, std::move(ranges),
_options.get_consistency()).then(
[this, &builder, page_size, now](foreign_ptr<lw_shared_ptr<query::result>> results) {
handle_result(builder, std::move(results), page_size, now);
});
}
future<std::unique_ptr<cql3::result_set>> fetch_page(uint32_t page_size,
db_clock::time_point now) override {
return do_with(
cql3::selection::result_set_builder(*_selection, now,
_options.get_serialization_format()),
[this, page_size, now](auto& builder) {
return this->fetch_page(builder, page_size, now).then([&builder] {
return builder.build();
});
});
}
void handle_result(
cql3::selection::result_set_builder& builder,
foreign_ptr<lw_shared_ptr<query::result>> results,
uint32_t page_size, db_clock::time_point now) {
class myvisitor : public cql3::selection::result_set_builder::visitor {
public:
impl& _impl;
uint32_t page_size;
uint32_t part_rows = 0;
uint32_t included_rows = 0;
uint32_t total_rows = 0;
std::experimental::optional<partition_key> last_pkey;
std::experimental::optional<clustering_key> last_ckey;
// just for verbosity
uint32_t part_ignored = 0;
clustering_key::less_compare _less;
bool include_row() {
++total_rows;
++part_rows;
if (included_rows >= page_size) {
++part_ignored;
return false;
}
++included_rows;
return true;
}
bool include_row(const clustering_key& key) {
if (!include_row()) {
return false;
}
if (included_rows == page_size) {
last_ckey = key;
}
return true;
}
myvisitor(impl& i, uint32_t ps,
cql3::selection::result_set_builder& builder,
const schema& s,
const cql3::selection::selection& selection)
: visitor(builder, s, selection), _impl(i), page_size(ps), _less(*_impl._schema) {
}
void accept_new_partition(uint32_t) {
throw std::logic_error("Should not reach!");
}
void accept_new_partition(const partition_key& key, uint32_t row_count) {
logger.trace("Begin partition: {} ({})", key, row_count);
part_rows = 0;
part_ignored = 0;
if (included_rows < page_size) {
last_pkey = key;
}
visitor::accept_new_partition(key, row_count);
}
void accept_new_row(const clustering_key& key,
const query::result_row_view& static_row,
const query::result_row_view& row) {
// TODO: should we use exception/long jump or introduce
// a "stop" condition to the calling result_view and
// avoid processing unneeded rows?
auto ok = include_row(key);
if (ok) {
visitor::accept_new_row(key, static_row, row);
}
}
void accept_new_row(const query::result_row_view& static_row,
const query::result_row_view& row) {
auto ok = include_row();
if (ok) {
visitor::accept_new_row(static_row, row);
}
}
void accept_partition_end(const query::result_row_view& static_row) {
// accept_partition_end with row_count == 0
// means we had an empty partition but live
// static columns, and since the fix,
// no CK restrictions.
// I.e. _row_count == 0 -> add a partially empty row
// So, treat this case as an accept_row variant
if (_row_count > 0 || include_row()) {
visitor::accept_partition_end(static_row);
}
logger.trace(
"End partition, included={}, ignored={}",
part_rows - part_ignored,
part_ignored);
}
};
myvisitor v(*this, std::min(page_size, _max), builder, *_schema, *_selection);
query::result_view::consume(results->buf(), _cmd->slice, v);
if (_last_pkey) {
// refs #752, when doing aggregate queries we will re-use same
// slice repeatedly. Since "specific ck ranges" only deal with
// a single extra range, we must clear out the old one
// Even if it was not so of course, leaving junk in the slice
// is bad.
_cmd->slice.clear_range(*_schema, *_last_pkey);
}
_max = _max - v.included_rows;
_exhausted = v.included_rows < page_size || _max == 0;
_last_pkey = v.last_pkey;
_last_ckey = v.last_ckey;
logger.debug("Fetched {}/{} rows, max_remain={} {}", v.included_rows, v.total_rows,
_max, _exhausted ? "(exh)" : "");
if (_last_pkey) {
logger.debug("Last partition key: {}", *_last_pkey);
}
if (_has_clustering_keys && _last_ckey) {
logger.debug("Last clustering key: {}", *_last_ckey);
}
}
bool is_exhausted() const override {
return _exhausted;
}
int max_remaining() const override {
return _max;
}
::shared_ptr<const service::pager::paging_state> state() const override {
return _exhausted ?
nullptr :
::make_shared<const paging_state>(*_last_pkey,
_last_ckey, _max);
}
private:
// remember if we use clustering. if not, each partition == one row
const bool _has_clustering_keys;
bool _exhausted = false;
uint32_t _rem = 0;
uint32_t _max;
std::experimental::optional<partition_key> _last_pkey;
std::experimental::optional<clustering_key> _last_ckey;
schema_ptr _schema;
::shared_ptr<cql3::selection::selection> _selection;
service::query_state& _state;
const cql3::query_options& _options;
lw_shared_ptr<query::read_command> _cmd;
std::vector<query::partition_range> _ranges;
};
bool service::pager::query_pagers::may_need_paging(uint32_t page_size,
const query::read_command& cmd,
const std::vector<query::partition_range>& ranges) {
auto est_max_rows =
[&] {
if (ranges.empty()) {
return cmd.row_limit;
}
uint32_t n = 0;
for (auto& r : ranges) {
if (r.is_singular() && cmd.slice.options.contains<query::partition_slice::option::distinct>()) {
++n;
continue;
}
return cmd.row_limit;
}
return n;
};
auto est = est_max_rows();
auto need_paging = est > page_size;
logger.debug("Query of {}, page_size={}, limit={} {}", cmd.cf_id, page_size,
cmd.row_limit,
need_paging ? "requires paging" : "does not require paging");
return need_paging;
}
::shared_ptr<service::pager::query_pager> service::pager::query_pagers::pager(
schema_ptr s, ::shared_ptr<cql3::selection::selection> selection,
service::query_state& state, const cql3::query_options& options,
lw_shared_ptr<query::read_command> cmd,
std::vector<query::partition_range> ranges) {
return ::make_shared<impl>(std::move(s), std::move(selection), state,
options, std::move(cmd), std::move(ranges));
}
<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCPVPModule.cpp
// @Author : LvSheng.Huang
// @Date : 2017-02-02
// @Module : NFCPVPModule
//
// -------------------------------------------------------------------------
#include "NFCPVPModule.h"
#include "NFComm/NFPluginModule/NFINetModule.h"
#include "NFComm/NFMessageDefine/NFMsgShare.pb.h"
#include "NFComm/NFMessageDefine/NFProtocolDefine.hpp"
bool NFCPVPModule::Init()
{
m_pTileModule = pPluginManager->FindModule<NFITileModule>();
m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
m_pClassModule = pPluginManager->FindModule<NFIClassModule>();
m_pNetModule = pPluginManager->FindModule<NFINetModule>();
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pLogModule = pPluginManager->FindModule<NFILogModule>();
m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>();
m_pPlayerRedisModule = pPluginManager->FindModule<NFIPlayerRedisModule>();
m_pSceneAOIModule = pPluginManager->FindModule<NFISceneAOIModule>();
m_pPropertyModule = pPluginManager->FindModule<NFIPropertyModule>();
m_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>();
return true;
}
bool NFCPVPModule::Shut()
{
return true;
}
bool NFCPVPModule::Execute()
{
return true;
}
bool NFCPVPModule::AfterInit()
{
FindAllTileScene();
m_pSceneAOIModule->AddEnterSceneConditionCallBack(this, &NFCPVPModule::EnterSceneConditionEvent);
m_pSceneAOIModule->AddBeforeEnterSceneGroupCallBack(this, &NFCPVPModule::BeforeEnterSceneGroupEvent);
m_pSceneAOIModule->AddAfterEnterSceneGroupCallBack(this, &NFCPVPModule::AfterEnterSceneGroupEvent);
m_pSceneAOIModule->AddBeforeLeaveSceneGroupCallBack(this, &NFCPVPModule::BeforeLeaveSceneGroupEvent);
m_pSceneAOIModule->AddAfterLeaveSceneGroupCallBack(this, &NFCPVPModule::AfterLeaveSceneGroupEvent);
if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_SEARCH_OPPNENT, this, &NFCPVPModule::OnReqSearchOppnentProcess)) { return false; }
if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_SWAP_HOME_SCENE, this, &NFCPVPModule::OnReqSwapHomeSceneProcess)) { return false; }
if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_START_OPPNENT, this, &NFCPVPModule::OnReqStartPVPOppnentProcess)) { return false; }
if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_END_OPPNENT, this, &NFCPVPModule::OnReqEndPVPOppnentProcess)) { return false; }
return true;
}
bool NFCPVPModule::ReadyExecute()
{
m_pSceneAOIModule->RemoveSwapSceneEventCallBack();
m_pSceneAOIModule->AddSwapSceneEventCallBack(this, &NFCPVPModule::OnSceneEvent);
return false;
}
void NFCPVPModule::OnReqSearchOppnentProcess(const int nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqSearchOppnent);
//find a tile map and swap scene
int nSceneID = RandomTileScene();
std::string strTileData;
NFGUID xViewOppnent;
if (m_pPlayerRedisModule->LoadPlayerTileRandom(nSceneID, xViewOppnent, strTileData))
{
NFMsg::AckMiningTitle xTileData;
if (xTileData.ParseFromString(strTileData))
{
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::ViewOppnent(), xViewOppnent);
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::FightOppnent(), NFGUID());
m_pSceneProcessModule->RequestEnterScene(nPlayerID, nSceneID, 0, NFDataList());
//tell client u shoud adjust tile
//m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_MINING_TITLE, xTileData, nPlayerID);
//tell client u should load resources
NFMsg::AckSearchOppnent xAckData;
xAckData.set_scene_id(nSceneID);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_SEARCH_OPPNENT, xAckData, nPlayerID);
return;
}
else
{
//failed
NFMsg::AckSearchOppnent xAckData;
xAckData.set_scene_id(0);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_SEARCH_OPPNENT, xAckData, nPlayerID);
}
}
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, nPlayerID, "ERROR TO FIND A OPPNENT!", "", __FUNCTION__, __LINE__);
}
void NFCPVPModule::OnReqSwapHomeSceneProcess(const int nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqAckHomeScene);
int nHomeSceneID = m_pKernelModule->GetPropertyInt(nPlayerID, NFrame::Player::HomeSceneID());
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::ViewOppnent(), nPlayerID);
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::FightOppnent(), NFGUID());
m_pSceneProcessModule->RequestEnterScene(nPlayerID, nHomeSceneID, 0, NFDataList());
/*
//send tile's data to client
std::string strTileData;
if (m_pPlayerRedisModule->LoadPlayerTile(nHomeSceneID, nPlayerID, strTileData))
{
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_MINING_TITLE, strTileData, nPlayerID);
}
*/
}
void NFCPVPModule::OnReqStartPVPOppnentProcess(const int nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqAckStartBattle);
NFGUID xViewOppnent = m_pKernelModule->GetPropertyObject(nPlayerID, NFrame::Player::ViewOppnent());
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::FightOppnent(), xViewOppnent);
int nGambleGold = xMsg.gold();
int nGambleDiamond = xMsg.diamond();
if (nGambleGold > 0)
{
m_pKernelModule->SetPropertyInt(nPlayerID, NFrame::Player::GambleGold(), nGambleGold);
}
if (nGambleDiamond > 0)
{
m_pKernelModule->SetPropertyInt(nPlayerID, NFrame::Player::GambleDiamond(), nGambleDiamond);
}
NFMsg::ReqAckStartBattle xReqAckStartBattle;
xReqAckStartBattle.set_gold(nGambleGold);
xReqAckStartBattle.set_diamond(nGambleDiamond);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_START_OPPNENT, xReqAckStartBattle, nPlayerID);
}
void NFCPVPModule::OnReqEndPVPOppnentProcess(const int nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqEndBattle);
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::ViewOppnent(), NFGUID());
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::FightOppnent(), NFGUID());
//get oppnent
//calculate how many monster has been killed
//calculate how many building has been destroyed
//calculate how much experice and how many money
//tell client the end information
//set oppnent 0
int nGambleGold = m_pKernelModule->GetPropertyInt(nPlayerID, NFrame::Player::GambleGold());
int nGambleDiamond = m_pKernelModule->GetPropertyInt(nPlayerID, NFrame::Player::GambleDiamond());
m_pPropertyModule->AddGold(nPlayerID, nGambleGold);
m_pPropertyModule->AddDiamond(nPlayerID, nGambleDiamond);
NFMsg::AckEndBattle xReqAckEndBattle;
xReqAckEndBattle.set_win(1);
xReqAckEndBattle.set_star(2);
xReqAckEndBattle.set_gold(nGambleGold);
xReqAckEndBattle.set_exp(0);
xReqAckEndBattle.set_diamond(nGambleDiamond);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_END_OPPNENT, xReqAckEndBattle, nPlayerID);
}
void NFCPVPModule::FindAllTileScene()
{
//Tile
//mxTileSceneIDList
NF_SHARE_PTR<NFIClass> xLogicClass = m_pClassModule->GetElement(NFrame::Scene::ThisName());
if (xLogicClass)
{
NFList<std::string>& strIdList = xLogicClass->GetIdList();
std::string strId;
for (bool bRet = strIdList.First(strId); bRet; bRet = strIdList.Next(strId))
{
const int nServerType = m_pElementModule->GetPropertyInt(strId, NFrame::Scene::Tile());
if (nServerType == 1)
{
mxTileSceneIDList.push_back(lexical_cast<int>(strId));
}
}
}
}
void NFCPVPModule::InitAllTileSceneRobot()
{
for (int i = 0; i < mxTileSceneIDList.size(); ++i)
{
int nSceneID = mxTileSceneIDList[i];
}
}
int NFCPVPModule::OnSceneEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
std::string strTileData;
NFVector3 vRelivePos = m_pSceneAOIModule->GetRelivePosition(nSceneID, 0);
NFGUID xViewOppnent = m_pKernelModule->GetPropertyObject(self, NFrame::Player::ViewOppnent());
NFMsg::ReqAckSwapScene xAckSwapScene;
xAckSwapScene.set_scene_id(nSceneID);
xAckSwapScene.set_transfer_type(NFMsg::ReqAckSwapScene::EGameSwapType::ReqAckSwapScene_EGameSwapType_EGST_NARMAL);
xAckSwapScene.set_line_id(0);
xAckSwapScene.set_x(vRelivePos.X());
xAckSwapScene.set_y(vRelivePos.Y());
xAckSwapScene.set_z(vRelivePos.Z());
if (self == xViewOppnent)
{
m_pKernelModule->SetPropertyObject(self, NFrame::Player::ViewOppnent(), NFGUID());
if (m_pTileModule->GetOnlinePlayerTileData(self, strTileData))
{
xAckSwapScene.set_data(strTileData.c_str());
}
}
else
{
if (m_pPlayerRedisModule->LoadPlayerTileRandomCache(xViewOppnent, strTileData))
{
xAckSwapScene.set_data(strTileData.c_str());
}
}
//attach tile data
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_SWAP_SCENE, xAckSwapScene, self);
return 0;
}
int NFCPVPModule::EnterSceneConditionEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
return 0;
}
int NFCPVPModule::BeforeEnterSceneGroupEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
return 0;
}
int NFCPVPModule::AfterEnterSceneGroupEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
return 0;
}
int NFCPVPModule::BeforeLeaveSceneGroupEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
return 0;
}
int NFCPVPModule::AfterLeaveSceneGroupEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
return 0;
}
int NFCPVPModule::RandomTileScene()
{
return mxTileSceneIDList.at(m_pKernelModule->Random(0, mxTileSceneIDList.size()));
}
<commit_msg>fixed for data length when set char* data<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCPVPModule.cpp
// @Author : LvSheng.Huang
// @Date : 2017-02-02
// @Module : NFCPVPModule
//
// -------------------------------------------------------------------------
#include "NFCPVPModule.h"
#include "NFComm/NFPluginModule/NFINetModule.h"
#include "NFComm/NFMessageDefine/NFMsgShare.pb.h"
#include "NFComm/NFMessageDefine/NFProtocolDefine.hpp"
bool NFCPVPModule::Init()
{
m_pTileModule = pPluginManager->FindModule<NFITileModule>();
m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
m_pClassModule = pPluginManager->FindModule<NFIClassModule>();
m_pNetModule = pPluginManager->FindModule<NFINetModule>();
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pLogModule = pPluginManager->FindModule<NFILogModule>();
m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>();
m_pPlayerRedisModule = pPluginManager->FindModule<NFIPlayerRedisModule>();
m_pSceneAOIModule = pPluginManager->FindModule<NFISceneAOIModule>();
m_pPropertyModule = pPluginManager->FindModule<NFIPropertyModule>();
m_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>();
return true;
}
bool NFCPVPModule::Shut()
{
return true;
}
bool NFCPVPModule::Execute()
{
return true;
}
bool NFCPVPModule::AfterInit()
{
FindAllTileScene();
m_pSceneAOIModule->AddEnterSceneConditionCallBack(this, &NFCPVPModule::EnterSceneConditionEvent);
m_pSceneAOIModule->AddBeforeEnterSceneGroupCallBack(this, &NFCPVPModule::BeforeEnterSceneGroupEvent);
m_pSceneAOIModule->AddAfterEnterSceneGroupCallBack(this, &NFCPVPModule::AfterEnterSceneGroupEvent);
m_pSceneAOIModule->AddBeforeLeaveSceneGroupCallBack(this, &NFCPVPModule::BeforeLeaveSceneGroupEvent);
m_pSceneAOIModule->AddAfterLeaveSceneGroupCallBack(this, &NFCPVPModule::AfterLeaveSceneGroupEvent);
if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_SEARCH_OPPNENT, this, &NFCPVPModule::OnReqSearchOppnentProcess)) { return false; }
if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_SWAP_HOME_SCENE, this, &NFCPVPModule::OnReqSwapHomeSceneProcess)) { return false; }
if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_START_OPPNENT, this, &NFCPVPModule::OnReqStartPVPOppnentProcess)) { return false; }
if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_END_OPPNENT, this, &NFCPVPModule::OnReqEndPVPOppnentProcess)) { return false; }
return true;
}
bool NFCPVPModule::ReadyExecute()
{
m_pSceneAOIModule->RemoveSwapSceneEventCallBack();
m_pSceneAOIModule->AddSwapSceneEventCallBack(this, &NFCPVPModule::OnSceneEvent);
return false;
}
void NFCPVPModule::OnReqSearchOppnentProcess(const int nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqSearchOppnent);
//find a tile map and swap scene
int nSceneID = RandomTileScene();
std::string strTileData;
NFGUID xViewOppnent;
if (m_pPlayerRedisModule->LoadPlayerTileRandom(nSceneID, xViewOppnent, strTileData))
{
NFMsg::AckMiningTitle xTileData;
if (xTileData.ParseFromString(strTileData))
{
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::ViewOppnent(), xViewOppnent);
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::FightOppnent(), NFGUID());
m_pSceneProcessModule->RequestEnterScene(nPlayerID, nSceneID, 0, NFDataList());
//tell client u shoud adjust tile
//m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_MINING_TITLE, xTileData, nPlayerID);
//tell client u should load resources
NFMsg::AckSearchOppnent xAckData;
xAckData.set_scene_id(nSceneID);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_SEARCH_OPPNENT, xAckData, nPlayerID);
return;
}
else
{
//failed
NFMsg::AckSearchOppnent xAckData;
xAckData.set_scene_id(0);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_SEARCH_OPPNENT, xAckData, nPlayerID);
}
}
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, nPlayerID, "ERROR TO FIND A OPPNENT!", "", __FUNCTION__, __LINE__);
}
void NFCPVPModule::OnReqSwapHomeSceneProcess(const int nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqAckHomeScene);
int nHomeSceneID = m_pKernelModule->GetPropertyInt(nPlayerID, NFrame::Player::HomeSceneID());
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::ViewOppnent(), nPlayerID);
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::FightOppnent(), NFGUID());
m_pSceneProcessModule->RequestEnterScene(nPlayerID, nHomeSceneID, 0, NFDataList());
/*
//send tile's data to client
std::string strTileData;
if (m_pPlayerRedisModule->LoadPlayerTile(nHomeSceneID, nPlayerID, strTileData))
{
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_MINING_TITLE, strTileData, nPlayerID);
}
*/
}
void NFCPVPModule::OnReqStartPVPOppnentProcess(const int nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqAckStartBattle);
NFGUID xViewOppnent = m_pKernelModule->GetPropertyObject(nPlayerID, NFrame::Player::ViewOppnent());
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::FightOppnent(), xViewOppnent);
int nGambleGold = xMsg.gold();
int nGambleDiamond = xMsg.diamond();
if (nGambleGold > 0)
{
m_pKernelModule->SetPropertyInt(nPlayerID, NFrame::Player::GambleGold(), nGambleGold);
}
if (nGambleDiamond > 0)
{
m_pKernelModule->SetPropertyInt(nPlayerID, NFrame::Player::GambleDiamond(), nGambleDiamond);
}
NFMsg::ReqAckStartBattle xReqAckStartBattle;
xReqAckStartBattle.set_gold(nGambleGold);
xReqAckStartBattle.set_diamond(nGambleDiamond);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_START_OPPNENT, xReqAckStartBattle, nPlayerID);
}
void NFCPVPModule::OnReqEndPVPOppnentProcess(const int nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqEndBattle);
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::ViewOppnent(), NFGUID());
m_pKernelModule->SetPropertyObject(nPlayerID, NFrame::Player::FightOppnent(), NFGUID());
//get oppnent
//calculate how many monster has been killed
//calculate how many building has been destroyed
//calculate how much experice and how many money
//tell client the end information
//set oppnent 0
int nGambleGold = m_pKernelModule->GetPropertyInt(nPlayerID, NFrame::Player::GambleGold());
int nGambleDiamond = m_pKernelModule->GetPropertyInt(nPlayerID, NFrame::Player::GambleDiamond());
m_pPropertyModule->AddGold(nPlayerID, nGambleGold);
m_pPropertyModule->AddDiamond(nPlayerID, nGambleDiamond);
NFMsg::AckEndBattle xReqAckEndBattle;
xReqAckEndBattle.set_win(1);
xReqAckEndBattle.set_star(2);
xReqAckEndBattle.set_gold(nGambleGold);
xReqAckEndBattle.set_exp(0);
xReqAckEndBattle.set_diamond(nGambleDiamond);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_END_OPPNENT, xReqAckEndBattle, nPlayerID);
}
void NFCPVPModule::FindAllTileScene()
{
//Tile
//mxTileSceneIDList
NF_SHARE_PTR<NFIClass> xLogicClass = m_pClassModule->GetElement(NFrame::Scene::ThisName());
if (xLogicClass)
{
NFList<std::string>& strIdList = xLogicClass->GetIdList();
std::string strId;
for (bool bRet = strIdList.First(strId); bRet; bRet = strIdList.Next(strId))
{
const int nServerType = m_pElementModule->GetPropertyInt(strId, NFrame::Scene::Tile());
if (nServerType == 1)
{
mxTileSceneIDList.push_back(lexical_cast<int>(strId));
}
}
}
}
void NFCPVPModule::InitAllTileSceneRobot()
{
for (int i = 0; i < mxTileSceneIDList.size(); ++i)
{
int nSceneID = mxTileSceneIDList[i];
}
}
int NFCPVPModule::OnSceneEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
std::string strTileData;
NFVector3 vRelivePos = m_pSceneAOIModule->GetRelivePosition(nSceneID, 0);
NFGUID xViewOppnent = m_pKernelModule->GetPropertyObject(self, NFrame::Player::ViewOppnent());
NFMsg::ReqAckSwapScene xAckSwapScene;
xAckSwapScene.set_scene_id(nSceneID);
xAckSwapScene.set_transfer_type(NFMsg::ReqAckSwapScene::EGameSwapType::ReqAckSwapScene_EGameSwapType_EGST_NARMAL);
xAckSwapScene.set_line_id(0);
xAckSwapScene.set_x(vRelivePos.X());
xAckSwapScene.set_y(vRelivePos.Y());
xAckSwapScene.set_z(vRelivePos.Z());
if (self == xViewOppnent)
{
m_pKernelModule->SetPropertyObject(self, NFrame::Player::ViewOppnent(), NFGUID());
if (m_pTileModule->GetOnlinePlayerTileData(self, strTileData))
{
xAckSwapScene.set_data(strTileData.c_str(), strTileData.length());
}
}
else
{
if (m_pPlayerRedisModule->LoadPlayerTileRandomCache(xViewOppnent, strTileData))
{
xAckSwapScene.set_data(strTileData.c_str(), strTileData.length());
}
}
//attach tile data
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_SWAP_SCENE, xAckSwapScene, self);
return 0;
}
int NFCPVPModule::EnterSceneConditionEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
return 0;
}
int NFCPVPModule::BeforeEnterSceneGroupEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
return 0;
}
int NFCPVPModule::AfterEnterSceneGroupEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
return 0;
}
int NFCPVPModule::BeforeLeaveSceneGroupEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
return 0;
}
int NFCPVPModule::AfterLeaveSceneGroupEvent(const NFGUID & self, const int nSceneID, const int nGroupID, const int nType, const NFDataList & argList)
{
return 0;
}
int NFCPVPModule::RandomTileScene()
{
return mxTileSceneIDList.at(m_pKernelModule->Random(0, mxTileSceneIDList.size()));
}
<|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 "base/command_line.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/gl/gl_implementation.h"
namespace {
void SimulateGPUCrash(Browser* browser) {
LOG(ERROR) << "SimulateGPUCrash, before NavigateToURLWithDisposition";
ui_test_utils::NavigateToURLWithDisposition(browser,
GURL(chrome::kChromeUIGpuCrashURL), NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_NONE);
browser->SelectPreviousTab();
LOG(ERROR) << "SimulateGPUCrash, after CloseTab";
}
} // namespace
class GPUCrashTest : public InProcessBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) {
EnableDOMAutomation();
InProcessBrowserTest::SetUpCommandLine(command_line);
// GPU tests require gpu acceleration.
// We do not care which GL backend is used.
command_line->AppendSwitchASCII(switches::kUseGL, "any");
}
virtual void SetUpInProcessBrowserTestFixture() {
FilePath test_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
gpu_test_dir_ = test_dir.AppendASCII("gpu");
}
FilePath gpu_test_dir_;
};
// Currently Kill timeout on GPU Debug bots: http://crbug.com/101513
#if !defined(NDEBUG)
#define MAYBE_Kill DISABLED_Kill
#else
#define MAYBE_Kill Kill
#endif
IN_PROC_BROWSER_TEST_F(GPUCrashTest, MAYBE_Kill) {
ui_test_utils::DOMMessageQueue message_queue;
ui_test_utils::NavigateToURL(
browser(),
ui_test_utils::GetFileUrlWithQuery(
gpu_test_dir_.AppendASCII("webgl.html"), "query=kill"));
SimulateGPUCrash(browser());
std::string m;
ASSERT_TRUE(message_queue.WaitForMessage(&m));
EXPECT_EQ("\"SUCCESS\"", m);
}
IN_PROC_BROWSER_TEST_F(GPUCrashTest, WebkitLoseContext) {
ui_test_utils::DOMMessageQueue message_queue;
ui_test_utils::NavigateToURL(
browser(),
ui_test_utils::GetFileUrlWithQuery(
gpu_test_dir_.AppendASCII("webgl.html"),
"query=WEBGL_lose_context"));
std::string m;
ASSERT_TRUE(message_queue.WaitForMessage(&m));
EXPECT_EQ("\"SUCCESS\"", m);
}
<commit_msg>Disabling GPUCrashTest.Kill browser test.<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 "base/command_line.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/gl/gl_implementation.h"
namespace {
void SimulateGPUCrash(Browser* browser) {
LOG(ERROR) << "SimulateGPUCrash, before NavigateToURLWithDisposition";
ui_test_utils::NavigateToURLWithDisposition(browser,
GURL(chrome::kChromeUIGpuCrashURL), NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_NONE);
browser->SelectPreviousTab();
LOG(ERROR) << "SimulateGPUCrash, after CloseTab";
}
} // namespace
class GPUCrashTest : public InProcessBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) {
EnableDOMAutomation();
InProcessBrowserTest::SetUpCommandLine(command_line);
// GPU tests require gpu acceleration.
// We do not care which GL backend is used.
command_line->AppendSwitchASCII(switches::kUseGL, "any");
}
virtual void SetUpInProcessBrowserTestFixture() {
FilePath test_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
gpu_test_dir_ = test_dir.AppendASCII("gpu");
}
FilePath gpu_test_dir_;
};
// Currently Kill times out on GPU bots: http://crbug.com/101513
IN_PROC_BROWSER_TEST_F(GPUCrashTest, DISABLED_Kill) {
ui_test_utils::DOMMessageQueue message_queue;
ui_test_utils::NavigateToURL(
browser(),
ui_test_utils::GetFileUrlWithQuery(
gpu_test_dir_.AppendASCII("webgl.html"), "query=kill"));
SimulateGPUCrash(browser());
std::string m;
ASSERT_TRUE(message_queue.WaitForMessage(&m));
EXPECT_EQ("\"SUCCESS\"", m);
}
IN_PROC_BROWSER_TEST_F(GPUCrashTest, WebkitLoseContext) {
ui_test_utils::DOMMessageQueue message_queue;
ui_test_utils::NavigateToURL(
browser(),
ui_test_utils::GetFileUrlWithQuery(
gpu_test_dir_.AppendASCII("webgl.html"),
"query=WEBGL_lose_context"));
std::string m;
ASSERT_TRUE(message_queue.WaitForMessage(&m));
EXPECT_EQ("\"SUCCESS\"", m);
}
<|endoftext|>
|
<commit_before>/*! \file string.hpp
\brief Support for types found in \<string\>
\ingroup STLSupport */
/*
Copyright (c) 2014, Randolph Voorhies, Shane Grant
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of cereal 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 RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CEREAL_TYPES_STRING_HPP_
#define CEREAL_TYPES_STRING_HPP_
#include "../cereal.hpp"
#include <string>
namespace cereal
{
//! Serialization for basic_string types, if binary data is supported
template<class Archive, class CharT, class Traits, class Alloc> inline
typename std::enable_if<traits::is_output_serializable<BinaryData<CharT>, Archive>::value, void>::type
CEREAL_SAVE_FUNCTION_NAME(Archive & ar, std::basic_string<CharT, Traits, Alloc> const & str)
{
// Save number of chars + the data
ar( make_size_tag( static_cast<size_type>(str.size()) ) );
ar( binary_data( str.data(), str.size() * sizeof(CharT) ) );
}
//! Serialization for basic_string types, if binary data is supported
template<class Archive, class CharT, class Traits, class Alloc> inline
typename std::enable_if<traits::is_input_serializable<BinaryData<CharT>, Archive>::value, void>::type
CEREAL_LOAD_FUNCTION_NAME(Archive & ar, std::basic_string<CharT, Traits, Alloc> & str)
{
size_type size;
ar( make_size_tag( size ) );
str.resize(static_cast<std::size_t>(size));
ar( binary_data( const_cast<CharT *>( str.data() ), static_cast<std::size_t>(size) * sizeof(CharT) ) );
}
} // namespace cereal
#endif // CEREAL_TYPES_STRING_HPP_
<commit_msg>Workaround until cereal is not removed at all.<commit_after>/*! \file string.hpp
\brief Support for types found in \<string\>
\ingroup STLSupport */
/*
Copyright (c) 2014, Randolph Voorhies, Shane Grant
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of cereal 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 RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CEREAL_TYPES_STRING_HPP_
#define CEREAL_TYPES_STRING_HPP_
#include "../cereal.hpp"
#include <string>
namespace cereal
{
//! Serialization for basic_string types, if binary data is supported
template<class Archive, class CharT, class Traits, class Alloc> inline
typename std::enable_if<traits::is_output_serializable<BinaryData<CharT>, Archive>::value, void>::type
CEREAL_SAVE_FUNCTION_NAME(Archive & ar, std::basic_string<CharT, Traits, Alloc> const & str)
{
// Save number of chars + the data
ar( make_size_tag( static_cast<size_type>(str.size()) ) );
ar( binary_data( str.data(), str.size() * sizeof(CharT) ) );
}
//! Serialization for basic_string types, if binary data is supported
template<class Archive, class CharT, class Traits, class Alloc> inline
typename std::enable_if<traits::is_input_serializable<BinaryData<CharT>, Archive>::value, void>::type
CEREAL_LOAD_FUNCTION_NAME(Archive & ar, std::basic_string<CharT, Traits, Alloc> & str)
{
size_type size;
ar( make_size_tag( size ) );
// TODO(AlexZ): Workaround for binary deserialization.
static constexpr const auto kHundredMegabytes = 1024 * 1024 * 100;
if (size > kHundredMegabytes)
throw Exception("Size for string is too big " + std::to_string(size) + ", there is a high chance that data is corrupted.");
str.resize(static_cast<std::size_t>(size));
ar( binary_data( const_cast<CharT *>( str.data() ), static_cast<std::size_t>(size) * sizeof(CharT) ) );
}
} // namespace cereal
#endif // CEREAL_TYPES_STRING_HPP_
<|endoftext|>
|
<commit_before>/* This file is part of the KDE project
Copyright (C) 2005 Matthias Kretz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
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., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "mediaobject.h"
#include "mediaobject_p.h"
#include "factory.h"
#include "bytestreaminterface.h"
#include "mediaobjectinterface.h"
#include <kdebug.h>
#define PHONON_CLASSNAME MediaObject
#define PHONON_INTERFACENAME MediaObjectInterface
namespace Phonon
{
PHONON_HEIR_IMPL( AbstractMediaProducer )
MediaObject::MediaObject( Phonon::MediaObjectPrivate& dd, QObject* parent )
: AbstractMediaProducer( dd, parent )
{
}
PHONON_INTERFACE_GETTER( KUrl, url, d->url )
PHONON_GETTER( qint32, aboutToFinishTime, d->aboutToFinishTime )
qint64 MediaObject::totalTime() const
{
K_D( const MediaObject );
if( !d->backendObject )
return -1;
MediaObjectInterface *iface = qobject_cast<MediaObjectInterface*>( d->backendObject );
if( iface )
return iface->totalTime();
else
{
ByteStreamInterface *iface2 = qobject_cast<ByteStreamInterface*>( d->backendObject );
if( iface2 )
return iface2->totalTime();
}
return -1;
}
qint64 MediaObject::remainingTime() const
{
K_D( const MediaObject );
if( !d->backendObject )
return -1;
qint64 ret;
if( !BACKEND_GET( qint64, ret, "remainingTime" ) )
ret = totalTime() - currentTime();
if( ret < 0 )
return -1;
return ret;
}
void MediaObject::setUrl( const KUrl& url )
{
K_D( MediaObject );
d->url = url;
if( iface() )
{
stop(); // first call stop as that often is the expected state
// for setting a new URL
INTERFACE_CALL1( setUrl, url );
//FIXME: the stateChanged signal will be emitted. Perhaps it should be
//disabled for the setUrl call and then replayed when it didn't go into
//ErrorState
if( state() == Phonon::ErrorState )
{
d->deleteIface();
//at this point MediaObject uses a ByteStream
//instead and sends the data it receives from the KIO Job via writeBuffer.
//This essentially makes all media frameworks read data via KIO...
d->setupKioStreaming();
}
}
}
void MediaObject::stop()
{
AbstractMediaProducer::stop();
K_D( MediaObject );
if( d->kiojob )
{
d->kiojob->kill();
// if( do pre-buffering )
d->setupKioJob();
}
}
void MediaObject::play()
{
K_D( MediaObject );
Phonon::State s = state();
if( s == Phonon::LoadingState || s == Phonon::StoppedState )
{
if( !d->jobDone && !d->kiojob && qobject_cast<ByteStreamInterface*>( d->backendObject ) )
d->setupKioJob();
else
// when play() is called and the whole data was already streamed (KIO job is
// finished) we can play once, the next time play() is called a new
// KIO job is needed.
d->jobDone = false;
}
AbstractMediaProducer::play();
}
PHONON_SETTER( setAboutToFinishTime, aboutToFinishTime, qint32 )
void MediaObjectPrivate::setupKioJob()
{
K_Q( MediaObject );
Q_ASSERT( backendObject );
jobDone = false;
kiojob = KIO::get( url, false, false );
kiojob->addMetaData( "UserAgent", QLatin1String( "KDE Phonon" ) );
QObject::connect( kiojob, SIGNAL(data(KIO::Job*,const QByteArray&)),
q, SLOT(_k_bytestreamData(KIO::Job*,const QByteArray&)) );
QObject::connect( kiojob, SIGNAL(result(KJob*)),
q, SLOT(_k_bytestreamResult(KJob*)) );
QObject::connect( kiojob, SIGNAL(totalSize(KJob*, qulonglong)),
q, SLOT(_k_bytestreamTotalSize(KJob*,qulonglong)) );
QObject::connect( backendObject, SIGNAL(finished()), q, SIGNAL(finished()) );
QObject::connect( backendObject, SIGNAL(aboutToFinish(qint32)), q, SIGNAL(aboutToFinish(qint32)) );
QObject::connect( backendObject, SIGNAL(length(qint64)), q, SIGNAL(length(qint64)) );
QObject::connect( backendObject, SIGNAL(needData()), q, SLOT(_k_bytestreamNeedData()) );
QObject::connect( backendObject, SIGNAL(enoughData()), q, SLOT(_k_bytestreamEnoughData()) );
pBACKEND_CALL1( "setStreamSeekable", bool, false ); //FIXME: KIO doesn't support seeking at this point
//connect( backendObject, SIGNAL(seekStream(qint64)), kiojob, SLOT(
}
void MediaObjectPrivate::setupKioStreaming()
{
K_Q( MediaObject );
Q_ASSERT( backendObject == 0 );
backendObject = Factory::self()->createByteStream( q );
if( backendObject )
{
QObject::connect( backendObject, SIGNAL( destroyed( QObject* ) ), q, SLOT( _k_cleanupByteStream() ) );
//setupIface for ByteStream
if( kiojob )
kiojob->kill();
setupKioJob();
static_cast<AbstractMediaProducer*>( q )->setupIface();
}
}
void MediaObjectPrivate::_k_bytestreamNeedData()
{
if( kiojob && kiojob->isSuspended() )
kiojob->resume();
}
void MediaObjectPrivate::_k_bytestreamEnoughData()
{
if( kiojob && !kiojob->isSuspended() )
kiojob->suspend();
}
void MediaObjectPrivate::_k_bytestreamData( KIO::Job*, const QByteArray& data )
{
ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject );
bs->writeData( data );
}
void MediaObjectPrivate::_k_bytestreamResult( KJob* job )
{
ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject );
bs->endOfData();
kiojob = 0;
// A special situation occurs when the KIO job finishes before play() was
// called. Then in play() a new KIO job would be created - jobDone tells
// play() that there already was a KIO job and that it has "finished early".
Phonon::State s = state();
if( s == LoadingState || s == StoppedState )
jobDone = true;
if( job->error() )
{
//TODO
}
}
void MediaObjectPrivate::_k_bytestreamTotalSize( KJob*, qulonglong size )
{
pBACKEND_CALL1( "setStreamSize", quint64, size );
}
void MediaObjectPrivate::_k_cleanupByteStream()
{
if( kiojob )
{
kiojob->kill();
kiojob = 0;
}
}
bool MediaObjectPrivate::aboutToDeleteIface()
{
//kDebug( 600 ) << k_funcinfo << endl;
pBACKEND_GET( qint32, aboutToFinishTime, "aboutToFinishTime" );
return AbstractMediaProducerPrivate::aboutToDeleteIface();
}
// setupIface is not called for ByteStream
void MediaObject::setupIface()
{
K_D( MediaObject );
Q_ASSERT( d->backendObject );
//kDebug( 600 ) << k_funcinfo << endl;
AbstractMediaProducer::setupIface();
connect( d->backendObject, SIGNAL( finished() ), SIGNAL( finished() ) );
connect( d->backendObject, SIGNAL( aboutToFinish( qint32 ) ), SIGNAL( aboutToFinish( qint32 ) ) );
connect( d->backendObject, SIGNAL( length( qint64 ) ), SIGNAL( length( qint64 ) ) );
// set up attributes
if( !d->url.isEmpty() )
INTERFACE_CALL1( setUrl, d->url );
if( state() == Phonon::ErrorState )
{
d->deleteIface();
//at this point MediaObject uses a ByteStream
//instead and sends the data it receives from the KIO Job via writeBuffer.
//This essentially makes all media frameworks read data via KIO...
d->setupKioStreaming();
return;
}
BACKEND_CALL1( "setAboutToFinishTime", qint32, d->aboutToFinishTime );
}
} //namespace Phonon
#include "mediaobject.moc"
// vim: sw=4 ts=4 tw=80 noet
<commit_msg>fixed a typo in last commit<commit_after>/* This file is part of the KDE project
Copyright (C) 2005 Matthias Kretz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
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., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "mediaobject.h"
#include "mediaobject_p.h"
#include "factory.h"
#include "bytestreaminterface.h"
#include "mediaobjectinterface.h"
#include <kdebug.h>
#define PHONON_CLASSNAME MediaObject
#define PHONON_INTERFACENAME MediaObjectInterface
namespace Phonon
{
PHONON_HEIR_IMPL( AbstractMediaProducer )
MediaObject::MediaObject( Phonon::MediaObjectPrivate& dd, QObject* parent )
: AbstractMediaProducer( dd, parent )
{
}
PHONON_INTERFACE_GETTER( KUrl, url, d->url )
PHONON_GETTER( qint32, aboutToFinishTime, d->aboutToFinishTime )
qint64 MediaObject::totalTime() const
{
K_D( const MediaObject );
if( !d->backendObject )
return -1;
MediaObjectInterface *iface = qobject_cast<MediaObjectInterface*>( d->backendObject );
if( iface )
return iface->totalTime();
else
{
ByteStreamInterface *iface2 = qobject_cast<ByteStreamInterface*>( d->backendObject );
if( iface2 )
return iface2->totalTime();
}
return -1;
}
qint64 MediaObject::remainingTime() const
{
K_D( const MediaObject );
if( !d->backendObject )
return -1;
qint64 ret;
if( !BACKEND_GET( qint64, ret, "remainingTime" ) )
ret = totalTime() - currentTime();
if( ret < 0 )
return -1;
return ret;
}
void MediaObject::setUrl( const KUrl& url )
{
K_D( MediaObject );
d->url = url;
if( iface() )
{
stop(); // first call stop as that often is the expected state
// for setting a new URL
INTERFACE_CALL1( setUrl, url );
//FIXME: the stateChanged signal will be emitted. Perhaps it should be
//disabled for the setUrl call and then replayed when it didn't go into
//ErrorState
if( state() == Phonon::ErrorState )
{
d->deleteIface();
//at this point MediaObject uses a ByteStream
//instead and sends the data it receives from the KIO Job via writeBuffer.
//This essentially makes all media frameworks read data via KIO...
d->setupKioStreaming();
}
}
}
void MediaObject::stop()
{
AbstractMediaProducer::stop();
K_D( MediaObject );
if( d->kiojob )
{
d->kiojob->kill();
// if( do pre-buffering )
d->setupKioJob();
}
}
void MediaObject::play()
{
K_D( MediaObject );
Phonon::State s = state();
if( s == Phonon::LoadingState || s == Phonon::StoppedState )
{
if( !d->jobDone && !d->kiojob && qobject_cast<ByteStreamInterface*>( d->backendObject ) )
d->setupKioJob();
else
// when play() is called and the whole data was already streamed (KIO job is
// finished) we can play once, the next time play() is called a new
// KIO job is needed.
d->jobDone = false;
}
AbstractMediaProducer::play();
}
PHONON_SETTER( setAboutToFinishTime, aboutToFinishTime, qint32 )
void MediaObjectPrivate::setupKioJob()
{
K_Q( MediaObject );
Q_ASSERT( backendObject );
jobDone = false;
kiojob = KIO::get( url, false, false );
kiojob->addMetaData( "UserAgent", QLatin1String( "KDE Phonon" ) );
QObject::connect( kiojob, SIGNAL(data(KIO::Job*,const QByteArray&)),
q, SLOT(_k_bytestreamData(KIO::Job*,const QByteArray&)) );
QObject::connect( kiojob, SIGNAL(result(KJob*)),
q, SLOT(_k_bytestreamResult(KJob*)) );
QObject::connect( kiojob, SIGNAL(totalSize(KJob*, qulonglong)),
q, SLOT(_k_bytestreamTotalSize(KJob*,qulonglong)) );
QObject::connect( backendObject, SIGNAL(finished()), q, SIGNAL(finished()) );
QObject::connect( backendObject, SIGNAL(aboutToFinish(qint32)), q, SIGNAL(aboutToFinish(qint32)) );
QObject::connect( backendObject, SIGNAL(length(qint64)), q, SIGNAL(length(qint64)) );
QObject::connect( backendObject, SIGNAL(needData()), q, SLOT(_k_bytestreamNeedData()) );
QObject::connect( backendObject, SIGNAL(enoughData()), q, SLOT(_k_bytestreamEnoughData()) );
pBACKEND_CALL1( "setStreamSeekable", bool, false ); //FIXME: KIO doesn't support seeking at this point
//connect( backendObject, SIGNAL(seekStream(qint64)), kiojob, SLOT(
}
void MediaObjectPrivate::setupKioStreaming()
{
K_Q( MediaObject );
Q_ASSERT( backendObject == 0 );
backendObject = Factory::self()->createByteStream( q );
if( backendObject )
{
QObject::connect( backendObject, SIGNAL( destroyed( QObject* ) ), q, SLOT( _k_cleanupByteStream() ) );
//setupIface for ByteStream
if( kiojob )
kiojob->kill();
setupKioJob();
static_cast<AbstractMediaProducer*>( q )->setupIface();
}
}
void MediaObjectPrivate::_k_bytestreamNeedData()
{
if( kiojob && kiojob->isSuspended() )
kiojob->resume();
}
void MediaObjectPrivate::_k_bytestreamEnoughData()
{
if( kiojob && !kiojob->isSuspended() )
kiojob->suspend();
}
void MediaObjectPrivate::_k_bytestreamData( KIO::Job*, const QByteArray& data )
{
ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject );
bs->writeData( data );
}
void MediaObjectPrivate::_k_bytestreamResult( KJob* job )
{
ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject );
bs->endOfData();
kiojob = 0;
// A special situation occurs when the KIO job finishes before play() was
// called. Then in play() a new KIO job would be created - jobDone tells
// play() that there already was a KIO job and that it has "finished early".
if( state == LoadingState || state == StoppedState )
jobDone = true;
if( job->error() )
{
//TODO
}
}
void MediaObjectPrivate::_k_bytestreamTotalSize( KJob*, qulonglong size )
{
pBACKEND_CALL1( "setStreamSize", quint64, size );
}
void MediaObjectPrivate::_k_cleanupByteStream()
{
if( kiojob )
{
kiojob->kill();
kiojob = 0;
}
}
bool MediaObjectPrivate::aboutToDeleteIface()
{
//kDebug( 600 ) << k_funcinfo << endl;
pBACKEND_GET( qint32, aboutToFinishTime, "aboutToFinishTime" );
return AbstractMediaProducerPrivate::aboutToDeleteIface();
}
// setupIface is not called for ByteStream
void MediaObject::setupIface()
{
K_D( MediaObject );
Q_ASSERT( d->backendObject );
//kDebug( 600 ) << k_funcinfo << endl;
AbstractMediaProducer::setupIface();
connect( d->backendObject, SIGNAL( finished() ), SIGNAL( finished() ) );
connect( d->backendObject, SIGNAL( aboutToFinish( qint32 ) ), SIGNAL( aboutToFinish( qint32 ) ) );
connect( d->backendObject, SIGNAL( length( qint64 ) ), SIGNAL( length( qint64 ) ) );
// set up attributes
if( !d->url.isEmpty() )
INTERFACE_CALL1( setUrl, d->url );
if( state() == Phonon::ErrorState )
{
d->deleteIface();
//at this point MediaObject uses a ByteStream
//instead and sends the data it receives from the KIO Job via writeBuffer.
//This essentially makes all media frameworks read data via KIO...
d->setupKioStreaming();
return;
}
BACKEND_CALL1( "setAboutToFinishTime", qint32, d->aboutToFinishTime );
}
} //namespace Phonon
#include "mediaobject.moc"
// vim: sw=4 ts=4 tw=80 noet
<|endoftext|>
|
<commit_before>#include "rdsstring.h"
#include <algorithm>
#include "tables.h"
namespace redsea {
namespace {
std::string rtrim(std::string s) {
int last_non_space = 0;
for (size_t i=0; i<s.length(); i++)
if (s.at(i) != ' ')
last_non_space = i+1;
return s.substr(0,last_non_space);
}
}
LCDchar::LCDchar() : code_(0) {
}
LCDchar::LCDchar(uint8_t _code) : code_(_code) {
}
uint8_t LCDchar::getCode() const {
return code_;
}
std::string LCDchar::toString() const {
return getLCDchar(code_);
}
RDSString::RDSString(int len) : chars_(len), is_char_sequential_(len),
prev_pos_(-1), last_complete_string_(getString()) {
}
void RDSString::setAt(int pos, LCDchar chr) {
if (pos < 0 || pos >= (int)chars_.size())
return;
chars_.at(pos) = chr;
if (pos != prev_pos_ + 1) {
for (size_t i=0; i<is_char_sequential_.size(); i++)
is_char_sequential_[i] = false;
}
is_char_sequential_.at(pos) = true;
if (isComplete()) {
last_complete_string_ = getString();
last_complete_chars_ = getChars();
}
prev_pos_ = pos;
}
std::string RDSString::charAt(int pos) const {
return (pos < (int)last_complete_chars_.size() ?
last_complete_chars_[pos].toString() : " ");
}
size_t RDSString::lengthReceived() const {
size_t result = 0;
for (size_t i=0; i<is_char_sequential_.size(); i++) {
if (!is_char_sequential_[i])
break;
result = i+1;
}
return result;
}
size_t RDSString::lengthExpected() const {
size_t result = chars_.size();
for (size_t i=0; i<chars_.size(); i++) {
if (chars_[i].getCode() == 0x0D) {
result = i;
break;
}
}
return result;
}
std::string RDSString::getString() const {
std::string result;
for (LCDchar chr : getChars()) {
result += chr.toString();
}
return result;
}
std::vector<LCDchar> RDSString::getChars() const {
std::vector<LCDchar> result;
size_t len = lengthExpected();
for (size_t i=0; i<len; i++) {
result.push_back(is_char_sequential_[i] ? chars_[i] : 32);
}
return result;
}
std::string RDSString::getTrimmedString() const {
return rtrim(getString());
}
std::string RDSString::getLastCompleteString() const {
return last_complete_string_;
}
std::string RDSString::getLastCompleteString(int start, int len) const {
std::string result;
for (int i=start; i<start+len; i++) {
result += (i < (int)last_complete_chars_.size() ?
last_complete_chars_[i].toString() : " ");
}
return result;
}
std::string RDSString::getLastCompleteStringTrimmed() const {
return rtrim(last_complete_string_);
}
std::string RDSString::getLastCompleteStringTrimmed(int start, int len) const {
return rtrim(getLastCompleteString(start, len));
}
bool RDSString::hasChars(int start, int len) const {
return start+len <= (int)last_complete_chars_.size();
}
bool RDSString::isComplete() const {
return lengthReceived() >= lengthExpected();
}
void RDSString::clear() {
for (size_t i=0; i<chars_.size(); i++) {
is_char_sequential_[i] = false;
}
last_complete_string_ = getString();
last_complete_chars_.clear();
}
} // namespace redsea
<commit_msg>use string::erase<commit_after>#include "rdsstring.h"
#include <algorithm>
#include "tables.h"
namespace redsea {
namespace {
std::string rtrim(std::string s) {
return s.erase(s.find_last_not_of(' ')+1);
}
}
LCDchar::LCDchar() : code_(0) {
}
LCDchar::LCDchar(uint8_t _code) : code_(_code) {
}
uint8_t LCDchar::getCode() const {
return code_;
}
std::string LCDchar::toString() const {
return getLCDchar(code_);
}
RDSString::RDSString(int len) : chars_(len), is_char_sequential_(len),
prev_pos_(-1), last_complete_string_(getString()) {
}
void RDSString::setAt(int pos, LCDchar chr) {
if (pos < 0 || pos >= (int)chars_.size())
return;
chars_.at(pos) = chr;
if (pos != prev_pos_ + 1) {
for (size_t i=0; i<is_char_sequential_.size(); i++)
is_char_sequential_[i] = false;
}
is_char_sequential_.at(pos) = true;
if (isComplete()) {
last_complete_string_ = getString();
last_complete_chars_ = getChars();
}
prev_pos_ = pos;
}
std::string RDSString::charAt(int pos) const {
return (pos < (int)last_complete_chars_.size() ?
last_complete_chars_[pos].toString() : " ");
}
size_t RDSString::lengthReceived() const {
size_t result = 0;
for (size_t i=0; i<is_char_sequential_.size(); i++) {
if (!is_char_sequential_[i])
break;
result = i+1;
}
return result;
}
size_t RDSString::lengthExpected() const {
size_t result = chars_.size();
for (size_t i=0; i<chars_.size(); i++) {
if (chars_[i].getCode() == 0x0D) {
result = i;
break;
}
}
return result;
}
std::string RDSString::getString() const {
std::string result;
for (LCDchar chr : getChars()) {
result += chr.toString();
}
return result;
}
std::vector<LCDchar> RDSString::getChars() const {
std::vector<LCDchar> result;
size_t len = lengthExpected();
for (size_t i=0; i<len; i++) {
result.push_back(is_char_sequential_[i] ? chars_[i] : 32);
}
return result;
}
std::string RDSString::getTrimmedString() const {
return rtrim(getString());
}
std::string RDSString::getLastCompleteString() const {
return last_complete_string_;
}
std::string RDSString::getLastCompleteString(int start, int len) const {
std::string result;
for (int i=start; i<start+len; i++) {
result += (i < (int)last_complete_chars_.size() ?
last_complete_chars_[i].toString() : " ");
}
return result;
}
std::string RDSString::getLastCompleteStringTrimmed() const {
return rtrim(last_complete_string_);
}
std::string RDSString::getLastCompleteStringTrimmed(int start, int len) const {
return rtrim(getLastCompleteString(start, len));
}
bool RDSString::hasChars(int start, int len) const {
return start+len <= (int)last_complete_chars_.size();
}
bool RDSString::isComplete() const {
return lengthReceived() >= lengthExpected();
}
void RDSString::clear() {
for (size_t i=0; i<chars_.size(); i++) {
is_char_sequential_[i] = false;
}
last_complete_string_ = getString();
last_complete_chars_.clear();
}
} // namespace redsea
<|endoftext|>
|
<commit_before>/**
* 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 <signal.h>
#include <unistd.h>
#include <mutex>
#include <event2/event.h>
#include <event2/thread.h>
#include <process/logging.hpp>
#include <stout/os/signals.hpp>
#include <stout/synchronized.hpp>
#include <stout/thread_local.hpp>
#include "event_loop.hpp"
#include "libevent.hpp"
namespace process {
event_base* base = NULL;
static std::mutex* functions_mutex = new std::mutex();
std::queue<lambda::function<void(void)>>* functions =
new std::queue<lambda::function<void(void)>>();
THREAD_LOCAL bool* _in_event_loop_ = NULL;
void async_function(int socket, short which, void* arg)
{
event* ev = reinterpret_cast<event*>(arg);
event_free(ev);
std::queue<lambda::function<void(void)>> q;
synchronized (functions_mutex) {
std::swap(q, *functions);
}
while (!q.empty()) {
q.front()();
q.pop();
}
}
void run_in_event_loop(
const lambda::function<void(void)>& f,
EventLoopLogicFlow event_loop_logic_flow)
{
if (__in_event_loop__ && event_loop_logic_flow == ALLOW_SHORT_CIRCUIT) {
f();
return;
}
synchronized (functions_mutex) {
functions->push(f);
// Add an event and activate it to interrupt the event loop.
// TODO(jmlvanre): after libevent v 2.1 we can use
// event_self_cbarg instead of re-assigning the event. For now we
// manually re-assign the event to pass in the pointer to the
// event itself as the callback argument.
event* ev = evtimer_new(base, async_function, NULL);
// 'event_assign' is only valid on non-pending AND non-active
// events. This means we have to assign the callback before
// calling 'event_active'.
if (evtimer_assign(ev, base, async_function, ev) < 0) {
LOG(FATAL) << "Failed to assign callback on event";
}
event_active(ev, EV_TIMEOUT, 0);
}
}
void EventLoop::run()
{
__in_event_loop__ = true;
// Block SIGPIPE in the event loop because we can not force
// underlying implementations such as SSL bufferevents to use
// MSG_NOSIGNAL.
bool unblock = os::signals::block(SIGPIPE);
do {
int result = event_base_loop(base, EVLOOP_ONCE);
if (result < 0) {
LOG(FATAL) << "Failed to run event loop";
} else if (result > 0) {
// All events are handled, continue event loop.
continue;
} else {
CHECK_EQ(0, result);
if (event_base_got_break(base)) {
break;
} else if (event_base_got_exit(base)) {
break;
}
}
} while (true);
__in_event_loop__ = false;
if (unblock) {
if (!os::signals::unblock(SIGPIPE)) {
LOG(FATAL) << "Failure to unblock SIGPIPE";
}
}
}
namespace internal {
struct Delay
{
lambda::function<void(void)> function;
event* timer;
};
void handle_delay(int, short, void* arg)
{
Delay* delay = reinterpret_cast<Delay*>(arg);
delay->function();
event_free(delay->timer);
delete delay;
}
} // namespace internal {
void EventLoop::delay(
const Duration& duration,
const lambda::function<void(void)>& function)
{
internal::Delay* delay = new internal::Delay();
delay->timer = evtimer_new(base, &internal::handle_delay, delay);
if (delay->timer == NULL) {
LOG(FATAL) << "Failed to delay, evtimer_new";
}
delay->function = function;
timeval t{0, 0};
if (duration > Seconds(0)) {
t = duration.timeval();
}
evtimer_add(delay->timer, &t);
}
double EventLoop::time()
{
// Get the cached time if running the event loop, or call
// gettimeofday() to get the current time. Since a lot of logic in
// libprocess depends on time math, we want to log fatal rather than
// cause logic errors if the time fails.
timeval t;
if (event_base_gettimeofday_cached(base, &t) < 0) {
LOG(FATAL) << "Failed to get time, event_base_gettimeofday_cached";
}
return Duration(t).secs();
}
void EventLoop::initialize()
{
// We need to initialize Libevent differently depending on the
// operating system threading support.
#if defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED)
if (evthread_use_pthreads() < 0) {
LOG(FATAL) << "Failed to initialize, evthread_use_pthreads";
}
#elif defined(EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED)
if (evthread_use_windows_threads() < 0) {
LOG(FATAL) << "Failed to initialize, evthread_use_windows_threads";
}
#else
#error "Libevent must be compiled with either pthread or Windows thread support"
#endif
// This enables debugging of libevent calls. We can remove this
// when the implementation settles and after we gain confidence.
event_enable_debug_mode();
// TODO(jmlvanre): Allow support for 'epoll' once SSL related
// issues are resolved.
struct event_config* config = event_config_new();
event_config_avoid_method(config, "epoll");
base = event_base_new_with_config(config);
if (base == NULL) {
LOG(FATAL) << "Failed to initialize, event_base_new";
}
}
} // namespace process {
<commit_msg>Added Once guard for Eventloop::initialize.<commit_after>/**
* 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 <signal.h>
#include <unistd.h>
#include <mutex>
#include <event2/event.h>
#include <event2/thread.h>
#include <process/logging.hpp>
#include <process/once.hpp>
#include <stout/os/signals.hpp>
#include <stout/synchronized.hpp>
#include <stout/thread_local.hpp>
#include "event_loop.hpp"
#include "libevent.hpp"
namespace process {
event_base* base = NULL;
static std::mutex* functions_mutex = new std::mutex();
std::queue<lambda::function<void(void)>>* functions =
new std::queue<lambda::function<void(void)>>();
THREAD_LOCAL bool* _in_event_loop_ = NULL;
void async_function(int socket, short which, void* arg)
{
event* ev = reinterpret_cast<event*>(arg);
event_free(ev);
std::queue<lambda::function<void(void)>> q;
synchronized (functions_mutex) {
std::swap(q, *functions);
}
while (!q.empty()) {
q.front()();
q.pop();
}
}
void run_in_event_loop(
const lambda::function<void(void)>& f,
EventLoopLogicFlow event_loop_logic_flow)
{
if (__in_event_loop__ && event_loop_logic_flow == ALLOW_SHORT_CIRCUIT) {
f();
return;
}
synchronized (functions_mutex) {
functions->push(f);
// Add an event and activate it to interrupt the event loop.
// TODO(jmlvanre): after libevent v 2.1 we can use
// event_self_cbarg instead of re-assigning the event. For now we
// manually re-assign the event to pass in the pointer to the
// event itself as the callback argument.
event* ev = evtimer_new(base, async_function, NULL);
// 'event_assign' is only valid on non-pending AND non-active
// events. This means we have to assign the callback before
// calling 'event_active'.
if (evtimer_assign(ev, base, async_function, ev) < 0) {
LOG(FATAL) << "Failed to assign callback on event";
}
event_active(ev, EV_TIMEOUT, 0);
}
}
void EventLoop::run()
{
__in_event_loop__ = true;
// Block SIGPIPE in the event loop because we can not force
// underlying implementations such as SSL bufferevents to use
// MSG_NOSIGNAL.
bool unblock = os::signals::block(SIGPIPE);
do {
int result = event_base_loop(base, EVLOOP_ONCE);
if (result < 0) {
LOG(FATAL) << "Failed to run event loop";
} else if (result > 0) {
// All events are handled, continue event loop.
continue;
} else {
CHECK_EQ(0, result);
if (event_base_got_break(base)) {
break;
} else if (event_base_got_exit(base)) {
break;
}
}
} while (true);
__in_event_loop__ = false;
if (unblock) {
if (!os::signals::unblock(SIGPIPE)) {
LOG(FATAL) << "Failure to unblock SIGPIPE";
}
}
}
namespace internal {
struct Delay
{
lambda::function<void(void)> function;
event* timer;
};
void handle_delay(int, short, void* arg)
{
Delay* delay = reinterpret_cast<Delay*>(arg);
delay->function();
event_free(delay->timer);
delete delay;
}
} // namespace internal {
void EventLoop::delay(
const Duration& duration,
const lambda::function<void(void)>& function)
{
internal::Delay* delay = new internal::Delay();
delay->timer = evtimer_new(base, &internal::handle_delay, delay);
if (delay->timer == NULL) {
LOG(FATAL) << "Failed to delay, evtimer_new";
}
delay->function = function;
timeval t{0, 0};
if (duration > Seconds(0)) {
t = duration.timeval();
}
evtimer_add(delay->timer, &t);
}
double EventLoop::time()
{
// Get the cached time if running the event loop, or call
// gettimeofday() to get the current time. Since a lot of logic in
// libprocess depends on time math, we want to log fatal rather than
// cause logic errors if the time fails.
timeval t;
if (event_base_gettimeofday_cached(base, &t) < 0) {
LOG(FATAL) << "Failed to get time, event_base_gettimeofday_cached";
}
return Duration(t).secs();
}
void EventLoop::initialize()
{
static Once* initialized = new Once();
if (initialized->once()) {
return;
}
// We need to initialize Libevent differently depending on the
// operating system threading support.
#if defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED)
if (evthread_use_pthreads() < 0) {
LOG(FATAL) << "Failed to initialize, evthread_use_pthreads";
}
#elif defined(EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED)
if (evthread_use_windows_threads() < 0) {
LOG(FATAL) << "Failed to initialize, evthread_use_windows_threads";
}
#else
#error "Libevent must be compiled with either pthread or Windows thread support"
#endif
// This enables debugging of libevent calls. We can remove this
// when the implementation settles and after we gain confidence.
event_enable_debug_mode();
// TODO(jmlvanre): Allow support for 'epoll' once SSL related
// issues are resolved.
struct event_config* config = event_config_new();
event_config_avoid_method(config, "epoll");
base = event_base_new_with_config(config);
if (base == NULL) {
LOG(FATAL) << "Failed to initialize, event_base_new";
}
initialized->done();
}
} // namespace process {
<|endoftext|>
|
<commit_before>/**
* @file infomax_ica.cc
* @author Chip Mappus
*
* Methods for InfomaxICA.
*
* @see infomax_ica.h
*/
#include "infomax_ica.h"
#include <fastlib/fx/io.h>
PARAM(double, "lambda", "The learning rate.", "info", .001,
false);
PARAM_INT_REQ("B", "Infomax data window size.", "info");
PARAM(double, "epsilon", "Infomax algorithm stop threshold.", "info", .001,
false);
PARAM_MODULE("info",
"This performs ICO decomposition on a given dataset using the Infomax method");
using namespace mlpack;
/**
* Dummy constructor
*/
InfomaxICA::InfomaxICA() { }
InfomaxICA::InfomaxICA(double lambda, index_t b, double epsilon) :
lambda_(lambda),
b_(b),
epsilon_(epsilon) { }
/**
* Sphere the data, apply ica. This is the first function to call
* after initializing the variables.
*/
void InfomaxICA::applyICA(const arma::mat& dataset) {
double current_cos = DBL_MAX;
w_.set_size(b_, b_);
data_ = dataset; // Copy the matrix? Stupid!
if (b_ < data_.n_cols) {
sphere(data_);
// initial estimate for w is Id
arma::mat i1;
i1.eye(data_.n_rows, data_.n_rows);
w_ = i1; // Another copy? Stupid!
while (epsilon_ <= current_cos){
arma::mat w_prev = w_;
evaluateICA();
current_cos = w_delta(w_prev, w_);
}
} else
IO::Fatal << "Window size must be less than number of instances."
<< std::endl;
}
/**
* Run infomax. Call this after initialization and applyICA.
*/
void InfomaxICA::evaluateICA() {
arma::mat BI;
BI.eye(w_.n_rows, w_.n_rows);
BI *= b_;
// intermediate calculation variables
arma::mat icv(w_.n_rows, b_);
arma::mat icv2(w_.n_rows, w_.n_cols);
arma::mat icv4(w_.n_rows, w_.n_cols);
for (index_t i = 0; i < data_.n_cols; i += b_) {
if ((i + b_) < data_.n_cols) {
// This is not tested.
icv = -2.0 * arma::pow(arma::exp(
-1 * (w_ * data_.cols(i, i + b_))) + 1, -1) + 1;
icv2 = icv * trans(data_.cols(i, i + b_));
icv4 = lambda_ * (icv2 + BI);
icv2 = icv4 * w_;
w_ += icv2;
}
}
}
// sphereing functions
/**
* Sphere the input data.
*/
void InfomaxICA::sphere(arma::mat& data) {
arma::mat sample_covariance = sampleCovariance(data);
arma::mat wz = sqrtm(sample_covariance);
arma::mat data_sub_means = subMeans(data);
arma::mat wz_inverse = inv(wz);
// Not tested.
wz_inverse *= 2.0;
data = wz_inverse * data_sub_means;
}
// Covariance matrix.
arma::mat InfomaxICA::sampleCovariance(const arma::mat& m) {
// Not tested.
arma::mat ttm = subMeans(m);
arma::mat wm = trans(ttm);
arma::mat twm(ttm.n_rows, ttm.n_rows);
arma::mat output(ttm.n_rows, ttm.n_rows);
output.zeros();
arma::mat tttm(wm);
tttm *= (1 / (double) (ttm.n_cols - 1));
twm = trans(wm) * tttm;
output = twm;
return output;
}
arma::mat InfomaxICA::subMeans(const arma::mat& m){
arma::mat output(m);
arma::vec row_means = rowMean(output);
for (index_t j = 0; j < output.n_cols; j++) {
output.col(j) -= row_means;
}
return output;
}
/**
* Compute the sample mean of a column
*/
arma::vec InfomaxICA::rowMean(const arma::mat& m){
arma::vec row_means(m.n_rows);
row_means.zeros();
for (index_t j = 0; j < m.n_cols; j++) {
row_means += m.col(j);
}
row_means /= (double) m.n_cols;
return row_means;
}
/**
* Matrix square root using Cholesky decomposition method. Assumes the input
* matrix is square.
*/
arma::mat InfomaxICA::sqrtm(const arma::mat& m) {
arma::mat output(m.n_rows, m.n_cols);
arma::mat chol;
if (arma::chol(chol, m)) {
arma::mat u, v;
arma::vec s;
if (arma::svd(u, s, v, trans(chol))) {
arma::mat S(s.n_elem, s.n_elem);
S.zeros();
S.diag() = s;
arma::mat tm1 = u * S;
output = tm1 * trans(u);
} else
IO::Warn << "InfomaxICA sqrtm: SVD failed." << std::endl;
} else
IO::Warn << "InfomaxICA sqrtm: Cholesky decomposition failed." << std::endl;
return output;
}
// Compare w estimates for convergence
double InfomaxICA::w_delta(const arma::mat& w_prev, const arma::mat& w_pres) {
arma::mat temp = w_pres - w_prev;
arma::vec delta = reshape(temp, 1, temp.n_rows * temp.n_cols);
double delta_dot = arma::dot(delta, delta);
IO::Info << "w change: " << delta_dot << std::endl;
return delta_dot;
}
/**
* Return the current unmixing matrix estimate. Requires a reference
* to an uninitialized matrix.
*/
void InfomaxICA::getUnmixing(arma::mat& w) {
w = w_;
}
/**
* Return the source estimates, S. S is a reference to an
* uninitialized matrix.
*/
void InfomaxICA::getSources(const arma::mat& dataset, arma::mat& s) {
s = w_ * dataset;
}
void InfomaxICA::setLambda(const double lambda) {
lambda_ = lambda;
}
void InfomaxICA::setB(const index_t b) {
b_ = b;
}
void InfomaxICA::setEpsilon(const double epsilon) {
epsilon_ = epsilon;
}
<commit_msg>Reshape to one column, not one row. This fixes a runtime error.<commit_after>/**
* @file infomax_ica.cc
* @author Chip Mappus
*
* Methods for InfomaxICA.
*
* @see infomax_ica.h
*/
#include "infomax_ica.h"
#include <fastlib/fx/io.h>
PARAM(double, "lambda", "The learning rate.", "info", .001,
false);
PARAM_INT_REQ("B", "Infomax data window size.", "info");
PARAM(double, "epsilon", "Infomax algorithm stop threshold.", "info", .001,
false);
PARAM_MODULE("info",
"This performs ICO decomposition on a given dataset using the Infomax method");
using namespace mlpack;
/**
* Dummy constructor
*/
InfomaxICA::InfomaxICA() { }
InfomaxICA::InfomaxICA(double lambda, index_t b, double epsilon) :
lambda_(lambda),
b_(b),
epsilon_(epsilon) { }
/**
* Sphere the data, apply ica. This is the first function to call
* after initializing the variables.
*/
void InfomaxICA::applyICA(const arma::mat& dataset) {
double current_cos = DBL_MAX;
w_.set_size(b_, b_);
data_ = dataset; // Copy the matrix? Stupid!
if (b_ < data_.n_cols) {
sphere(data_);
// initial estimate for w is Id
arma::mat i1;
i1.eye(data_.n_rows, data_.n_rows);
w_ = i1; // Another copy? Stupid!
while (epsilon_ <= current_cos){
arma::mat w_prev = w_;
evaluateICA();
current_cos = w_delta(w_prev, w_);
}
} else
IO::Fatal << "Window size must be less than number of instances."
<< std::endl;
}
/**
* Run infomax. Call this after initialization and applyICA.
*/
void InfomaxICA::evaluateICA() {
arma::mat BI;
BI.eye(w_.n_rows, w_.n_rows);
BI *= b_;
// intermediate calculation variables
arma::mat icv(w_.n_rows, b_);
arma::mat icv2(w_.n_rows, w_.n_cols);
arma::mat icv4(w_.n_rows, w_.n_cols);
for (index_t i = 0; i < data_.n_cols; i += b_) {
if ((i + b_) < data_.n_cols) {
// This is not tested.
icv = -2.0 * arma::pow(arma::exp(
-1 * (w_ * data_.cols(i, i + b_))) + 1, -1) + 1;
icv2 = icv * trans(data_.cols(i, i + b_));
icv4 = lambda_ * (icv2 + BI);
icv2 = icv4 * w_;
w_ += icv2;
}
}
}
// sphereing functions
/**
* Sphere the input data.
*/
void InfomaxICA::sphere(arma::mat& data) {
arma::mat sample_covariance = sampleCovariance(data);
arma::mat wz = sqrtm(sample_covariance);
arma::mat data_sub_means = subMeans(data);
arma::mat wz_inverse = inv(wz);
// Not tested.
wz_inverse *= 2.0;
data = wz_inverse * data_sub_means;
}
// Covariance matrix.
arma::mat InfomaxICA::sampleCovariance(const arma::mat& m) {
// Not tested.
arma::mat ttm = subMeans(m);
arma::mat wm = trans(ttm);
arma::mat twm(ttm.n_rows, ttm.n_rows);
arma::mat output(ttm.n_rows, ttm.n_rows);
output.zeros();
arma::mat tttm(wm);
tttm *= (1 / (double) (ttm.n_cols - 1));
twm = trans(wm) * tttm;
output = twm;
return output;
}
arma::mat InfomaxICA::subMeans(const arma::mat& m){
arma::mat output(m);
arma::vec row_means = rowMean(output);
for (index_t j = 0; j < output.n_cols; j++) {
output.col(j) -= row_means;
}
return output;
}
/**
* Compute the sample mean of a column
*/
arma::vec InfomaxICA::rowMean(const arma::mat& m){
arma::vec row_means(m.n_rows);
row_means.zeros();
for (index_t j = 0; j < m.n_cols; j++) {
row_means += m.col(j);
}
row_means /= (double) m.n_cols;
return row_means;
}
/**
* Matrix square root using Cholesky decomposition method. Assumes the input
* matrix is square.
*/
arma::mat InfomaxICA::sqrtm(const arma::mat& m) {
arma::mat output(m.n_rows, m.n_cols);
arma::mat chol;
if (arma::chol(chol, m)) {
arma::mat u, v;
arma::vec s;
if (arma::svd(u, s, v, trans(chol))) {
arma::mat S(s.n_elem, s.n_elem);
S.zeros();
S.diag() = s;
arma::mat tm1 = u * S;
output = tm1 * trans(u);
} else
IO::Warn << "InfomaxICA sqrtm: SVD failed." << std::endl;
} else
IO::Warn << "InfomaxICA sqrtm: Cholesky decomposition failed." << std::endl;
return output;
}
// Compare w estimates for convergence
double InfomaxICA::w_delta(const arma::mat& w_prev, const arma::mat& w_pres) {
arma::mat temp = w_pres - w_prev;
arma::vec delta = reshape(temp, temp.n_rows * temp.n_cols, 1);
double delta_dot = arma::dot(delta, delta);
IO::Info << "w change: " << delta_dot << std::endl;
return delta_dot;
}
/**
* Return the current unmixing matrix estimate. Requires a reference
* to an uninitialized matrix.
*/
void InfomaxICA::getUnmixing(arma::mat& w) {
w = w_;
}
/**
* Return the source estimates, S. S is a reference to an
* uninitialized matrix.
*/
void InfomaxICA::getSources(const arma::mat& dataset, arma::mat& s) {
s = w_ * dataset;
}
void InfomaxICA::setLambda(const double lambda) {
lambda_ = lambda;
}
void InfomaxICA::setB(const index_t b) {
b_ = b;
}
void InfomaxICA::setEpsilon(const double epsilon) {
epsilon_ = epsilon;
}
<|endoftext|>
|
<commit_before>#include "ROOT/TDataFrame.hxx"
#include "TRandom.h"
#include "TROOT.h"
#include "gtest/gtest.h"
#include <limits>
using namespace ROOT::Experimental;
using namespace ROOT::Experimental::TDF;
using namespace ROOT::Detail::TDF;
/********* FIXTURES *********/
static constexpr ULong64_t gNEvents = 8ull;
static constexpr unsigned int gNSlots = 4u;
// fixture that provides a TDF with no data-source and a single column "x" containing normal-distributed doubles
class TDFCallbacks : public ::testing::Test {
private:
TDataFrame fLoopManager;
TInterface<TLoopManager> DefineRandomCol()
{
TRandom r;
return fLoopManager.Define("x", [r]() mutable { return r.Gaus(); });
}
protected:
TDFCallbacks() : fLoopManager(gNEvents), tdf(DefineRandomCol()) {}
TInterface<TLoopManager> tdf;
};
#ifdef R__USE_IMT
// fixture that enables implicit MT and provides a TDF with no data-source and a single column "x" containing
// normal-distributed doubles
class TDFCallbacksMT : public ::testing::Test {
class TIMTEnabler {
public:
TIMTEnabler(unsigned int sl) { ROOT::EnableImplicitMT(sl); }
~TIMTEnabler() { ROOT::DisableImplicitMT(); }
};
private:
TIMTEnabler fIMTEnabler;
TDataFrame fLoopManager;
TInterface<TLoopManager> DefineRandomCol()
{
std::vector<TRandom> rs(gNSlots);
return fLoopManager.DefineSlot("x", [rs](unsigned int slot) mutable { return rs[slot].Gaus(); });
}
protected:
TDFCallbacksMT() : fIMTEnabler(gNSlots), fLoopManager(gNEvents), tdf(DefineRandomCol()) {}
TInterface<TLoopManager> tdf;
};
#endif
/********* TESTS *********/
TEST_F(TDFCallbacks, Histo1DWithFillTOHelper)
{
// Histo1D<double> + OnPartialResult + FillTOHelper
auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x");
using value_t = typename decltype(h)::Value_t;
ULong64_t i = 0ull;
ULong64_t everyN = 1ull;
h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {
i += everyN;
EXPECT_EQ(h_.GetEntries(), i);
});
*h;
EXPECT_EQ(gNEvents, i);
}
TEST_F(TDFCallbacks, JittedHisto1DWithFillTOHelper)
{
// Histo1D + Jitting + OnPartialResult + FillTOHelper
auto h = tdf.Histo1D({"", "", 128, -2., 2.}, "x");
using value_t = typename decltype(h)::Value_t;
ULong64_t i = 0ull;
ULong64_t everyN = 1ull;
h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {
i += everyN;
EXPECT_EQ(h_.GetEntries(), i);
});
*h;
EXPECT_EQ(gNEvents, i);
}
TEST_F(TDFCallbacks, Histo1DWithFillHelper)
{
// Histo1D<double> + OnPartialResult + FillHelper
auto h = tdf.Histo1D<double>("x");
using value_t = typename decltype(h)::Value_t;
ULong64_t i = 0ull;
ULong64_t everyN = 1ull;
h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {
i += everyN;
EXPECT_EQ(h_.GetEntries(), i);
});
*h;
EXPECT_EQ(gNEvents, i);
}
TEST_F(TDFCallbacks, JittedHisto1DWithFillHelper)
{
// Histo1D + Jitting + OnPartialResult + FillHelper
auto h = tdf.Histo1D("x");
using value_t = typename decltype(h)::Value_t;
ULong64_t i = 0ull;
ULong64_t everyN = 1ull;
h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {
i += everyN;
EXPECT_EQ(h_.GetEntries(), i);
});
*h;
EXPECT_EQ(gNEvents, i);
}
TEST_F(TDFCallbacks, Min)
{
// Min + OnPartialResult
auto m = tdf.Min<double>("x");
double runningMin = std::numeric_limits<double>::max();
m.OnPartialResult(2, [&runningMin](double x) {
EXPECT_LE(x, runningMin);
runningMin = x;
});
*m;
EXPECT_DOUBLE_EQ(runningMin, *m);
}
TEST_F(TDFCallbacks, JittedMin)
{
// Min + Jitting + OnPartialResult
auto m = tdf.Min("x");
double runningMin = std::numeric_limits<double>::max();
m.OnPartialResult(2, [&runningMin](double x) {
EXPECT_LE(x, runningMin);
runningMin = x;
});
*m;
EXPECT_DOUBLE_EQ(runningMin, *m);
}
TEST_F(TDFCallbacks, Max)
{
// Max + OnPartialResult
auto m = tdf.Max<double>("x");
double runningMax = std::numeric_limits<double>::lowest();
m.OnPartialResult(2, [&runningMax](double x) {
EXPECT_GE(x, runningMax);
runningMax = x;
});
*m;
EXPECT_DOUBLE_EQ(runningMax, *m);
}
TEST_F(TDFCallbacks, JittedMax)
{
// Max + Jitting + OnPartialResult
auto m = tdf.Max("x");
double runningMax = std::numeric_limits<double>::lowest();
m.OnPartialResult(2, [&runningMax](double x) {
EXPECT_GE(x, runningMax);
runningMax = x;
});
*m;
EXPECT_DOUBLE_EQ(runningMax, *m);
}
TEST_F(TDFCallbacks, Mean)
{
// Mean + OnPartialResult
auto m = tdf.Mean<double>("x");
// TODO find a better way to check that the running mean makes sense
bool called = false;
m.OnPartialResult(gNEvents / 2, [&called](double) { called = true; });
*m;
EXPECT_TRUE(called);
}
TEST_F(TDFCallbacks, JittedMean)
{
// Mean + Jitting + OnPartialResult
auto m = tdf.Mean("x");
// TODO find a better way to check that the running mean makes sense
bool called = false;
m.OnPartialResult(gNEvents / 2, [&called](double) { called = true; });
*m;
EXPECT_TRUE(called);
}
TEST_F(TDFCallbacks, Take)
{
// Take + OnPartialResult
auto t = tdf.Take<double>("x");
unsigned int i = 0u;
t.OnPartialResult(1, [&](decltype(t)::Value_t &t_) {
++i;
EXPECT_EQ(t_.size(), i);
});
*t;
}
TEST_F(TDFCallbacks, Count)
{
// Count + OnPartialResult
auto c = tdf.Count();
ULong64_t i = 0ull;
c.OnPartialResult(1, [&](decltype(c)::Value_t c_) {
++i;
EXPECT_EQ(c_, i);
});
*c;
EXPECT_EQ(*c, i);
}
TEST_F(TDFCallbacks, Reduce)
{
// Reduce + OnPartialResult
double runningMin;
auto m = tdf.Min<double>("x").OnPartialResult(1, [&runningMin](double m_) { runningMin = m_; });
auto r = tdf.Reduce([](double x1, double x2) { return std::min(x1, x2); }, {"x"}, 0.);
r.OnPartialResult(1, [&runningMin](double r_) { EXPECT_DOUBLE_EQ(r_, runningMin); });
*r;
}
TEST_F(TDFCallbacks, Chaining)
{
// Chaining of multiple OnPartialResult[Slot] calls
unsigned int i = 0u;
auto c = tdf.Count()
.OnPartialResult(1, [&i](ULong64_t) { ++i; })
.OnPartialResultSlot(1, [&i](unsigned int, ULong64_t) {++i; });
*c;
EXPECT_EQ(i, gNEvents * 2);
}
TEST_F(TDFCallbacks, OrderOfExecution)
{
// Test that callbacks are executed in the order they are registered
unsigned int i = 0u;
auto c = tdf.Count();
c.OnPartialResult(1, [&i](ULong64_t) {
EXPECT_EQ(i, 0u);
i = 42u;
});
c.OnPartialResultSlot(1, [&i](unsigned int slot, ULong64_t) {
if (slot == 0u) {
EXPECT_EQ(i, 42u);
i = 0u;
}
});
*c;
EXPECT_EQ(i, 0u);
}
TEST_F(TDFCallbacks, ExecuteOnce)
{
// OnPartialResult(kOnce)
auto c = tdf.Count();
unsigned int callCount = 0;
c.OnPartialResult(0, [&callCount](ULong64_t) { callCount++; });
*c;
EXPECT_EQ(callCount, 1u);
}
TEST_F(TDFCallbacks, MultipleCallbacks)
{
// registration of multiple callbacks on the same partial result
auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x");
using value_t = typename decltype(h)::Value_t;
ULong64_t everyN = 1ull;
ULong64_t i = 0ull;
h.OnPartialResult(everyN, [&i, everyN](value_t &h_) {
i += everyN;
EXPECT_EQ(h_.GetEntries(), i);
});
everyN = 2ull;
ULong64_t i2 = 0ull;
h.OnPartialResult(everyN, [&i2, everyN](value_t &h_) {
i2 += everyN;
EXPECT_EQ(h_.GetEntries(), i2);
});
*h;
}
TEST_F(TDFCallbacks, MultipleEventLoops)
{
// callbacks must be de-registered after the event-loop is run
auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x");
using value_t = typename decltype(h)::Value_t;
ULong64_t i = 0ull;
h.OnPartialResult(1ull, [&i](value_t &) { ++i; });
*h;
auto h2 = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x");
*h2;
EXPECT_EQ(i, gNEvents);
}
class FunctorClass {
unsigned int &i_;
public:
FunctorClass(unsigned int &i) : i_(i) {}
void operator()(ULong64_t) { ++i_; }
};
TEST_F(TDFCallbacks, FunctorClass)
{
unsigned int i = 0;
*(tdf.Count().OnPartialResult(1, FunctorClass(i)));
EXPECT_EQ(i, gNEvents);
}
unsigned int freeFunctionCounter = 0;
void FreeFunction(ULong64_t)
{
freeFunctionCounter++;
}
TEST_F(TDFCallbacks, FreeFunction)
{
*(tdf.Count().OnPartialResult(1, FreeFunction));
EXPECT_EQ(freeFunctionCounter, gNEvents);
}
#ifdef R__USE_IMT
/******** Multi-thread tests **********/
TEST_F(TDFCallbacksMT, ExecuteOncePerSlot)
{
// OnPartialResultSlot(kOnce)
auto c = tdf.Count();
std::atomic_uint callCount(0u);
c.OnPartialResultSlot(c.kOnce, [&callCount](unsigned int, ULong64_t) { callCount++; });
*c;
EXPECT_EQ(callCount, gNSlots * 2); // TDF spawns two tasks per slot
}
TEST_F(TDFCallbacksMT, Histo1DWithFillTOHelper)
{
// Histo1D<double> + OnPartialResultSlot + FillTOHelper
auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x");
using value_t = typename decltype(h)::Value_t;
std::array<ULong64_t, gNSlots> is;
is.fill(0ull);
constexpr ULong64_t everyN = 1ull;
h.OnPartialResultSlot(everyN, [&is, &everyN](unsigned int slot, value_t &h_) {
is[slot] += everyN;
EXPECT_EQ(h_.GetEntries(), is[slot]);
});
*h;
EXPECT_EQ(gNEvents, std::accumulate(is.begin(), is.end(), 0ull));
}
TEST_F(TDFCallbacksMT, Histo1DWithFillHelper)
{
// Histo1D<double> + OnPartialResultSlot + FillHelper
auto h = tdf.Histo1D<double>("x");
using value_t = typename decltype(h)::Value_t;
std::array<ULong64_t, gNSlots> is;
is.fill(0ull);
constexpr ULong64_t everyN = 1ull;
h.OnPartialResultSlot(everyN, [&is, &everyN](unsigned int slot, value_t &h_) {
is[slot] += everyN;
EXPECT_EQ(h_.GetEntries(), is[slot]);
});
*h;
EXPECT_EQ(gNEvents, std::accumulate(is.begin(), is.end(), 0ull));
}
#endif
<commit_msg>[TDF] Fix no-imt warning: only define variable for imt builds<commit_after>#include "ROOT/TDataFrame.hxx"
#include "TRandom.h"
#include "TROOT.h"
#include "gtest/gtest.h"
#include <limits>
using namespace ROOT::Experimental;
using namespace ROOT::Experimental::TDF;
using namespace ROOT::Detail::TDF;
/********* FIXTURES *********/
static constexpr ULong64_t gNEvents = 8ull;
// fixture that provides a TDF with no data-source and a single column "x" containing normal-distributed doubles
class TDFCallbacks : public ::testing::Test {
private:
TDataFrame fLoopManager;
TInterface<TLoopManager> DefineRandomCol()
{
TRandom r;
return fLoopManager.Define("x", [r]() mutable { return r.Gaus(); });
}
protected:
TDFCallbacks() : fLoopManager(gNEvents), tdf(DefineRandomCol()) {}
TInterface<TLoopManager> tdf;
};
#ifdef R__USE_IMT
static constexpr unsigned int gNSlots = 4u;
// fixture that enables implicit MT and provides a TDF with no data-source and a single column "x" containing
// normal-distributed doubles
class TDFCallbacksMT : public ::testing::Test {
class TIMTEnabler {
public:
TIMTEnabler(unsigned int sl) { ROOT::EnableImplicitMT(sl); }
~TIMTEnabler() { ROOT::DisableImplicitMT(); }
};
private:
TIMTEnabler fIMTEnabler;
TDataFrame fLoopManager;
TInterface<TLoopManager> DefineRandomCol()
{
std::vector<TRandom> rs(gNSlots);
return fLoopManager.DefineSlot("x", [rs](unsigned int slot) mutable { return rs[slot].Gaus(); });
}
protected:
TDFCallbacksMT() : fIMTEnabler(gNSlots), fLoopManager(gNEvents), tdf(DefineRandomCol()) {}
TInterface<TLoopManager> tdf;
};
#endif
/********* TESTS *********/
TEST_F(TDFCallbacks, Histo1DWithFillTOHelper)
{
// Histo1D<double> + OnPartialResult + FillTOHelper
auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x");
using value_t = typename decltype(h)::Value_t;
ULong64_t i = 0ull;
ULong64_t everyN = 1ull;
h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {
i += everyN;
EXPECT_EQ(h_.GetEntries(), i);
});
*h;
EXPECT_EQ(gNEvents, i);
}
TEST_F(TDFCallbacks, JittedHisto1DWithFillTOHelper)
{
// Histo1D + Jitting + OnPartialResult + FillTOHelper
auto h = tdf.Histo1D({"", "", 128, -2., 2.}, "x");
using value_t = typename decltype(h)::Value_t;
ULong64_t i = 0ull;
ULong64_t everyN = 1ull;
h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {
i += everyN;
EXPECT_EQ(h_.GetEntries(), i);
});
*h;
EXPECT_EQ(gNEvents, i);
}
TEST_F(TDFCallbacks, Histo1DWithFillHelper)
{
// Histo1D<double> + OnPartialResult + FillHelper
auto h = tdf.Histo1D<double>("x");
using value_t = typename decltype(h)::Value_t;
ULong64_t i = 0ull;
ULong64_t everyN = 1ull;
h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {
i += everyN;
EXPECT_EQ(h_.GetEntries(), i);
});
*h;
EXPECT_EQ(gNEvents, i);
}
TEST_F(TDFCallbacks, JittedHisto1DWithFillHelper)
{
// Histo1D + Jitting + OnPartialResult + FillHelper
auto h = tdf.Histo1D("x");
using value_t = typename decltype(h)::Value_t;
ULong64_t i = 0ull;
ULong64_t everyN = 1ull;
h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {
i += everyN;
EXPECT_EQ(h_.GetEntries(), i);
});
*h;
EXPECT_EQ(gNEvents, i);
}
TEST_F(TDFCallbacks, Min)
{
// Min + OnPartialResult
auto m = tdf.Min<double>("x");
double runningMin = std::numeric_limits<double>::max();
m.OnPartialResult(2, [&runningMin](double x) {
EXPECT_LE(x, runningMin);
runningMin = x;
});
*m;
EXPECT_DOUBLE_EQ(runningMin, *m);
}
TEST_F(TDFCallbacks, JittedMin)
{
// Min + Jitting + OnPartialResult
auto m = tdf.Min("x");
double runningMin = std::numeric_limits<double>::max();
m.OnPartialResult(2, [&runningMin](double x) {
EXPECT_LE(x, runningMin);
runningMin = x;
});
*m;
EXPECT_DOUBLE_EQ(runningMin, *m);
}
TEST_F(TDFCallbacks, Max)
{
// Max + OnPartialResult
auto m = tdf.Max<double>("x");
double runningMax = std::numeric_limits<double>::lowest();
m.OnPartialResult(2, [&runningMax](double x) {
EXPECT_GE(x, runningMax);
runningMax = x;
});
*m;
EXPECT_DOUBLE_EQ(runningMax, *m);
}
TEST_F(TDFCallbacks, JittedMax)
{
// Max + Jitting + OnPartialResult
auto m = tdf.Max("x");
double runningMax = std::numeric_limits<double>::lowest();
m.OnPartialResult(2, [&runningMax](double x) {
EXPECT_GE(x, runningMax);
runningMax = x;
});
*m;
EXPECT_DOUBLE_EQ(runningMax, *m);
}
TEST_F(TDFCallbacks, Mean)
{
// Mean + OnPartialResult
auto m = tdf.Mean<double>("x");
// TODO find a better way to check that the running mean makes sense
bool called = false;
m.OnPartialResult(gNEvents / 2, [&called](double) { called = true; });
*m;
EXPECT_TRUE(called);
}
TEST_F(TDFCallbacks, JittedMean)
{
// Mean + Jitting + OnPartialResult
auto m = tdf.Mean("x");
// TODO find a better way to check that the running mean makes sense
bool called = false;
m.OnPartialResult(gNEvents / 2, [&called](double) { called = true; });
*m;
EXPECT_TRUE(called);
}
TEST_F(TDFCallbacks, Take)
{
// Take + OnPartialResult
auto t = tdf.Take<double>("x");
unsigned int i = 0u;
t.OnPartialResult(1, [&](decltype(t)::Value_t &t_) {
++i;
EXPECT_EQ(t_.size(), i);
});
*t;
}
TEST_F(TDFCallbacks, Count)
{
// Count + OnPartialResult
auto c = tdf.Count();
ULong64_t i = 0ull;
c.OnPartialResult(1, [&](decltype(c)::Value_t c_) {
++i;
EXPECT_EQ(c_, i);
});
*c;
EXPECT_EQ(*c, i);
}
TEST_F(TDFCallbacks, Reduce)
{
// Reduce + OnPartialResult
double runningMin;
auto m = tdf.Min<double>("x").OnPartialResult(1, [&runningMin](double m_) { runningMin = m_; });
auto r = tdf.Reduce([](double x1, double x2) { return std::min(x1, x2); }, {"x"}, 0.);
r.OnPartialResult(1, [&runningMin](double r_) { EXPECT_DOUBLE_EQ(r_, runningMin); });
*r;
}
TEST_F(TDFCallbacks, Chaining)
{
// Chaining of multiple OnPartialResult[Slot] calls
unsigned int i = 0u;
auto c = tdf.Count()
.OnPartialResult(1, [&i](ULong64_t) { ++i; })
.OnPartialResultSlot(1, [&i](unsigned int, ULong64_t) {++i; });
*c;
EXPECT_EQ(i, gNEvents * 2);
}
TEST_F(TDFCallbacks, OrderOfExecution)
{
// Test that callbacks are executed in the order they are registered
unsigned int i = 0u;
auto c = tdf.Count();
c.OnPartialResult(1, [&i](ULong64_t) {
EXPECT_EQ(i, 0u);
i = 42u;
});
c.OnPartialResultSlot(1, [&i](unsigned int slot, ULong64_t) {
if (slot == 0u) {
EXPECT_EQ(i, 42u);
i = 0u;
}
});
*c;
EXPECT_EQ(i, 0u);
}
TEST_F(TDFCallbacks, ExecuteOnce)
{
// OnPartialResult(kOnce)
auto c = tdf.Count();
unsigned int callCount = 0;
c.OnPartialResult(0, [&callCount](ULong64_t) { callCount++; });
*c;
EXPECT_EQ(callCount, 1u);
}
TEST_F(TDFCallbacks, MultipleCallbacks)
{
// registration of multiple callbacks on the same partial result
auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x");
using value_t = typename decltype(h)::Value_t;
ULong64_t everyN = 1ull;
ULong64_t i = 0ull;
h.OnPartialResult(everyN, [&i, everyN](value_t &h_) {
i += everyN;
EXPECT_EQ(h_.GetEntries(), i);
});
everyN = 2ull;
ULong64_t i2 = 0ull;
h.OnPartialResult(everyN, [&i2, everyN](value_t &h_) {
i2 += everyN;
EXPECT_EQ(h_.GetEntries(), i2);
});
*h;
}
TEST_F(TDFCallbacks, MultipleEventLoops)
{
// callbacks must be de-registered after the event-loop is run
auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x");
using value_t = typename decltype(h)::Value_t;
ULong64_t i = 0ull;
h.OnPartialResult(1ull, [&i](value_t &) { ++i; });
*h;
auto h2 = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x");
*h2;
EXPECT_EQ(i, gNEvents);
}
class FunctorClass {
unsigned int &i_;
public:
FunctorClass(unsigned int &i) : i_(i) {}
void operator()(ULong64_t) { ++i_; }
};
TEST_F(TDFCallbacks, FunctorClass)
{
unsigned int i = 0;
*(tdf.Count().OnPartialResult(1, FunctorClass(i)));
EXPECT_EQ(i, gNEvents);
}
unsigned int freeFunctionCounter = 0;
void FreeFunction(ULong64_t)
{
freeFunctionCounter++;
}
TEST_F(TDFCallbacks, FreeFunction)
{
*(tdf.Count().OnPartialResult(1, FreeFunction));
EXPECT_EQ(freeFunctionCounter, gNEvents);
}
#ifdef R__USE_IMT
/******** Multi-thread tests **********/
TEST_F(TDFCallbacksMT, ExecuteOncePerSlot)
{
// OnPartialResultSlot(kOnce)
auto c = tdf.Count();
std::atomic_uint callCount(0u);
c.OnPartialResultSlot(c.kOnce, [&callCount](unsigned int, ULong64_t) { callCount++; });
*c;
EXPECT_EQ(callCount, gNSlots * 2); // TDF spawns two tasks per slot
}
TEST_F(TDFCallbacksMT, Histo1DWithFillTOHelper)
{
// Histo1D<double> + OnPartialResultSlot + FillTOHelper
auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x");
using value_t = typename decltype(h)::Value_t;
std::array<ULong64_t, gNSlots> is;
is.fill(0ull);
constexpr ULong64_t everyN = 1ull;
h.OnPartialResultSlot(everyN, [&is, &everyN](unsigned int slot, value_t &h_) {
is[slot] += everyN;
EXPECT_EQ(h_.GetEntries(), is[slot]);
});
*h;
EXPECT_EQ(gNEvents, std::accumulate(is.begin(), is.end(), 0ull));
}
TEST_F(TDFCallbacksMT, Histo1DWithFillHelper)
{
// Histo1D<double> + OnPartialResultSlot + FillHelper
auto h = tdf.Histo1D<double>("x");
using value_t = typename decltype(h)::Value_t;
std::array<ULong64_t, gNSlots> is;
is.fill(0ull);
constexpr ULong64_t everyN = 1ull;
h.OnPartialResultSlot(everyN, [&is, &everyN](unsigned int slot, value_t &h_) {
is[slot] += everyN;
EXPECT_EQ(h_.GetEntries(), is[slot]);
});
*h;
EXPECT_EQ(gNEvents, std::accumulate(is.begin(), is.end(), 0ull));
}
#endif
<|endoftext|>
|
<commit_before>#include "normals.h"
PointCloud<PointXYZINormal> Normals::estimate() {
PointCloud<PointXYZINormal> normals;
for (auto point : cloud.points) {
auto neighbors = find_neighbors_naive(point, 10);
auto covar = covariance(neighbors);
double eig_val[3];
double eig_vec[9];
eigen3(&covar[0], eig_val, eig_vec);
normals.points.push_back(PointXYZINormal(point.x, point.y, point.z, 1.0, eig_vec[6], eig_vec[7], eig_vec[8]));
}
return normals;
}
PointCloud<Point3D> Normals::find_neighbors_naive(Point3D &query_point, int k_neighbors) {
double dist_thresh = DBL_MAX;
double d;
auto cmp = [&](Point3D left, Point3D right) { return (query_point.distance2(left)) > (query_point.distance2(right));};
std::priority_queue<Point3D, std::vector<Point3D>, decltype(cmp)> queue(cmp);
for (auto point : cloud.points) {
d = query_point.distance2(point);
if (d < dist_thresh) {
queue.push(point);
// TODO reduce threshold size
}
}
PointCloud<Point3D> neighbors;
for (int i = 0; i < k_neighbors; ++i) {
Point3D p = queue.top();
queue.pop();
neighbors.points.push_back(p);
}
return neighbors;
}
<commit_msg>Minor changes<commit_after>#include "normals.h"
PointCloud<PointXYZINormal> Normals::estimate() {
PointCloud<PointXYZINormal> normals;
double eig_val[3], eig_vec[9];
for (auto point : cloud.points) {
auto neighbors = find_neighbors_naive(point, 10);
auto covar = covariance(neighbors);
eigen3(&covar[0], eig_val, eig_vec);
normals.points.push_back(PointXYZINormal(point.x, point.y, point.z, 1.0, eig_vec[6], eig_vec[7], eig_vec[8]));
}
return normals;
}
PointCloud<Point3D> Normals::find_neighbors_naive(Point3D &query_point, int k_neighbors) {
auto cmp = [&](Point3D left, Point3D right) { return (query_point.distance2(left)) < (query_point.distance2(right));};
auto cloud_sort = cloud;
std::sort(cloud_sort.points.begin(), cloud_sort.points.end(), cmp);
PointCloud<Point3D> neighbors;
for (int i = 0; i < k_neighbors; ++i) {
neighbors.points.push_back(cloud_sort.points[i]);
}
return neighbors;
}
<|endoftext|>
|
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: representation.C,v 1.53 2004/12/03 00:42:49 amoll Exp $
//
#include <BALL/VIEW/KERNEL/representation.h>
#include <BALL/VIEW/MODELS/modelProcessor.h>
#include <BALL/VIEW/MODELS/colorProcessor.h>
#include <BALL/VIEW/KERNEL/geometricObject.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/SYSTEM/timer.h>
#include <qapplication.h>
// #define BALL_BENCHMARKING
namespace BALL
{
namespace VIEW
{
Representation::Representation()
throw()
: PropertyManager(),
drawing_mode_(DRAWING_MODE_SOLID),
drawing_precision_(DRAWING_PRECISION_HIGH),
surface_drawing_precision_(-1),
model_type_(MODEL_UNKNOWN),
coloring_method_(COLORING_UNKNOWN),
transparency_(0),
model_processor_(0),
color_processor_(0),
geometric_objects_(),
composites_(),
model_build_time_(),
rebuild_(true),
hidden_(false)
{
}
Representation::Representation(const Representation& rp)
throw()
: PropertyManager(rp),
drawing_mode_(rp.drawing_mode_),
drawing_precision_(rp.drawing_precision_),
surface_drawing_precision_(rp.drawing_precision_),
model_type_(rp.model_type_),
coloring_method_(rp.coloring_method_),
transparency_(rp.transparency_),
model_processor_(0),
color_processor_(0),
geometric_objects_(),
composites_(rp.composites_),
model_build_time_(),
rebuild_(rp.rebuild_),
hidden_(rp.hidden_)
{
if (rp.model_processor_ != 0)
{
model_processor_ = new ModelProcessor(*rp.model_processor_);
}
if (rp.color_processor_ != 0)
{
color_processor_ = new ColorProcessor(*rp.color_processor_);
}
GeometricObjectList::ConstIterator it = rp.geometric_objects_.begin();
for (;it != rp.geometric_objects_.end(); it++)
{
GeometricObject* object = new GeometricObject(**it);
geometric_objects_.push_back(object);
}
}
Representation::Representation(ModelType model_type,
DrawingPrecision drawing_precision,
DrawingMode drawing_mode)
throw()
: PropertyManager(),
drawing_mode_(drawing_mode),
drawing_precision_(drawing_precision),
surface_drawing_precision_(-1),
model_type_(model_type),
transparency_(0),
model_processor_(0),
color_processor_(0),
geometric_objects_(),
composites_(),
model_build_time_(),
rebuild_(true),
hidden_(false)
{
}
Representation::Representation(const HashSet<const Composite*>& composites,
ModelProcessor* model_processor)
throw()
: PropertyManager(),
drawing_mode_(DRAWING_MODE_SOLID),
drawing_precision_(DRAWING_PRECISION_HIGH),
surface_drawing_precision_(-1),
transparency_(0),
model_processor_(model_processor),
color_processor_(0),
geometric_objects_(),
composites_(composites),
model_build_time_(),
rebuild_(true),
hidden_(false)
{
}
const Representation& Representation::operator = (const Representation& representation)
throw()
{
clear();
drawing_mode_= representation.drawing_mode_;
drawing_precision_= representation.drawing_precision_;
model_type_ = representation.model_type_;
coloring_method_ = representation.coloring_method_;
transparency_ = representation.transparency_;
surface_drawing_precision_ = representation.surface_drawing_precision_;
PropertyManager::operator = (representation);
if (representation.model_processor_ != 0)
{
model_processor_ = new ModelProcessor(*representation.model_processor_);
}
else
{
model_processor_ = 0;
}
if (representation.color_processor_ != 0)
{
color_processor_ = new ColorProcessor(*representation.color_processor_);
color_processor_->setTransparency(transparency_);
}
else
{
color_processor_ = 0;
}
GeometricObjectList::ConstIterator it = representation.geometric_objects_.begin();
for (;it != representation.geometric_objects_.end(); it++)
{
GeometricObject* object = new GeometricObject(**it);
geometric_objects_.push_back(object);
}
composites_ = representation.composites_;
rebuild_ = true;
hidden_ = representation.hidden_;
return *this;
}
Representation::~Representation()
throw()
{
clear();
}
void Representation::clear()
throw()
{
clearGeometricObjects();
composites_.clear();
if (model_processor_ != 0) delete model_processor_;
if (color_processor_ != 0) delete color_processor_;
model_processor_ = 0;
color_processor_ = 0;
drawing_mode_= DRAWING_MODE_SOLID;
drawing_precision_= DRAWING_PRECISION_HIGH;
model_type_ = MODEL_UNKNOWN;
coloring_method_ = COLORING_UNKNOWN;
transparency_ = 0;
surface_drawing_precision_ = -1;
rebuild_ = true;
hidden_ = false;
}
void Representation::clearGeometricObjects()
throw()
{
List<GeometricObject*>::Iterator it = geometric_objects_.begin();
for (; it != geometric_objects_.end(); it++)
{
delete *it;
}
geometric_objects_.clear();
if (model_processor_ != 0)
{
model_processor_->getGeometricObjects().clear();
}
}
void Representation::dump(std::ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
BALL_DUMP_DEPTH(s, depth);
s << "drawing mode: " << drawing_mode_<< std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "drawing precision: " << drawing_precision_<< std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "model type : " << model_type_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "coloring type : " << coloring_method_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "number of primitives: " << geometric_objects_.size() << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "number of composites: " << composites_.size() << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "model processor: " << model_processor_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "hidden: " << hidden_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "PropertyManager: " << std::endl;
PropertyManager::dump(s, depth + 1);
BALL_DUMP_STREAM_SUFFIX(s);
}
bool Representation::isValid() const
throw()
{
if (drawing_precision_ < 0 || drawing_precision_ > BALL_VIEW_MAXIMAL_DRAWING_PRECISION ||
drawing_mode_ < 0 || drawing_mode_ > BALL_VIEW_MAXIMAL_DRAWING_MODE ||
transparency_ > 255)
{
return false;
}
#ifdef BALL_VIEW_DEBUG
GeometricObjectList::ConstIterator it = geometric_objects_.begin();
for (; it != geometric_objects_.end(); it++)
{
if (!(*it)->isValid()) return false;
}
#endif
if (model_processor_ != 0 && !model_processor_->isValid()) return false;
return true;
}
void Representation::update(bool rebuild)
throw()
{
rebuild_ = rebuild;
#ifdef BALL_QT_HAS_THREADS
MainControl* mc = getMainControl();
if (mc != 0)
{
// MainControl* mc = dynamic_cast<MainControl*>(qApp->mainWidget());
mc->getPrimitiveManager().update_(*this);
return;
}
#endif
update_();
}
void Representation::update_()
throw()
{
needs_update_ = false;
#ifdef BALL_BENCHMARKING
Timer t;
t.start();
#endif
// if no ModelProcessor was given, there can only exist
// handmade GeometricObjects, which dont need to be updated
if (model_processor_ != 0 && rebuild_)
{
clearGeometricObjects();
model_processor_->getGeometricObjects().clear();
model_processor_->clearComposites();
CompositeSet::Iterator it = composites_.begin();
for (; it!= composites_.end(); it++)
{
(const_cast<Composite*>(*it))->apply(*model_processor_);
}
model_processor_->createGeometricObjects();
geometric_objects_ = model_processor_->getGeometricObjects();
model_build_time_ = PreciseTime::now();
}
if (color_processor_ != 0)
{
// make sure, that the atom grid is recomputed for meshes
if (rebuild_) color_processor_->setComposites(&composites_);
color_processor_->setTransparency(transparency_);
color_processor_->setModelType(model_type_);
geometric_objects_.apply(*color_processor_);
}
#ifdef BALL_BENCHMARKING
Log.info() << "Calculating Representation time: " << t.getCPUTime() << std::endl;
t.stop();
#endif
}
String Representation::getModelName() const
throw()
{
return VIEW::getModelName(model_type_);
}
String Representation::getColoringName() const
throw()
{
return VIEW::getColoringName(coloring_method_);
}
String Representation::getProperties() const
throw()
{
return String(composites_.size()) + " C, " + String(geometric_objects_.size()) + " P";
}
void Representation::setModelProcessor(ModelProcessor* processor)
throw()
{
if (model_processor_ != 0)
{
delete model_processor_;
}
model_processor_ = processor;
if (model_processor_ != 0)
{
model_processor_->setDrawingPrecision(drawing_precision_);
model_processor_->setSurfaceDrawingPrecision(surface_drawing_precision_);
}
}
void Representation::setColorProcessor(ColorProcessor* processor)
throw()
{
if (color_processor_ != 0)
{
delete color_processor_;
}
color_processor_ = processor;
if (color_processor_ != 0)
{
color_processor_->setComposites(&composites_);
color_processor_->setTransparency(transparency_);
}
}
void Representation::setDrawingPrecision(DrawingPrecision precision)
throw()
{
drawing_precision_ = precision;
if (model_processor_ != 0) model_processor_->setDrawingPrecision(drawing_precision_);
}
void Representation::setSurfaceDrawingPrecision(float precision)
throw()
{
surface_drawing_precision_ = precision;
if (model_processor_ != 0) model_processor_->setSurfaceDrawingPrecision(surface_drawing_precision_);
}
void Representation::setTransparency(Size value)
throw()
{
transparency_ = value;
if (transparency_ > 255)
{
transparency_ = 255;
}
if (color_processor_ != 0)
{
color_processor_->setTransparency(transparency_);
}
}
bool Representation::needsUpdate() const
throw()
{
if (getModelType() == MODEL_CLIPPING_PLANE)
{
return false;
}
if (needs_update_ ||
getModelBuildTime() < Atom::getAttributesModificationTime())
{
return true;
}
CompositeSet::ConstIterator it = composites_.begin();
for (;it != composites_.end(); it++)
{
if (getModelBuildTime() < (*it)->getModificationTime()) return true;
}
return false;
}
String Representation::toString() const
throw()
{
String result;
if (getModelType() == MODEL_CLIPPING_PLANE)
{
result+= "CP:";
result+= String(getProperty("AX").getFloat()) + " ";
result+= String(getProperty("BY").getFloat()) + " ";
result+= String(getProperty("CZ").getFloat()) + " ";
result+= String(getProperty("D").getFloat());
return result;
}
result += String(model_type_) + " ";
result += String(drawing_mode_) + " ";
result += String(drawing_precision_) + " ";
result += String(surface_drawing_precision_) + " ";
result += String(coloring_method_) + " ";
result += String(transparency_) + " ";
if (composites_.size() == 0)
{
result += "[]";
return result;
}
result += "[";
const Composite& root = (*composites_.begin())->getRoot();
HashMap<const Composite*, Position> composite_to_index;
collectRecursive_(root, composite_to_index);
CompositesConstIterator it = begin();
for (; it != end(); it++)
{
if (composite_to_index.has(*it))
{
result += String(composite_to_index[*it]) + ",";
}
}
result.trimRight(",");
result += "]";
if (color_processor_ != 0)
{
result += "|";
String temp;
result += color_processor_->getDefaultColor();
result += "|";
}
if (isHidden())
{
result += "H";
}
return result;
}
void Representation::collectRecursive_(const Composite& c,
HashMap<const Composite*, Position>& hashmap) const
throw()
{
hashmap[&c] = hashmap.size();
for (Position p = 0; p < c.getDegree(); p++)
{
collectRecursive_(*c.getChild(p), hashmap);
}
}
} // namespace VIEW
} // namespace BALL
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: representation.C,v 1.54 2004/12/09 23:22:56 amoll Exp $
//
#include <BALL/VIEW/KERNEL/representation.h>
#include <BALL/VIEW/MODELS/modelProcessor.h>
#include <BALL/VIEW/MODELS/colorProcessor.h>
#include <BALL/VIEW/KERNEL/geometricObject.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/SYSTEM/timer.h>
#include <qapplication.h>
// #define BALL_BENCHMARKING
namespace BALL
{
namespace VIEW
{
Representation::Representation()
throw()
: PropertyManager(),
drawing_mode_(DRAWING_MODE_SOLID),
drawing_precision_(DRAWING_PRECISION_HIGH),
surface_drawing_precision_(-1),
model_type_(MODEL_UNKNOWN),
coloring_method_(COLORING_UNKNOWN),
transparency_(0),
model_processor_(0),
color_processor_(0),
geometric_objects_(),
composites_(),
model_build_time_(),
rebuild_(true),
hidden_(false)
{
}
Representation::Representation(const Representation& rp)
throw()
: PropertyManager(rp),
drawing_mode_(rp.drawing_mode_),
drawing_precision_(rp.drawing_precision_),
surface_drawing_precision_(rp.drawing_precision_),
model_type_(rp.model_type_),
coloring_method_(rp.coloring_method_),
transparency_(rp.transparency_),
model_processor_(0),
color_processor_(0),
geometric_objects_(),
composites_(rp.composites_),
model_build_time_(),
rebuild_(rp.rebuild_),
hidden_(rp.hidden_)
{
if (rp.model_processor_ != 0)
{
model_processor_ = new ModelProcessor(*rp.model_processor_);
}
if (rp.color_processor_ != 0)
{
color_processor_ = new ColorProcessor(*rp.color_processor_);
}
GeometricObjectList::ConstIterator it = rp.geometric_objects_.begin();
for (;it != rp.geometric_objects_.end(); it++)
{
GeometricObject* object = new GeometricObject(**it);
geometric_objects_.push_back(object);
}
}
Representation::Representation(ModelType model_type,
DrawingPrecision drawing_precision,
DrawingMode drawing_mode)
throw()
: PropertyManager(),
drawing_mode_(drawing_mode),
drawing_precision_(drawing_precision),
surface_drawing_precision_(-1),
model_type_(model_type),
transparency_(0),
model_processor_(0),
color_processor_(0),
geometric_objects_(),
composites_(),
model_build_time_(),
rebuild_(true),
hidden_(false)
{
}
Representation::Representation(const HashSet<const Composite*>& composites,
ModelProcessor* model_processor)
throw()
: PropertyManager(),
drawing_mode_(DRAWING_MODE_SOLID),
drawing_precision_(DRAWING_PRECISION_HIGH),
surface_drawing_precision_(-1),
transparency_(0),
model_processor_(model_processor),
color_processor_(0),
geometric_objects_(),
composites_(composites),
model_build_time_(),
rebuild_(true),
hidden_(false)
{
}
const Representation& Representation::operator = (const Representation& representation)
throw()
{
clear();
drawing_mode_= representation.drawing_mode_;
drawing_precision_= representation.drawing_precision_;
model_type_ = representation.model_type_;
coloring_method_ = representation.coloring_method_;
transparency_ = representation.transparency_;
surface_drawing_precision_ = representation.surface_drawing_precision_;
PropertyManager::operator = (representation);
if (representation.model_processor_ != 0)
{
model_processor_ = new ModelProcessor(*representation.model_processor_);
}
else
{
model_processor_ = 0;
}
if (representation.color_processor_ != 0)
{
color_processor_ = new ColorProcessor(*representation.color_processor_);
color_processor_->setTransparency(transparency_);
}
else
{
color_processor_ = 0;
}
GeometricObjectList::ConstIterator it = representation.geometric_objects_.begin();
for (;it != representation.geometric_objects_.end(); it++)
{
GeometricObject* object = new GeometricObject(**it);
geometric_objects_.push_back(object);
}
composites_ = representation.composites_;
rebuild_ = true;
hidden_ = representation.hidden_;
return *this;
}
Representation::~Representation()
throw()
{
clear();
}
void Representation::clear()
throw()
{
clearGeometricObjects();
composites_.clear();
if (model_processor_ != 0) delete model_processor_;
if (color_processor_ != 0) delete color_processor_;
model_processor_ = 0;
color_processor_ = 0;
drawing_mode_= DRAWING_MODE_SOLID;
drawing_precision_= DRAWING_PRECISION_HIGH;
model_type_ = MODEL_UNKNOWN;
coloring_method_ = COLORING_UNKNOWN;
transparency_ = 0;
surface_drawing_precision_ = -1;
rebuild_ = true;
hidden_ = false;
}
void Representation::clearGeometricObjects()
throw()
{
List<GeometricObject*>::Iterator it = geometric_objects_.begin();
for (; it != geometric_objects_.end(); it++)
{
delete *it;
}
geometric_objects_.clear();
if (model_processor_ != 0)
{
model_processor_->getGeometricObjects().clear();
}
}
void Representation::dump(std::ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
BALL_DUMP_DEPTH(s, depth);
s << "drawing mode: " << drawing_mode_<< std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "drawing precision: " << drawing_precision_<< std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "model type : " << model_type_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "coloring type : " << coloring_method_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "number of primitives: " << geometric_objects_.size() << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "number of composites: " << composites_.size() << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "model processor: " << model_processor_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "hidden: " << hidden_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "PropertyManager: " << std::endl;
PropertyManager::dump(s, depth + 1);
BALL_DUMP_STREAM_SUFFIX(s);
}
bool Representation::isValid() const
throw()
{
if (drawing_precision_ < 0 || drawing_precision_ > BALL_VIEW_MAXIMAL_DRAWING_PRECISION ||
drawing_mode_ < 0 || drawing_mode_ > BALL_VIEW_MAXIMAL_DRAWING_MODE ||
transparency_ > 255)
{
return false;
}
#ifdef BALL_VIEW_DEBUG
GeometricObjectList::ConstIterator it = geometric_objects_.begin();
for (; it != geometric_objects_.end(); it++)
{
if (!(*it)->isValid()) return false;
}
#endif
if (model_processor_ != 0 && !model_processor_->isValid()) return false;
return true;
}
void Representation::update(bool rebuild)
throw()
{
rebuild_ = rebuild;
#ifdef BALL_QT_HAS_THREADS
MainControl* mc = getMainControl();
if (mc != 0)
{
// MainControl* mc = dynamic_cast<MainControl*>(qApp->mainWidget());
mc->getPrimitiveManager().update_(*this);
return;
}
#endif
update_();
}
void Representation::update_()
throw()
{
needs_update_ = false;
#ifdef BALL_BENCHMARKING
Timer t;
t.start();
#endif
// if no ModelProcessor was given, there can only exist
// handmade GeometricObjects, which dont need to be updated
if (model_processor_ != 0 && rebuild_)
{
clearGeometricObjects();
model_processor_->clearComposites();
CompositeSet::Iterator it = composites_.begin();
for (; it!= composites_.end(); it++)
{
(const_cast<Composite*>(*it))->apply(*model_processor_);
}
model_processor_->createGeometricObjects();
geometric_objects_ = model_processor_->getGeometricObjects();
model_build_time_ = PreciseTime::now();
}
if (color_processor_ != 0)
{
// make sure, that the atom grid is recomputed for meshes
if (rebuild_) color_processor_->setComposites(&composites_);
color_processor_->setTransparency(transparency_);
color_processor_->setModelType(model_type_);
geometric_objects_.apply(*color_processor_);
}
#ifdef BALL_BENCHMARKING
Log.info() << "Calculating Representation time: " << t.getCPUTime() << std::endl;
t.stop();
#endif
}
String Representation::getModelName() const
throw()
{
return VIEW::getModelName(model_type_);
}
String Representation::getColoringName() const
throw()
{
return VIEW::getColoringName(coloring_method_);
}
String Representation::getProperties() const
throw()
{
return String(composites_.size()) + " C, " + String(geometric_objects_.size()) + " P";
}
void Representation::setModelProcessor(ModelProcessor* processor)
throw()
{
if (model_processor_ != 0)
{
delete model_processor_;
}
model_processor_ = processor;
if (model_processor_ != 0)
{
model_processor_->setDrawingPrecision(drawing_precision_);
model_processor_->setSurfaceDrawingPrecision(surface_drawing_precision_);
}
}
void Representation::setColorProcessor(ColorProcessor* processor)
throw()
{
if (color_processor_ != 0)
{
delete color_processor_;
}
color_processor_ = processor;
if (color_processor_ != 0)
{
color_processor_->setComposites(&composites_);
color_processor_->setTransparency(transparency_);
}
}
void Representation::setDrawingPrecision(DrawingPrecision precision)
throw()
{
drawing_precision_ = precision;
if (model_processor_ != 0) model_processor_->setDrawingPrecision(drawing_precision_);
}
void Representation::setSurfaceDrawingPrecision(float precision)
throw()
{
surface_drawing_precision_ = precision;
if (model_processor_ != 0) model_processor_->setSurfaceDrawingPrecision(surface_drawing_precision_);
}
void Representation::setTransparency(Size value)
throw()
{
transparency_ = value;
if (transparency_ > 255)
{
transparency_ = 255;
}
if (color_processor_ != 0)
{
color_processor_->setTransparency(transparency_);
}
}
bool Representation::needsUpdate() const
throw()
{
if (getModelType() == MODEL_CLIPPING_PLANE)
{
return false;
}
if (needs_update_ ||
getModelBuildTime() < Atom::getAttributesModificationTime())
{
return true;
}
CompositeSet::ConstIterator it = composites_.begin();
for (;it != composites_.end(); it++)
{
if (getModelBuildTime() < (*it)->getModificationTime()) return true;
}
return false;
}
String Representation::toString() const
throw()
{
String result;
if (getModelType() == MODEL_CLIPPING_PLANE)
{
result+= "CP:";
result+= String(getProperty("AX").getFloat()) + " ";
result+= String(getProperty("BY").getFloat()) + " ";
result+= String(getProperty("CZ").getFloat()) + " ";
result+= String(getProperty("D").getFloat());
return result;
}
result += String(model_type_) + " ";
result += String(drawing_mode_) + " ";
result += String(drawing_precision_) + " ";
result += String(surface_drawing_precision_) + " ";
result += String(coloring_method_) + " ";
result += String(transparency_) + " ";
if (composites_.size() == 0)
{
result += "[]";
return result;
}
result += "[";
const Composite& root = (*composites_.begin())->getRoot();
HashMap<const Composite*, Position> composite_to_index;
collectRecursive_(root, composite_to_index);
CompositesConstIterator it = begin();
for (; it != end(); it++)
{
if (composite_to_index.has(*it))
{
result += String(composite_to_index[*it]) + ",";
}
}
result.trimRight(",");
result += "]";
if (color_processor_ != 0)
{
result += "|";
String temp;
result += color_processor_->getDefaultColor();
result += "|";
}
if (isHidden())
{
result += "H";
}
return result;
}
void Representation::collectRecursive_(const Composite& c,
HashMap<const Composite*, Position>& hashmap) const
throw()
{
hashmap[&c] = hashmap.size();
for (Position p = 0; p < c.getDegree(); p++)
{
collectRecursive_(*c.getChild(p), hashmap);
}
}
} // namespace VIEW
} // namespace BALL
<|endoftext|>
|
<commit_before>#include "mcrt/scene.hh"
#include <glm/glm.hpp>
#include <limits>
#include <vector>
#include <cmath>
namespace mcrt {
Ray::Intersection Scene::intersect(const Ray& ray) const {
Ray::Intersection closestHit {
std::numeric_limits<double>::max(),
glm::dvec3(0.0),
nullptr,
glm::dvec3(0.0)
};
for (const Geometry* geometry : geometries) {
Ray::Intersection rayHit = geometry->intersect(ray);
if (rayHit.distance > 0.0 && rayHit.distance < closestHit.distance)
closestHit = rayHit;
}
for (Light* lightSource : lights) {
Ray::Intersection lightHit = lightSource->intersect(ray);
if(lightHit.distance > 0.0 && lightHit.distance < closestHit.distance ){
closestHit = lightHit;
}
}
return closestHit;
}
double Scene::inShadow(const Ray& ray) const{
double distance = std::numeric_limits<double>::max();
for(const Geometry* geometry: geometries){
Ray::Intersection rayHit = geometry->intersect(ray);
if(rayHit.distance <= 0.0) {
continue;
}
// Intersects Refractive surface
if(rayHit.material->type == Material::Type::Refractive){
continue;
}
distance = std::min(distance, rayHit.distance);
}
// Return distance to occlusion
return distance;
}
// Will be our resource after this...
void Scene::add(Geometry* geometry) {
geometries.push_back(geometry);
}
void Scene::add(Material* material) {
materials.push_back(material);
}
void Scene::add(Light* light) {
lights.push_back(light);
}
size_t Scene::maxRayDepth = 10;
// Store the resulting photons in the photons vector.
void Scene::photonTrace(const Ray& ray, const size_t depth = 0) const {
// Make sure we don't bounce forever
if(depth >= Scene::maxRayDepth)
return;
Ray::Intersection rayHit = intersect(ray);
glm::dvec3 rayHitPosition { ray.origin + ray.direction * rayHit.distance };
// We have hit nothing or something like that I guess.....
if (rayHit.material == nullptr) return;
if(rayHit.material->type == Material::Type::Diffuse) {
// We terminate path
photons[currentPhoton];
} else if(rayHit.material->type == Material::Type::Reflective) {
Ray reflectionRay { ray.reflect(rayHitPosition, rayHit.normal) };
photonTrace(reflectionRay, depth + 1);
} else if(rayHit.material->type == Material::Type::Refractive) {
double kr = ray.fresnel(rayHit.normal, rayHit.material->refractionIndex);
bool outside = glm::dot(ray.direction, rayHit.normal) < 0.0;
if(kr < 1.0) { // Check if ray isn't completely parallel to graze.
Ray refractionRay { ray.refract(rayHitPosition, rayHit.normal,
rayHit.material->refractionIndex) };
photonTrace(refractionRay,depth + 1);
return;
}
Ray reflectionRay; // If we need to invert the bias if we are inside.
if (outside) reflectionRay = ray.reflect(rayHitPosition, rayHit.normal);
else reflectionRay = ray.insideReflect(rayHitPosition, rayHit.normal);
photonTrace(reflectionRay, depth + 1);
return;
} else if(rayHit.material->type == Material::Type::LightSource) {
return;
}
return ;
}
const std::vector<Photon>& Scene::gatherPhotons() {
currentPhoton = 0;
photons.reserve(Scene::MAX_PHOTONS);
double totalLightArea = 0.0;
for(Light* l: lights) {
totalLightArea += dynamic_cast<AreaLight*>(l)->area;
}
for(Light* l: lights) {
AreaLight* al = dynamic_cast<AreaLight*>(l);
const double ratio = al->area / totalLightArea;
const unsigned numPhotons = ratio * Scene::MAX_PHOTONS;
// Create photons for this area light
for(unsigned i = 0; i < numPhotons; ++i) {
Ray path { al->sample(), al->sampleHemisphere()};
photonTrace(path);
++currentPhoton;
}
}
}
glm::dvec3 Scene::rayTrace(const Ray& ray, const size_t depth = 0) const {
glm::dvec3 rayColor { 0.0 };
// Make sure we don't bounce forever
if(depth >= Scene::maxRayDepth)
return rayColor;
Ray::Intersection rayHit = intersect(ray);
glm::dvec3 rayHitPosition { ray.origin + ray.direction * rayHit.distance };
// We have hit nothing or something like that I guess.....
if (rayHit.material == nullptr) return glm::dvec3 { 0.0 };
if(rayHit.material->type == Material::Type::Diffuse) {
glm::dvec3 reflectionDir = rayHit.sampleHemisphere(ray);
if (glm::length(reflectionDir) > 0.0) {
Ray reflectionRay { rayHit.position + reflectionDir*Ray::EPSILON, reflectionDir };
glm::dvec3 brdf = rayHit.material->brdf(rayHit.position, rayHit.normal, reflectionDir, -ray.direction);
rayColor += rayTrace(reflectionRay, depth + 1) * brdf * glm::pi<double>() / rayHit.material->reflectionRate;
}
for (Light* lightSource : lights) {
rayColor += lightSource->radiance(ray, rayHit, this);
}
} else if(rayHit.material->type == Material::Type::Reflective) {
Ray reflectionRay { ray.reflect(rayHitPosition, rayHit.normal) };
rayColor += rayTrace(reflectionRay, depth + 1) * 0.9; // Falloff.
} else if(rayHit.material->type == Material::Type::Refractive) {
double kr = ray.fresnel(rayHit.normal, rayHit.material->refractionIndex);
bool outside = glm::dot(ray.direction, rayHit.normal) < 0.0;
glm::dvec3 refractionColor = glm::dvec3(0.0);
glm::dvec3 refractionDir;
if(kr < 1.0) { // Check if ray isn't completely parallel to graze.
Ray refractionRay { ray.refract(rayHitPosition, rayHit.normal,
rayHit.material->refractionIndex) };
refractionColor = rayTrace(refractionRay,depth + 1);
}
Ray reflectionRay; // If we need to invert the bias if we are inside.
if (outside) reflectionRay = ray.reflect(rayHitPosition, rayHit.normal);
else reflectionRay = ray.insideReflect(rayHitPosition, rayHit.normal);
glm::dvec3 reflectionColor = rayTrace(reflectionRay, depth + 1);
rayColor += reflectionColor * kr + refractionColor * (1.0 - kr);
} else if(rayHit.material->type == Material::Type::LightSource) {
rayColor = rayHit.material->color;
}
return rayColor;
}
}
<commit_msg>Add photon radiance estimation to Scene::rayTrace<commit_after>#include "mcrt/scene.hh"
#include "mcrt/photon.hh"
#include <glm/glm.hpp>
#include <limits>
#include <vector>
#include <cmath>
namespace mcrt {
Ray::Intersection Scene::intersect(const Ray& ray) const {
Ray::Intersection closestHit {
std::numeric_limits<double>::max(),
glm::dvec3(0.0),
nullptr,
glm::dvec3(0.0)
};
for (const Geometry* geometry : geometries) {
Ray::Intersection rayHit = geometry->intersect(ray);
if (rayHit.distance > 0.0 && rayHit.distance < closestHit.distance)
closestHit = rayHit;
}
for (Light* lightSource : lights) {
Ray::Intersection lightHit = lightSource->intersect(ray);
if(lightHit.distance > 0.0 && lightHit.distance < closestHit.distance ){
closestHit = lightHit;
}
}
return closestHit;
}
double Scene::inShadow(const Ray& ray) const{
double distance = std::numeric_limits<double>::max();
for(const Geometry* geometry: geometries){
Ray::Intersection rayHit = geometry->intersect(ray);
if(rayHit.distance <= 0.0) {
continue;
}
// Intersects Refractive surface
if(rayHit.material->type == Material::Type::Refractive){
continue;
}
distance = std::min(distance, rayHit.distance);
}
// Return distance to occlusion
return distance;
}
// Will be our resource after this...
void Scene::add(Geometry* geometry) {
geometries.push_back(geometry);
}
void Scene::add(Material* material) {
materials.push_back(material);
}
void Scene::add(Light* light) {
lights.push_back(light);
}
size_t Scene::maxRayDepth = 10;
// Store the resulting photons in the photons vector.
void Scene::photonTrace(const Ray& ray, const size_t depth = 0) const {
// Make sure we don't bounce forever
if(depth >= Scene::maxRayDepth)
return;
Ray::Intersection rayHit = intersect(ray);
glm::dvec3 rayHitPosition { ray.origin + ray.direction * rayHit.distance };
// We have hit nothing or something like that I guess.....
if (rayHit.material == nullptr) return;
if(rayHit.material->type == Material::Type::Diffuse) {
// We terminate path
photons[currentPhoton];
} else if(rayHit.material->type == Material::Type::Reflective) {
Ray reflectionRay { ray.reflect(rayHitPosition, rayHit.normal) };
photonTrace(reflectionRay, depth + 1);
} else if(rayHit.material->type == Material::Type::Refractive) {
double kr = ray.fresnel(rayHit.normal, rayHit.material->refractionIndex);
bool outside = glm::dot(ray.direction, rayHit.normal) < 0.0;
if(kr < 1.0) { // Check if ray isn't completely parallel to graze.
Ray refractionRay { ray.refract(rayHitPosition, rayHit.normal,
rayHit.material->refractionIndex) };
photonTrace(refractionRay,depth + 1);
return;
}
Ray reflectionRay; // If we need to invert the bias if we are inside.
if (outside) reflectionRay = ray.reflect(rayHitPosition, rayHit.normal);
else reflectionRay = ray.insideReflect(rayHitPosition, rayHit.normal);
photonTrace(reflectionRay, depth + 1);
return;
} else if(rayHit.material->type == Material::Type::LightSource) {
return;
}
return ;
}
const std::vector<Photon>& Scene::gatherPhotons() {
currentPhoton = 0;
photons.reserve(Scene::MAX_PHOTONS);
double totalLightArea = 0.0;
for(Light* l: lights) {
totalLightArea += dynamic_cast<AreaLight*>(l)->area;
}
for(Light* l: lights) {
AreaLight* al = dynamic_cast<AreaLight*>(l);
const double ratio = al->area / totalLightArea;
const unsigned numPhotons = ratio * Scene::MAX_PHOTONS;
// Create photons for this area light
for(unsigned i = 0; i < numPhotons; ++i) {
Ray path { al->sample(), al->sampleHemisphere()};
photonTrace(path);
++currentPhoton;
}
}
return photons;
}
glm::dvec3 Scene::rayTrace(const Ray& ray, const size_t depth = 0) const {
glm::dvec3 rayColor { 0.0 };
// Make sure we don't bounce forever
if(depth >= Scene::maxRayDepth)
return rayColor;
Ray::Intersection rayHit = intersect(ray);
glm::dvec3 rayHitPosition { ray.origin + ray.direction * rayHit.distance };
// We have hit nothing or something like that I guess.....
if (rayHit.material == nullptr) return glm::dvec3 { 0.0 };
if(rayHit.material->type == Material::Type::Diffuse) {
glm::dvec3 reflectionDir = rayHit.sampleHemisphere(ray);
if (glm::length(reflectionDir) > 0.0) {
Ray reflectionRay { rayHit.position + reflectionDir*Ray::EPSILON, reflectionDir };
glm::dvec3 brdf = rayHit.material->brdf(rayHit.position, rayHit.normal, reflectionDir, -ray.direction);
rayColor += rayTrace(reflectionRay, depth + 1) * brdf * glm::pi<double>() / rayHit.material->reflectionRate;
}
glm::dvec3 color{0};
double radius{0};
std::vector<Photon*> photons{};
bool radianceEstimationPossible = false;
// Use photon map to estimate radiance from direct lighting
if (radianceEstimationPossible) {
for (Photon* photon : photons) {
double distance = glm::distance(rayHit.position, photon->position);
radius = std::max(radius, distance);
glm::dvec3 brdf = rayHit.material->brdf(rayHit.position, rayHit.normal, -photon->incoming, -ray.direction);
color += brdf * photon->color;
}
rayColor += color / (glm::pi<double>() * (radius*radius));
}
// Photon mapping conditions not met, use MC raytracing instead
else {
for (Light* lightSource : lights) {
rayColor += lightSource->radiance(ray, rayHit, this);
}
}
} else if(rayHit.material->type == Material::Type::Reflective) {
Ray reflectionRay { ray.reflect(rayHitPosition, rayHit.normal) };
rayColor += rayTrace(reflectionRay, depth + 1) * 0.9; // Falloff.
} else if(rayHit.material->type == Material::Type::Refractive) {
double kr = ray.fresnel(rayHit.normal, rayHit.material->refractionIndex);
bool outside = glm::dot(ray.direction, rayHit.normal) < 0.0;
glm::dvec3 refractionColor = glm::dvec3(0.0);
glm::dvec3 refractionDir;
if(kr < 1.0) { // Check if ray isn't completely parallel to graze.
Ray refractionRay { ray.refract(rayHitPosition, rayHit.normal,
rayHit.material->refractionIndex) };
refractionColor = rayTrace(refractionRay,depth + 1);
}
Ray reflectionRay; // If we need to invert the bias if we are inside.
if (outside) reflectionRay = ray.reflect(rayHitPosition, rayHit.normal);
else reflectionRay = ray.insideReflect(rayHitPosition, rayHit.normal);
glm::dvec3 reflectionColor = rayTrace(reflectionRay, depth + 1);
rayColor += reflectionColor * kr + refractionColor * (1.0 - kr);
} else if(rayHit.material->type == Material::Type::LightSource) {
rayColor = rayHit.material->color;
}
return rayColor;
}
}
<|endoftext|>
|
<commit_before>#include "notebook.h"
#include "logging.h"
#include "sourcefile.h"
#include "singletons.h"
#include <fstream>
#include <regex>
#include "cmake.h"
#include <iostream> //TODO: remove
using namespace std; //TODO: remove
namespace sigc {
#ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
template <typename Functor>
struct functor_trait<Functor, false> {
typedef decltype (::sigc::mem_fun(std::declval<Functor&>(),
&Functor::operator())) _intermediate;
typedef typename _intermediate::result_type result_type;
typedef Functor functor_type;
};
#else
SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
#endif
}
Notebook::Notebook(Directories &directories) : Gtk::Notebook(), directories(directories) {
Gsv::init();
}
int Notebook::size() {
return get_n_pages();
}
Source::View* Notebook::get_view(int page) {
return source_views.at(get_index(page));
}
size_t Notebook::get_index(int page) {
for(size_t c=0;c<hboxes.size();c++) {
if(page_num(*hboxes.at(c))==page)
return c;
}
return -1;
}
Source::View* Notebook::get_current_view() {
return get_view(get_current_page());
}
void Notebook::open(const boost::filesystem::path &file_path) {
DEBUG("start");
for(int c=0;c<size();c++) {
if(file_path==get_view(c)->file_path) {
set_current_page(c);
get_current_view()->grab_focus();
return;
}
}
std::ifstream can_read(file_path.string());
if(!can_read) {
Singleton::terminal()->print("Error: could not open "+file_path.string()+"\n");
return;
}
can_read.close();
auto language=Source::guess_language(file_path);
if(language && (language->get_id()=="chdr" || language->get_id()=="c" || language->get_id()=="cpp" || language->get_id()=="objc")) {
boost::filesystem::path project_path;
if(directories.cmake && directories.cmake->project_path!="" && file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/')
project_path=directories.cmake->project_path;
else {
project_path=file_path.parent_path();
CMake cmake(project_path);
if(cmake.project_path!="") {
project_path=cmake.project_path;
Singleton::terminal()->print("Project path for "+file_path.string()+" set to "+project_path.string()+"\n");
}
else
Singleton::terminal()->print("Error: could not find project path for "+file_path.string()+"\n");
}
source_views.emplace_back(new Source::ClangView(file_path, project_path, language));
}
else
source_views.emplace_back(new Source::GenericView(file_path, language));
source_views.back()->on_update_status=[this](Source::View* view, const std::string &status) {
if(get_current_page()!=-1 && get_current_view()==view)
Singleton::status()->set_text(status+" ");
};
source_views.back()->on_update_info=[this](Source::View* view, const std::string &info) {
if(get_current_page()!=-1 && get_current_view()==view)
Singleton::info()->set_text(" "+info);
};
scrolled_windows.emplace_back(new Gtk::ScrolledWindow());
hboxes.emplace_back(new Gtk::HBox());
scrolled_windows.back()->add(*source_views.back());
hboxes.back()->pack_start(*scrolled_windows.back(), true, true);
std::string title=file_path.filename().string();
append_page(*hboxes.back(), title);
set_tab_reorderable(*hboxes.back(), true);
show_all_children();
set_current_page(size()-1);
set_focus_child(*source_views.back());
get_current_view()->get_buffer()->set_modified(false);
get_current_view()->grab_focus();
//Add star on tab label when the page is not saved:
auto source_view=get_current_view();
get_current_view()->get_buffer()->signal_modified_changed().connect([this, source_view]() {
std::string title=source_view->file_path.filename().string();
if(source_view->get_buffer()->get_modified())
title+="*";
int page=-1;
for(int c=0;c<size();c++) {
if(get_view(c)==source_view) {
page=c;
break;
}
}
if(page!=-1)
set_tab_label_text(*(get_nth_page(page)), title);
});
DEBUG("end");
}
bool Notebook::save(int page, bool reparse_needed) {
DEBUG("start");
if(page>=size()) {
DEBUG("end false");
return false;
}
auto view=get_view(page);
if (view->file_path != "" && view->get_buffer()->get_modified()) {
if(juci::filesystem::write(view->file_path, view->get_buffer())) {
if(reparse_needed) {
if(auto clang_view=dynamic_cast<Source::ClangView*>(view)) {
for(auto a_view: source_views) {
if(auto a_clang_view=dynamic_cast<Source::ClangView*>(a_view)) {
if(clang_view!=a_clang_view)
a_clang_view->reparse_needed=true;
}
}
}
}
view->get_buffer()->set_modified(false);
Singleton::terminal()->print("File saved to: " +view->file_path.string()+"\n");
//If CMakeLists.txt have been modified:
//TODO: recreate cmake even without directories open?
if(view->file_path.filename()=="CMakeLists.txt") {
if(directories.cmake && directories.cmake->project_path!="" && view->file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/' && CMake::create_compile_commands(directories.cmake->project_path)) {
for(auto source_view: source_views) {
if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view)) {
if(directories.cmake->project_path.string()==source_clang_view->project_path) {
if(source_clang_view->restart_parse())
Singleton::terminal()->async_print("Reparsing "+source_clang_view->file_path.string()+"\n");
else
Singleton::terminal()->async_print("Error: failed to reparse "+source_clang_view->file_path.string()+". Please reopen the file manually.\n");
}
}
}
}
}
DEBUG("end true");
return true;
}
Singleton::terminal()->print("Error: could not save file " +view->file_path.string()+"\n");
}
DEBUG("end false");
return false;
}
bool Notebook::save_current() {
if(get_current_page()==-1)
return false;
return save(get_current_page(), true);
}
bool Notebook::close_current_page() {
DEBUG("start");
if (get_current_page()!=-1) {
if(get_current_view()->get_buffer()->get_modified()){
if(!save_modified_dialog()) {
DEBUG("end false");
return false;
}
}
int page = get_current_page();
int index=get_index(page);
remove_page(page);
auto source_view=source_views.at(index);
if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view))
source_clang_view->async_delete();
else
delete source_view;
source_views.erase(source_views.begin()+index);
scrolled_windows.erase(scrolled_windows.begin()+index);
hboxes.erase(hboxes.begin()+index);
}
DEBUG("end true");
return true;
}
bool Notebook::save_modified_dialog() {
Gtk::MessageDialog dialog((Gtk::Window&)(*get_toplevel()), "Save file!", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO);
dialog.set_default_response(Gtk::RESPONSE_YES);
dialog.set_secondary_text("Do you want to save: " + get_current_view()->file_path.string()+" ?");
int result = dialog.run();
if(result==Gtk::RESPONSE_YES) {
save_current();
return true;
}
else if(result==Gtk::RESPONSE_NO) {
return true;
}
else {
return false;
}
}
<commit_msg>Now creates compile_commands if missing when opening a file in a project.<commit_after>#include "notebook.h"
#include "logging.h"
#include "sourcefile.h"
#include "singletons.h"
#include <fstream>
#include <regex>
#include "cmake.h"
#include <iostream> //TODO: remove
using namespace std; //TODO: remove
namespace sigc {
#ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
template <typename Functor>
struct functor_trait<Functor, false> {
typedef decltype (::sigc::mem_fun(std::declval<Functor&>(),
&Functor::operator())) _intermediate;
typedef typename _intermediate::result_type result_type;
typedef Functor functor_type;
};
#else
SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
#endif
}
Notebook::Notebook(Directories &directories) : Gtk::Notebook(), directories(directories) {
Gsv::init();
}
int Notebook::size() {
return get_n_pages();
}
Source::View* Notebook::get_view(int page) {
return source_views.at(get_index(page));
}
size_t Notebook::get_index(int page) {
for(size_t c=0;c<hboxes.size();c++) {
if(page_num(*hboxes.at(c))==page)
return c;
}
return -1;
}
Source::View* Notebook::get_current_view() {
return get_view(get_current_page());
}
void Notebook::open(const boost::filesystem::path &file_path) {
DEBUG("start");
for(int c=0;c<size();c++) {
if(file_path==get_view(c)->file_path) {
set_current_page(c);
get_current_view()->grab_focus();
return;
}
}
std::ifstream can_read(file_path.string());
if(!can_read) {
Singleton::terminal()->print("Error: could not open "+file_path.string()+"\n");
return;
}
can_read.close();
auto language=Source::guess_language(file_path);
if(language && (language->get_id()=="chdr" || language->get_id()=="c" || language->get_id()=="cpp" || language->get_id()=="objc")) {
boost::filesystem::path project_path;
if(directories.cmake && directories.cmake->project_path!="" && file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/') {
project_path=directories.cmake->project_path;
if(boost::filesystem::exists(project_path.string()+"/CMakeLists.txt") && !boost::filesystem::exists(project_path.string()+"/compile_commands.json"))
CMake::create_compile_commands(project_path);
}
else {
project_path=file_path.parent_path();
CMake cmake(project_path);
if(cmake.project_path!="") {
project_path=cmake.project_path;
Singleton::terminal()->print("Project path for "+file_path.string()+" set to "+project_path.string()+"\n");
}
else
Singleton::terminal()->print("Error: could not find project path for "+file_path.string()+"\n");
}
source_views.emplace_back(new Source::ClangView(file_path, project_path, language));
}
else
source_views.emplace_back(new Source::GenericView(file_path, language));
source_views.back()->on_update_status=[this](Source::View* view, const std::string &status) {
if(get_current_page()!=-1 && get_current_view()==view)
Singleton::status()->set_text(status+" ");
};
source_views.back()->on_update_info=[this](Source::View* view, const std::string &info) {
if(get_current_page()!=-1 && get_current_view()==view)
Singleton::info()->set_text(" "+info);
};
scrolled_windows.emplace_back(new Gtk::ScrolledWindow());
hboxes.emplace_back(new Gtk::HBox());
scrolled_windows.back()->add(*source_views.back());
hboxes.back()->pack_start(*scrolled_windows.back(), true, true);
std::string title=file_path.filename().string();
append_page(*hboxes.back(), title);
set_tab_reorderable(*hboxes.back(), true);
show_all_children();
set_current_page(size()-1);
set_focus_child(*source_views.back());
get_current_view()->get_buffer()->set_modified(false);
get_current_view()->grab_focus();
//Add star on tab label when the page is not saved:
auto source_view=get_current_view();
get_current_view()->get_buffer()->signal_modified_changed().connect([this, source_view]() {
std::string title=source_view->file_path.filename().string();
if(source_view->get_buffer()->get_modified())
title+="*";
int page=-1;
for(int c=0;c<size();c++) {
if(get_view(c)==source_view) {
page=c;
break;
}
}
if(page!=-1)
set_tab_label_text(*(get_nth_page(page)), title);
});
DEBUG("end");
}
bool Notebook::save(int page, bool reparse_needed) {
DEBUG("start");
if(page>=size()) {
DEBUG("end false");
return false;
}
auto view=get_view(page);
if (view->file_path != "" && view->get_buffer()->get_modified()) {
if(juci::filesystem::write(view->file_path, view->get_buffer())) {
if(reparse_needed) {
if(auto clang_view=dynamic_cast<Source::ClangView*>(view)) {
for(auto a_view: source_views) {
if(auto a_clang_view=dynamic_cast<Source::ClangView*>(a_view)) {
if(clang_view!=a_clang_view)
a_clang_view->reparse_needed=true;
}
}
}
}
view->get_buffer()->set_modified(false);
Singleton::terminal()->print("File saved to: " +view->file_path.string()+"\n");
//If CMakeLists.txt have been modified:
//TODO: recreate cmake even without directories open?
if(view->file_path.filename()=="CMakeLists.txt") {
if(directories.cmake && directories.cmake->project_path!="" && view->file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/' && CMake::create_compile_commands(directories.cmake->project_path)) {
for(auto source_view: source_views) {
if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view)) {
if(directories.cmake->project_path.string()==source_clang_view->project_path) {
if(source_clang_view->restart_parse())
Singleton::terminal()->async_print("Reparsing "+source_clang_view->file_path.string()+"\n");
else
Singleton::terminal()->async_print("Error: failed to reparse "+source_clang_view->file_path.string()+". Please reopen the file manually.\n");
}
}
}
}
}
DEBUG("end true");
return true;
}
Singleton::terminal()->print("Error: could not save file " +view->file_path.string()+"\n");
}
DEBUG("end false");
return false;
}
bool Notebook::save_current() {
if(get_current_page()==-1)
return false;
return save(get_current_page(), true);
}
bool Notebook::close_current_page() {
DEBUG("start");
if (get_current_page()!=-1) {
if(get_current_view()->get_buffer()->get_modified()){
if(!save_modified_dialog()) {
DEBUG("end false");
return false;
}
}
int page = get_current_page();
int index=get_index(page);
remove_page(page);
auto source_view=source_views.at(index);
if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view))
source_clang_view->async_delete();
else
delete source_view;
source_views.erase(source_views.begin()+index);
scrolled_windows.erase(scrolled_windows.begin()+index);
hboxes.erase(hboxes.begin()+index);
}
DEBUG("end true");
return true;
}
bool Notebook::save_modified_dialog() {
Gtk::MessageDialog dialog((Gtk::Window&)(*get_toplevel()), "Save file!", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO);
dialog.set_default_response(Gtk::RESPONSE_YES);
dialog.set_secondary_text("Do you want to save: " + get_current_view()->file_path.string()+" ?");
int result = dialog.run();
if(result==Gtk::RESPONSE_YES) {
save_current();
return true;
}
else if(result==Gtk::RESPONSE_NO) {
return true;
}
else {
return false;
}
}
<|endoftext|>
|
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: representation.C,v 1.31 2004/04/18 17:15:47 amoll Exp $
#include <BALL/VIEW/KERNEL/representation.h>
#include <BALL/VIEW/MODELS/modelProcessor.h>
#include <BALL/VIEW/MODELS/colorProcessor.h>
#include <BALL/VIEW/KERNEL/geometricObject.h>
#include <BALL/VIEW/KERNEL/threads.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/KERNEL/atom.h>
#include <qapplication.h>
namespace BALL
{
namespace VIEW
{
#ifdef BALL_QT_HAS_THREADS
UpdateRepresentationThread* Representation::thread_ = 0;
#endif
Representation::Representation()
throw()
: PropertyManager(),
drawing_mode_(DRAWING_MODE_SOLID),
drawing_precision_(DRAWING_PRECISION_HIGH),
surface_drawing_precision_(-1),
model_type_(MODEL_UNKNOWN),
coloring_method_(COLORING_UNKNOWN),
transparency_(0),
model_processor_(0),
color_processor_(0),
geometric_objects_(),
composites_()
{
}
Representation::Representation(const Representation& rp)
throw()
: PropertyManager(rp)
{
*this = rp;
}
Representation::Representation(ModelType model_type,
DrawingPrecision drawing_precision,
DrawingMode drawing_mode)
throw()
: PropertyManager(),
drawing_mode_(drawing_mode),
drawing_precision_(drawing_precision),
surface_drawing_precision_(-1),
model_type_(model_type),
transparency_(0),
model_processor_(0),
color_processor_(0),
geometric_objects_(),
composites_()
{
}
Representation::Representation(const HashSet<const Composite*>& composites,
ModelProcessor* model_processor)
throw()
: PropertyManager(),
drawing_mode_(DRAWING_MODE_SOLID),
drawing_precision_(DRAWING_PRECISION_HIGH),
surface_drawing_precision_(-1),
transparency_(0),
model_processor_(model_processor),
color_processor_(0),
geometric_objects_(),
composites_(composites)
{
}
const Representation& Representation::operator = (const Representation& representation)
throw()
{
clear();
drawing_mode_= representation.drawing_mode_;
drawing_precision_= representation.drawing_precision_;
model_type_ = representation.model_type_;
coloring_method_ = representation.coloring_method_;
transparency_ = representation.transparency_;
surface_drawing_precision_ = representation.surface_drawing_precision_;
PropertyManager::operator = (representation);
if (representation.model_processor_ != 0)
{
model_processor_ = new ModelProcessor(*representation.model_processor_);
}
else
{
model_processor_ = 0;
}
if (representation.color_processor_ != 0)
{
color_processor_ = new ColorProcessor(*representation.color_processor_);
color_processor_->setTransparency(transparency_);
}
else
{
color_processor_ = 0;
}
GeometricObjectList::ConstIterator it = representation.geometric_objects_.begin();
for (;it != representation.geometric_objects_.end(); it++)
{
GeometricObject* object = new GeometricObject(**it);
geometric_objects_.push_back(object);
}
composites_ = representation.composites_;
return *this;
}
Representation::~Representation()
throw()
{
clear();
}
void Representation::clear()
throw()
{
clearGeometricObjects();
composites_.clear();
if (model_processor_ != 0) delete model_processor_;
if (color_processor_ != 0) delete color_processor_;
model_processor_ = 0;
color_processor_ = 0;
drawing_mode_= DRAWING_MODE_SOLID;
drawing_precision_= DRAWING_PRECISION_HIGH;
model_type_ = MODEL_UNKNOWN;
coloring_method_ = COLORING_UNKNOWN;
transparency_ = 0;
surface_drawing_precision_ = -1;
}
void Representation::clearGeometricObjects()
throw()
{
List<GeometricObject*>::Iterator it = geometric_objects_.begin();
for (; it != geometric_objects_.end(); it++)
{
delete *it;
}
geometric_objects_.clear();
if (model_processor_ != 0)
{
model_processor_->getGeometricObjects().clear();
}
}
void Representation::dump(std::ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
BALL_DUMP_DEPTH(s, depth);
s << "drawing mode: " << drawing_mode_<< std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "drawing precision: " << drawing_precision_<< std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "model type : " << model_type_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "coloring type : " << coloring_method_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "number of primitives: " << geometric_objects_.size() << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "number of composites: " << composites_.size() << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "model processor: " << model_processor_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "PropertyManager: " << std::endl;
PropertyManager::dump(s, depth + 1);
BALL_DUMP_STREAM_SUFFIX(s);
}
bool Representation::isValid() const
throw()
{
if (drawing_precision_ < 0 || drawing_precision_ > BALL_VIEW_MAXIMAL_DRAWING_PRECISION ||
drawing_mode_ < 0 || drawing_mode_ > BALL_VIEW_MAXIMAL_DRAWING_MODE ||
transparency_ > 255)
{
return false;
}
#ifdef BALL_VIEW_DEBUG
GeometricObjectList::ConstIterator it = geometric_objects_.begin();
for (; it != geometric_objects_.end(); it++)
{
if (!(*it)->isValid()) return false;
}
#endif
if (model_processor_ != 0 && !model_processor_->isValid()) return false;
return true;
}
void Representation::update(bool rebuild)
throw()
{
// no need to update hidden representations
if (hasProperty(PROPERTY__HIDDEN))
{
needs_update_ = true;
return;
}
else
{
needs_update_ = false;
}
#ifndef BALL_QT_HAS_THREADS
update_(rebuild);
#else
MainControl* mc = MainControl::getInstance(0);
// ????? dirty trick to avoid getInstance problem under windows
#ifdef BALL_PLATFORM_WINDOWS
mc = dynamic_cast<MainControl*>(qApp->mainWidget());
#endif
if (mc == 0)
{
update_(rebuild);
return;
}
if (thread_ != 0)
{
thread_->wait();
delete thread_;
thread_ = 0;
}
thread_ = new UpdateRepresentationThread;
thread_->setRepresentation(*this);
thread_->setRebuild(rebuild);
thread_->start();
//bool mc_was_muteable = mc->compositesAreMuteable();
mc->setCompositesMuteable(false);
Position pos = 3;
String dots;
while (thread_->running())
{
qApp->wakeUpGuiThread();
qApp->processEvents();
if (pos < 40)
{
pos ++;
dots +="..";
}
else
{
pos = 3;
dots = "...";
}
mc->setStatusbarText("Creating " + getModelName() + " Model " + dots);
thread_->wait(500);
}
mc->setStatusbarText("");
mc->setCompositesMuteable(true);
if (mc->getPrimitiveManager().has(*this))
{
RepresentationMessage* msg = new RepresentationMessage(*this, RepresentationMessage::UPDATE);
mc->sendMessage(*msg);
return;
}
mc->insert(*this);
mc->setStatusbarText("");
#endif
}
void Representation::update_(bool rebuild)
throw()
{
// if no ModelProcessor was given, there can only exist
// handmade GeometricObjects, which dont need to be updated
if (model_processor_ != 0 && rebuild)
{
clearGeometricObjects();
model_processor_->getGeometricObjects().clear();
model_processor_->clearComposites();
CompositeSet::Iterator it = composites_.begin();
for (; it!= composites_.end(); it++)
{
(const_cast<Composite*>(*it))->apply(*model_processor_);
}
geometric_objects_ = model_processor_->getGeometricObjects();
model_build_time_ = PreciseTime::now();
}
if (color_processor_ != 0)
{
// make sure, that the atom grid is recomputed for meshes
if (rebuild) color_processor_->setComposites(&composites_);
color_processor_->setTransparency(transparency_);
color_processor_->setModelType(model_type_);
geometric_objects_.apply(*color_processor_);
}
}
String Representation::getModelName() const
throw()
{
return VIEW::getModelName(model_type_);
}
String Representation::getColoringName() const
throw()
{
return VIEW::getColoringName(coloring_method_);
}
String Representation::getProperties() const
throw()
{
return String(composites_.size()) + " C, " + String(geometric_objects_.size()) + " P";
}
void Representation::setModelProcessor(ModelProcessor* processor)
throw()
{
if (model_processor_ != 0)
{
delete model_processor_;
}
model_processor_ = processor;
if (model_processor_ != 0)
{
model_processor_->setDrawingPrecision(drawing_precision_);
model_processor_->setSurfaceDrawingPrecision(surface_drawing_precision_);
}
}
void Representation::setColorProcessor(ColorProcessor* processor)
throw()
{
if (color_processor_ != 0)
{
delete color_processor_;
}
color_processor_ = processor;
if (color_processor_ != 0)
{
color_processor_->setComposites(&composites_);
color_processor_->setTransparency(transparency_);
}
}
void Representation::setDrawingPrecision(DrawingPrecision precision)
throw()
{
drawing_precision_ = precision;
if (model_processor_ != 0) model_processor_->setDrawingPrecision(drawing_precision_);
}
void Representation::setSurfaceDrawingPrecision(float precision)
throw()
{
surface_drawing_precision_ = precision;
if (model_processor_ != 0) model_processor_->setSurfaceDrawingPrecision(surface_drawing_precision_);
}
void Representation::setTransparency(Size value)
throw()
{
transparency_ = value;
if (transparency_ > 255)
{
transparency_ = 255;
}
if (color_processor_ != 0)
{
color_processor_->setTransparency(transparency_);
}
}
bool Representation::needsUpdate() const
throw()
{
if (needs_update_ ||
getModelBuildTime() < Atom::getAttributesModificationTime())
{
return true;
}
CompositeSet::ConstIterator it = composites_.begin();
for (;it != composites_.end(); it++)
{
if (getModelBuildTime() < (*it)->getModificationTime()) return true;
}
return false;
}
} // namespace VIEW
} // namespace BALL
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: representation.C,v 1.32 2004/04/18 18:12:24 amoll Exp $
#include <BALL/VIEW/KERNEL/representation.h>
#include <BALL/VIEW/MODELS/modelProcessor.h>
#include <BALL/VIEW/MODELS/colorProcessor.h>
#include <BALL/VIEW/KERNEL/geometricObject.h>
#include <BALL/VIEW/KERNEL/threads.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/KERNEL/atom.h>
#include <qapplication.h>
namespace BALL
{
namespace VIEW
{
#ifdef BALL_QT_HAS_THREADS
UpdateRepresentationThread* Representation::thread_ = 0;
#endif
Representation::Representation()
throw()
: PropertyManager(),
drawing_mode_(DRAWING_MODE_SOLID),
drawing_precision_(DRAWING_PRECISION_HIGH),
surface_drawing_precision_(-1),
model_type_(MODEL_UNKNOWN),
coloring_method_(COLORING_UNKNOWN),
transparency_(0),
model_processor_(0),
color_processor_(0),
geometric_objects_(),
composites_()
{
}
Representation::Representation(const Representation& rp)
throw()
: PropertyManager(rp)
{
*this = rp;
}
Representation::Representation(ModelType model_type,
DrawingPrecision drawing_precision,
DrawingMode drawing_mode)
throw()
: PropertyManager(),
drawing_mode_(drawing_mode),
drawing_precision_(drawing_precision),
surface_drawing_precision_(-1),
model_type_(model_type),
transparency_(0),
model_processor_(0),
color_processor_(0),
geometric_objects_(),
composites_()
{
}
Representation::Representation(const HashSet<const Composite*>& composites,
ModelProcessor* model_processor)
throw()
: PropertyManager(),
drawing_mode_(DRAWING_MODE_SOLID),
drawing_precision_(DRAWING_PRECISION_HIGH),
surface_drawing_precision_(-1),
transparency_(0),
model_processor_(model_processor),
color_processor_(0),
geometric_objects_(),
composites_(composites)
{
}
const Representation& Representation::operator = (const Representation& representation)
throw()
{
clear();
drawing_mode_= representation.drawing_mode_;
drawing_precision_= representation.drawing_precision_;
model_type_ = representation.model_type_;
coloring_method_ = representation.coloring_method_;
transparency_ = representation.transparency_;
surface_drawing_precision_ = representation.surface_drawing_precision_;
PropertyManager::operator = (representation);
if (representation.model_processor_ != 0)
{
model_processor_ = new ModelProcessor(*representation.model_processor_);
}
else
{
model_processor_ = 0;
}
if (representation.color_processor_ != 0)
{
color_processor_ = new ColorProcessor(*representation.color_processor_);
color_processor_->setTransparency(transparency_);
}
else
{
color_processor_ = 0;
}
GeometricObjectList::ConstIterator it = representation.geometric_objects_.begin();
for (;it != representation.geometric_objects_.end(); it++)
{
GeometricObject* object = new GeometricObject(**it);
geometric_objects_.push_back(object);
}
composites_ = representation.composites_;
return *this;
}
Representation::~Representation()
throw()
{
clear();
}
void Representation::clear()
throw()
{
clearGeometricObjects();
composites_.clear();
if (model_processor_ != 0) delete model_processor_;
if (color_processor_ != 0) delete color_processor_;
model_processor_ = 0;
color_processor_ = 0;
drawing_mode_= DRAWING_MODE_SOLID;
drawing_precision_= DRAWING_PRECISION_HIGH;
model_type_ = MODEL_UNKNOWN;
coloring_method_ = COLORING_UNKNOWN;
transparency_ = 0;
surface_drawing_precision_ = -1;
}
void Representation::clearGeometricObjects()
throw()
{
List<GeometricObject*>::Iterator it = geometric_objects_.begin();
for (; it != geometric_objects_.end(); it++)
{
delete *it;
}
geometric_objects_.clear();
if (model_processor_ != 0)
{
model_processor_->getGeometricObjects().clear();
}
}
void Representation::dump(std::ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
BALL_DUMP_DEPTH(s, depth);
s << "drawing mode: " << drawing_mode_<< std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "drawing precision: " << drawing_precision_<< std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "model type : " << model_type_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "coloring type : " << coloring_method_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "number of primitives: " << geometric_objects_.size() << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "number of composites: " << composites_.size() << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "model processor: " << model_processor_ << std::endl;
BALL_DUMP_DEPTH(s, depth);
s << "PropertyManager: " << std::endl;
PropertyManager::dump(s, depth + 1);
BALL_DUMP_STREAM_SUFFIX(s);
}
bool Representation::isValid() const
throw()
{
if (drawing_precision_ < 0 || drawing_precision_ > BALL_VIEW_MAXIMAL_DRAWING_PRECISION ||
drawing_mode_ < 0 || drawing_mode_ > BALL_VIEW_MAXIMAL_DRAWING_MODE ||
transparency_ > 255)
{
return false;
}
#ifdef BALL_VIEW_DEBUG
GeometricObjectList::ConstIterator it = geometric_objects_.begin();
for (; it != geometric_objects_.end(); it++)
{
if (!(*it)->isValid()) return false;
}
#endif
if (model_processor_ != 0 && !model_processor_->isValid()) return false;
return true;
}
void Representation::update(bool rebuild)
throw()
{
MainControl* mc = MainControl::getInstance(0);
// ????? dirty trick to avoid getInstance problem under windows
#ifdef BALL_PLATFORM_WINDOWS
mc = dynamic_cast<MainControl*>(qApp->mainWidget());
#endif
// no need to update hidden representations
if (hasProperty(PROPERTY__HIDDEN))
{
needs_update_ = true;
// update of GeometricControl, also if Representation is hidden
RepresentationMessage* msg = new RepresentationMessage(*this, RepresentationMessage::UPDATE);
mc->sendMessage(*msg);
return;
}
else
{
needs_update_ = false;
}
#ifndef BALL_QT_HAS_THREADS
update_(rebuild);
#else
if (mc == 0)
{
update_(rebuild);
return;
}
if (thread_ != 0)
{
thread_->wait();
delete thread_;
thread_ = 0;
}
thread_ = new UpdateRepresentationThread;
thread_->setRepresentation(*this);
thread_->setRebuild(rebuild);
thread_->start();
//bool mc_was_muteable = mc->compositesAreMuteable();
mc->setCompositesMuteable(false);
Position pos = 3;
String dots;
while (thread_->running())
{
qApp->wakeUpGuiThread();
qApp->processEvents();
if (pos < 40)
{
pos ++;
dots +="..";
}
else
{
pos = 3;
dots = "...";
}
mc->setStatusbarText("Creating " + getModelName() + " Model " + dots);
thread_->wait(500);
}
mc->setStatusbarText("");
mc->setCompositesMuteable(true);
if (mc->getPrimitiveManager().has(*this))
{
RepresentationMessage* msg = new RepresentationMessage(*this, RepresentationMessage::UPDATE);
mc->sendMessage(*msg);
return;
}
mc->insert(*this);
mc->setStatusbarText("");
#endif
}
void Representation::update_(bool rebuild)
throw()
{
// if no ModelProcessor was given, there can only exist
// handmade GeometricObjects, which dont need to be updated
if (model_processor_ != 0 && rebuild)
{
clearGeometricObjects();
model_processor_->getGeometricObjects().clear();
model_processor_->clearComposites();
CompositeSet::Iterator it = composites_.begin();
for (; it!= composites_.end(); it++)
{
(const_cast<Composite*>(*it))->apply(*model_processor_);
}
geometric_objects_ = model_processor_->getGeometricObjects();
model_build_time_ = PreciseTime::now();
}
if (color_processor_ != 0)
{
// make sure, that the atom grid is recomputed for meshes
if (rebuild) color_processor_->setComposites(&composites_);
color_processor_->setTransparency(transparency_);
color_processor_->setModelType(model_type_);
geometric_objects_.apply(*color_processor_);
}
}
String Representation::getModelName() const
throw()
{
return VIEW::getModelName(model_type_);
}
String Representation::getColoringName() const
throw()
{
return VIEW::getColoringName(coloring_method_);
}
String Representation::getProperties() const
throw()
{
return String(composites_.size()) + " C, " + String(geometric_objects_.size()) + " P";
}
void Representation::setModelProcessor(ModelProcessor* processor)
throw()
{
if (model_processor_ != 0)
{
delete model_processor_;
}
model_processor_ = processor;
if (model_processor_ != 0)
{
model_processor_->setDrawingPrecision(drawing_precision_);
model_processor_->setSurfaceDrawingPrecision(surface_drawing_precision_);
}
}
void Representation::setColorProcessor(ColorProcessor* processor)
throw()
{
if (color_processor_ != 0)
{
delete color_processor_;
}
color_processor_ = processor;
if (color_processor_ != 0)
{
color_processor_->setComposites(&composites_);
color_processor_->setTransparency(transparency_);
}
}
void Representation::setDrawingPrecision(DrawingPrecision precision)
throw()
{
drawing_precision_ = precision;
if (model_processor_ != 0) model_processor_->setDrawingPrecision(drawing_precision_);
}
void Representation::setSurfaceDrawingPrecision(float precision)
throw()
{
surface_drawing_precision_ = precision;
if (model_processor_ != 0) model_processor_->setSurfaceDrawingPrecision(surface_drawing_precision_);
}
void Representation::setTransparency(Size value)
throw()
{
transparency_ = value;
if (transparency_ > 255)
{
transparency_ = 255;
}
if (color_processor_ != 0)
{
color_processor_->setTransparency(transparency_);
}
}
bool Representation::needsUpdate() const
throw()
{
if (needs_update_ ||
getModelBuildTime() < Atom::getAttributesModificationTime())
{
return true;
}
CompositeSet::ConstIterator it = composites_.begin();
for (;it != composites_.end(); it++)
{
if (getModelBuildTime() < (*it)->getModificationTime()) return true;
}
return false;
}
} // namespace VIEW
} // namespace BALL
<|endoftext|>
|
<commit_before>#include "graphics/Logger.h"
#include <spdlog/spdlog.h>
_GATHERER_GRAPHICS_BEGIN
std::shared_ptr<spdlog::logger> Logger::create(const char* name)
{
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_mt>());
#if defined(__ANDROID__)
sinks.push_back(std::make_shared<spdlog::sinks::android_sink_mt>());
#endif
auto logger = std::make_shared<spdlog::logger>(
name, begin(sinks), end(sinks)
);
spdlog::register_logger(logger);
spdlog::set_pattern("[%H:%M:%S.%e | thread:%t | %n | %l]: %v");
return logger;
}
std::shared_ptr<spdlog::logger> Logger::get(const char* name)
{
return spdlog::get(name);
}
_GATHERER_GRAPHICS_END
<commit_msg>Fix Android build<commit_after>#include "graphics/Logger.h"
#include <spdlog/spdlog.h>
#if defined(__ANDROID__)
# include <spdlog/sinks/android_sink.h>
#endif
_GATHERER_GRAPHICS_BEGIN
std::shared_ptr<spdlog::logger> Logger::create(const char* name)
{
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_mt>());
#if defined(__ANDROID__)
sinks.push_back(std::make_shared<spdlog::sinks::android_sink_mt>());
#endif
auto logger = std::make_shared<spdlog::logger>(
name, begin(sinks), end(sinks)
);
spdlog::register_logger(logger);
spdlog::set_pattern("[%H:%M:%S.%e | thread:%t | %n | %l]: %v");
return logger;
}
std::shared_ptr<spdlog::logger> Logger::get(const char* name)
{
return spdlog::get(name);
}
_GATHERER_GRAPHICS_END
<|endoftext|>
|
<commit_before>#pragma once
#include "seq.hpp"
#include "util.hpp"
#include "value.hpp"
#include <memory>
namespace imu {
namespace ty {
template<typename Value = value, typename mixin = no_mixin>
struct basic_list {
typedef std::shared_ptr<basic_list> p;
// the type store in this list. by default this is
// a generic type that can store any value
typedef Value value_type;
// a mixin can extra hold user data in this type
mixin _mixin;
uint64_t _count;
value_type _first;
p _rest;
inline basic_list()
: _count(0)
{}
template<typename T>
inline basic_list(const T& v, const p& l = p())
: _count(l ? l->_count + 1 : 1)
, _first(v)
, _rest(l)
{}
inline bool is_empty() const {
return _count == 0;
}
inline uint64_t count() const {
return _count;
}
template<typename T>
inline const T& first() const {
return value_cast<T>(_first);
};
inline const value_type& first() const {
return _first;
};
inline p rest() const {
return _rest;
}
template<typename S>
inline friend bool operator== (
const p& self, const std::shared_ptr<S>& x) {
return seqs::equiv(self, x);
}
};
typedef basic_list<> list;
}
inline ty::list::p list() {
return ty::list::p();
}
template<typename Val, typename... Vals>
inline ty::list::p list(const Val& val, Vals... vals) {
return nu<ty::list>(val, list(vals...));
}
/**
* @namespace fxd
* @brief Functions in this namespace create sequences
* with a fixed type.
*
*/
namespace fxd {
template<typename T>
inline typename ty::basic_list<T>::p list() {
return typename ty::basic_list<T>::p();
}
template<typename Val, typename... Vals>
inline typename ty::basic_list<Val>::p
list(const Val& val, Vals... vals) {
return nu<ty::basic_list<Val>>(val, list<Val>(vals...));
}
}
template<typename T>
inline ty::list::p list(std::initializer_list<T> l) {
auto out = nu<ty::list>();
for (auto& val : l) {
out = nu<ty::list>(val, out);
}
return out;
}
// @cond HIDE
template<typename T, typename X>
inline typename ty::basic_list<T>::p
conj(const std::shared_ptr<ty::basic_list<T>>& l, const X& v) {
return nu<ty::basic_list<T>>(v, l);
}
// @endcond
}
<commit_msg>Allow construnctionof lists from STL containers<commit_after>#pragma once
#include "seq.hpp"
#include "util.hpp"
#include "value.hpp"
#include <memory>
namespace imu {
namespace ty {
template<typename Value = value, typename mixin = no_mixin>
struct basic_list : public mixin {
typedef std::shared_ptr<basic_list> p;
// the type store in this list. by default this is
// a generic type that can store any value
typedef Value value_type;
uint64_t _count;
value_type _first;
p _rest;
inline basic_list()
: _count(0)
{}
template<typename T>
inline basic_list(const T& v, const p& l = p())
: _count(l ? l->_count + 1 : 1)
, _first(v)
, _rest(l)
{}
static inline p factory() {
return p();
}
template<typename Val, typename... Vals>
static inline p factory(const Val& val, Vals... vals) {
return nu<basic_list>(val, factory(vals...));
}
template<typename T>
static inline p from_std(const T& coll) {
auto out = nu<basic_list>();
for (auto& val : coll) {
out = nu<basic_list>(val, out);
}
return out;
}
inline bool is_empty() const {
return _count == 0;
}
inline uint64_t count() const {
return _count;
}
template<typename T>
inline const T& first() const {
return value_cast<T>(_first);
};
inline const value_type& first() const {
return _first;
};
inline p rest() const {
return _rest;
}
template<typename S>
inline friend bool operator== (
const p& self, const std::shared_ptr<S>& x) {
return seqs::equiv(self, x);
}
};
typedef basic_list<> list;
}
inline ty::list::p list() {
return ty::list::factory();
}
template<typename Val, typename... Vals>
inline ty::list::p list(const Val& val, Vals... vals) {
return ty::list::factory(val, vals...);
}
template<typename T>
inline auto list(const T& coll)
-> decltype(std::begin(coll), std::end(coll), ty::list::p()) {
return ty::list::from_std(coll);
}
template<typename T>
inline ty::list::p list(std::initializer_list<T> l) {
return ty::list::from_std(l);
}
/**
* @namespace fxd
* @brief Functions in this namespace create sequences
* with a fixed type.
*
*/
namespace fxd {
template<typename T>
inline typename ty::basic_list<T>::p list() {
return typename ty::basic_list<T>::p();
}
template<typename Val, typename... Vals>
inline typename ty::basic_list<Val>::p
list(const Val& val, Vals... vals) {
return nu<ty::basic_list<Val>>(val, list<Val>(vals...));
}
}
// @cond HIDE
template<typename X, typename... T>
inline typename ty::basic_list<T...>::p
conj(const typename ty::basic_list<T...>::p& l, const X& v) {
return nu<ty::basic_list<T...>>(v, l);
}
// @endcond
}
<|endoftext|>
|
<commit_before>Bool_t ConfigKstarLeading(
AliRsnMiniAnalysisTask *task,
Bool_t isMC = kFALSE,
Bool_t isPP = kFALSE,
Double_t nSigmaPart1TPC = -1,
Double_t nSigmaPart2TPC = -1,
Double_t nSigmaPart1TOF = -1,
Double_t nSigmaPart2TOF = -1,
Int_t customQualityCutsID=AliRsnCutSetDaughterParticle::kDisableCustom,
Int_t aodFilterBit=0
)
{
// -- Values ------------------------------------------------------------------------------------
/* invariant mass */ Int_t imID = task->CreateValue(AliRsnMiniValue::kInvMass, kFALSE);
/* transv. momentum */ Int_t ptID = task->CreateValue(AliRsnMiniValue::kPt, kFALSE);
/* angel to leading */ Int_t alID = task->CreateValue(AliRsnMiniValue::kAngleLeading, kFALSE);
/* pt of leading */ Int_t ptlID = task->CreateValue(AliRsnMiniValue::kLeadingPt, kFALSE);
/* multiplicity */ Int_t multID = task->CreateValue(AliRsnMiniValue::kMult,kFALSE);
/* delta eta */ Int_t detaID = task->CreateValue(AliRsnMiniValue::kDeltaEta, kFALSE);
/* phi of leading */ Int_t philID = task->CreateValue(AliRsnMiniValue::kLeadingPhi, kFALSE);
/* phi angle */ Int_t phiID = task->CreateValue(AliRsnMiniValue::kPhi, kFALSE);
// set daughter cuts
AliRsnCutSetDaughterParticle* cutSetPi;
AliRsnCutSetDaughterParticle* cutSetK;
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s;
AliRsnCutTrackQuality* trkQualityCut= new AliRsnCutTrackQuality("myQualityCut");
trkQualityCut->SetDefaults2011(kTRUE,kTRUE);
cout<<"Value of custom quality--------------------"<<customQualityCutsID<<endl;
if(customQualityCutsID==3){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.0150+0.0500/pt^1.1");}
else if(customQualityCutsID==4){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.006+0.0200/pt^1.1");}
else if(customQualityCutsID==5){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(3.);}
else if(customQualityCutsID==6){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(0.2);}
else if(customQualityCutsID==7){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(5.);}
else if(customQualityCutsID==8){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(3.);}
else if(customQualityCutsID==9){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(60);}
else if(customQualityCutsID==10){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(100);}
else if(customQualityCutsID==11){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.7);}
else if(customQualityCutsID==12){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.9);}
else if(customQualityCutsID==13){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(49.);}
else if(customQualityCutsID==14){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(4.);}
else if(customQualityCutsID==15){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(49.);}
else if(customQualityCutsID==16){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(25.);}
else if(customQualityCutsID==17){trkQualityCut->GetESDtrackCuts()->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kOff);}
else if(customQualityCutsID==56){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(1.);}
else if(customQualityCutsID==60){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(80);}
else if(customQualityCutsID==64){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(25.);}
cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigmaTPC_%2.1fsigmaTOF",cutPiCandidate,nSigmaPart1TPC,nSigmaPart1TOF),trkQualityCut,cutPiCandidate,AliPID::kPion,nSigmaPart1TPC,nSigmaPart1TOF);
cutSetK=new AliRsnCutSetDaughterParticle(Form("cutK%i_%2.1fsigma_%2.1fsigmaTOF",cutPiCandidate, nSigmaPart2TPC,nSigmaPart2TOF),trkQualityCut,cutPiCandidate,AliPID::kKaon,nSigmaPart2TPC,nSigmaPart2TOF);
Int_t iCutPi = task->AddTrackCuts(cutSetPi);
Int_t iCutK = task->AddTrackCuts(cutSetK);
// Defining output objects
const Int_t dims = 8;
Int_t useIM[dims] = { 1, 1, 1, 1, 0, 0, isMC, isMC};
TString name[dims] = { "UnlikePM", "UnlikeMP", "MixingPM", "MixingMP", "LikePP", "LikeMM", "True", "Mother"};
TString comp[dims] = { "PAIR", "PAIR", "MIX", "MIX", "PAIR", "PAIR", "TRUE", "MOTHER"};
TString output[dims] = { "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE"};
Char_t charge1[dims] = { '+', '-', '+', '-', '+', '-', '+', '+'};
Char_t charge2[dims] = { '-', '+', '-', '+', '+', '-', '-', '-'};
Int_t pdgCode[dims] = { 313, 313, 313, 313, 313, 313, 313, 313};
Double_t motherMass[dims] = { 0.896, 0.896, 0.896, 0.896, 0.896, 0.896, 0.896, 0.896};
for (Int_t i = 0; i < dims; i++)
{
if (!useIM[i])
continue;
AliRsnMiniOutput *out = task->CreateOutput(name[i].Data(), output[i].Data(), comp[i].Data());
out->SetCutID(0, iCutK);
out->SetCutID(1, iCutPi);
out->SetDaughter(0, AliRsnDaughter::kKaon);
out->SetDaughter(1, AliRsnDaughter::kPion);
out->SetCharge(0, charge1[i]);
out->SetCharge(1, charge2[i]);
out->SetMotherPDG(pdgCode[i]);
out->SetMotherMass(motherMass[i]);
out->AddAxis(imID, 85, 0.77, 1.20);
out->AddAxis(ptID, 10, 0., 10.);
if(!isPP ) out->AddAxis(multID,10,0.,100.);
else out->AddAxis(multID, 10, 0., 100.);
out->AddAxis(alID, 36, -0.5 * TMath::Pi(), 1.5 * TMath::Pi());
out->AddAxis(ptlID, 15, 0., 30.);
out->AddAxis(detaID, 16, -1.6, 1.6);
// out->AddAxis(philID, 18, -0.5 * TMath::Pi(), 1.5 * TMath::Pi());
// out->AddAxis(phiID, 18, -0.5 * TMath::Pi(), 1.5 * TMath::Pi());
}
return kTRUE;
}
<commit_msg>Update ConfigKstarLeading.C<commit_after>Bool_t ConfigKstarLeading(
AliRsnMiniAnalysisTask *task,
Bool_t isMC = kFALSE,
Bool_t isPP = kFALSE,
Double_t nSigmaPart1TPC = -1,
Double_t nSigmaPart2TPC = -1,
Double_t nSigmaPart1TOF = -1,
Double_t nSigmaPart2TOF = -1,
Int_t customQualityCutsID=AliRsnCutSetDaughterParticle::kDisableCustom,
Int_t aodFilterBit=0
)
{
// -- Values ------------------------------------------------------------------------------------
/* invariant mass */ Int_t imID = task->CreateValue(AliRsnMiniValue::kInvMass, kFALSE);
/* transv. momentum */ Int_t ptID = task->CreateValue(AliRsnMiniValue::kPt, kFALSE);
/* angel to leading */ Int_t alID = task->CreateValue(AliRsnMiniValue::kAngleLeading, kFALSE);
/* pt of leading */ Int_t ptlID = task->CreateValue(AliRsnMiniValue::kLeadingPt, kFALSE);
/* multiplicity */ Int_t multID = task->CreateValue(AliRsnMiniValue::kMult,kFALSE);
/* delta eta */ Int_t detaID = task->CreateValue(AliRsnMiniValue::kDeltaEta, kFALSE);
/* phi of leading */ Int_t philID = task->CreateValue(AliRsnMiniValue::kLeadingPhi, kFALSE);
/* phi angle */ Int_t phiID = task->CreateValue(AliRsnMiniValue::kPhi, kFALSE);
// set daughter cuts
AliRsnCutSetDaughterParticle* cutSetPi;
AliRsnCutSetDaughterParticle* cutSetK;
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s;
AliRsnCutTrackQuality* trkQualityCut= new AliRsnCutTrackQuality("myQualityCut");
trkQualityCut->SetDefaults2011(kTRUE,kTRUE);
cout<<"Value of custom quality--------------------"<<customQualityCutsID<<endl;
if(customQualityCutsID==3){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.0150+0.0500/pt^1.1");}
else if(customQualityCutsID==4){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.006+0.0200/pt^1.1");}
else if(customQualityCutsID==5){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(3.);}
else if(customQualityCutsID==6){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(0.2);}
else if(customQualityCutsID==7){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(5.);}
else if(customQualityCutsID==8){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(3.);}
else if(customQualityCutsID==9){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(60);}
else if(customQualityCutsID==10){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(100);}
else if(customQualityCutsID==11){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.7);}
else if(customQualityCutsID==12){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.9);}
else if(customQualityCutsID==13){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(49.);}
else if(customQualityCutsID==14){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(4.);}
else if(customQualityCutsID==15){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(49.);}
else if(customQualityCutsID==16){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(25.);}
else if(customQualityCutsID==17){trkQualityCut->GetESDtrackCuts()->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kOff);}
else if(customQualityCutsID==56){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(1.);}
else if(customQualityCutsID==60){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(80);}
else if(customQualityCutsID==64){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(25.);}
cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigmaTPC_%2.1fsigmaTOF",cutPiCandidate,nSigmaPart1TPC,nSigmaPart1TOF),trkQualityCut,cutPiCandidate,AliPID::kPion,nSigmaPart1TPC,nSigmaPart1TOF);
cutSetK=new AliRsnCutSetDaughterParticle(Form("cutK%i_%2.1fsigma_%2.1fsigmaTOF",cutPiCandidate, nSigmaPart2TPC,nSigmaPart2TOF),trkQualityCut,cutPiCandidate,AliPID::kKaon,nSigmaPart2TPC,nSigmaPart2TOF);
Int_t iCutPi = task->AddTrackCuts(cutSetPi);
Int_t iCutK = task->AddTrackCuts(cutSetK);
// Defining output objects
const Int_t dims = 8;
Int_t useIM[dims] = { 1, 1, 1, 1, 0, 0, isMC, isMC};
TString name[dims] = { "UnlikePM", "UnlikeMP", "MixingPM", "MixingMP", "LikePP", "LikeMM", "True", "Mother"};
TString comp[dims] = { "PAIR", "PAIR", "MIX", "MIX", "PAIR", "PAIR", "TRUE", "MOTHER"};
TString output[dims] = { "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE"};
Char_t charge1[dims] = { '+', '-', '+', '-', '+', '-', '+', '+'};
Char_t charge2[dims] = { '-', '+', '-', '+', '+', '-', '-', '-'};
Int_t pdgCode[dims] = { 313, 313, 313, 313, 313, 313, 313, 313};
Double_t motherMass[dims] = { 0.896, 0.896, 0.896, 0.896, 0.896, 0.896, 0.896, 0.896};
for (Int_t i = 0; i < dims; i++)
{
if (!useIM[i])
continue;
AliRsnMiniOutput *out = task->CreateOutput(name[i].Data(), output[i].Data(), comp[i].Data());
out->SetCutID(0, iCutK);
out->SetCutID(1, iCutPi);
out->SetDaughter(0, AliRsnDaughter::kKaon);
out->SetDaughter(1, AliRsnDaughter::kPion);
out->SetCharge(0, charge1[i]);
out->SetCharge(1, charge2[i]);
out->SetMotherPDG(pdgCode[i]);
out->SetMotherMass(motherMass[i]);
out->AddAxis(imID, 85, 0.77, 1.20);
out->AddAxis(ptID, 8, 2., 10.);
if(!isPP ) out->AddAxis(multID,10,0.,100.);
else out->AddAxis(multID, 10, 0., 100.);
out->AddAxis(alID, 36, -0.5 * TMath::Pi(), 1.5 * TMath::Pi());
out->AddAxis(ptlID, 13, 4., 30.);
out->AddAxis(detaID, 16, -1.6, 1.6);
// out->AddAxis(philID, 18, -0.5 * TMath::Pi(), 1.5 * TMath::Pi());
// out->AddAxis(phiID, 18, -0.5 * TMath::Pi(), 1.5 * TMath::Pi());
}
return kTRUE;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011, Tim Branyen @tbranyen <[email protected]>
* @author Michael Robinson @codeofinterest <[email protected]>
*
* Dual licensed under the MIT and GPL licenses.
*/
#include <v8.h>
#include <node.h>
#include <string>
#include "../vendor/libgit2/include/git2.h"
#include "../include/repo.h"
#include "../include/reference.h"
#include "../include/oid.h"
#include "../include/error.h"
#include "../include/functions/string.h"
using namespace v8;
using namespace node;
void GitReference::Initialize(Handle<Object> target) {
HandleScope scope;
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(String::NewSymbol("Reference"));
NODE_SET_PROTOTYPE_METHOD(tpl, "oid", Oid);
NODE_SET_PROTOTYPE_METHOD(tpl, "lookup", Lookup);
constructor_template = Persistent<Function>::New(tpl->GetFunction());
target->Set(String::NewSymbol("Reference"), constructor_template);
}
git_reference* GitReference::GetValue() {
return this->ref;
}
void GitReference::SetValue(git_reference *ref) {
this->ref = ref;
}
Handle<Value> GitReference::New(const Arguments& args) {
HandleScope scope;
GitReference *ref = new GitReference();
ref->Wrap(args.This());
return args.This();
}
Handle<Value> GitReference::Oid(const Arguments& args) {
HandleScope scope;
if(args.Length() == 0 || !args[0]->IsFunction()) {
return ThrowException(Exception::Error(String::New("Callback is required and must be a Function.")));
}
OidBaton *baton = new OidBaton;
baton->request.data = baton;
baton->error = NULL;
baton->rawOid = NULL;
baton->rawRef = ObjectWrap::Unwrap<GitReference>(args.This())->GetValue();
baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[0]));
uv_queue_work(uv_default_loop(), &baton->request, OidWork, (uv_after_work_cb)OidAfterWork);
return Undefined();
}
void GitReference::OidWork(uv_work_t* req) {
OidBaton *baton = static_cast<OidBaton *>(req->data);
git_ref_t referenceType = git_reference_type(baton->rawRef);
if (referenceType == GIT_REF_INVALID) {
printf("invalid\n");
giterr_set_str(GITERR_INVALID, "Invalid reference type");
baton->error = giterr_last();
return;
}
if (referenceType == GIT_REF_SYMBOLIC) {
printf("symbolic\n");
int returnCode = git_reference_resolve(&baton->rawRef, baton->rawRef);
if (returnCode != GIT_OK) {
baton->error = giterr_last();
return;
}
}
baton->rawOid = git_reference_target(baton->rawRef);
}
void GitReference::OidAfterWork(uv_work_t* req) {
HandleScope scope;
OidBaton *baton = static_cast<OidBaton *>(req->data);
if (baton->error) {
Local<Value> argv[1] = {
GitError::WrapError(baton->error)
};
TryCatch try_catch;
baton->callback->Call(Context::GetCurrent()->Global(), 1, argv);
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
} else {
Handle<Object> oid = GitOid::constructor_template->NewInstance();
GitOid *oidInstance = ObjectWrap::Unwrap<GitOid>(oid);
oidInstance->SetValue(*const_cast<git_oid *>(baton->rawOid));
Handle<Value> argv[2] = {
Local<Value>::New(Null()),
oid
};
TryCatch try_catch;
baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
}
delete req;
}
Handle<Value> GitReference::Lookup(const Arguments& args) {
HandleScope scope;
if(args.Length() == 0 || !args[0]->IsObject()) {
return ThrowException(Exception::Error(String::New("Repo is required and must be a Object.")));
}
if(args.Length() == 1 || !args[1]->IsString()) {
return ThrowException(Exception::Error(String::New("Name is required and must be a String.")));
}
if(args.Length() == 2 || !args[2]->IsFunction()) {
return ThrowException(Exception::Error(String::New("Callback is required and must be a Function.")));
}
LookupBaton *baton = new LookupBaton;
baton->request.data = baton;
baton->ref = ObjectWrap::Unwrap<GitReference>(args.This());
baton->ref->Ref();
baton->error = NULL;
baton->rawRepo = ObjectWrap::Unwrap<GitRepo>(args[0]->ToObject())->GetValue();
baton->name = stringArgToString(args[1]->ToString());
baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[2]));
uv_queue_work(uv_default_loop(), &baton->request, LookupWork, (uv_after_work_cb)LookupAfterWork);
return Undefined();
}
void GitReference::LookupWork(uv_work_t *req) {
LookupBaton *baton = static_cast<LookupBaton *>(req->data);
baton->rawRef = NULL;
int returnCode = git_reference_lookup(&baton->rawRef, baton->rawRepo, baton->name.c_str());
if (returnCode != GIT_OK) {
baton->error = giterr_last();
}
}
void GitReference::LookupAfterWork(uv_work_t *req) {
HandleScope scope;
LookupBaton *baton = static_cast<LookupBaton *>(req->data);
if (baton->error) {
Local<Value> argv[1] = {
GitError::WrapError(baton->error)
};
TryCatch try_catch;
baton->callback->Call(Context::GetCurrent()->Global(), 1, argv);
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
} else {
baton->ref->SetValue(baton->rawRef);
Handle<Value> argv[2] = {
Local<Value>::New(Null()),
baton->ref->handle_
};
TryCatch try_catch;
baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
}
baton->ref->Unref();
delete req;
}
Persistent<Function> GitReference::constructor_template;
<commit_msg>Removed debug lines<commit_after>/*
* Copyright 2011, Tim Branyen @tbranyen <[email protected]>
* @author Michael Robinson @codeofinterest <[email protected]>
*
* Dual licensed under the MIT and GPL licenses.
*/
#include <v8.h>
#include <node.h>
#include <string>
#include "../vendor/libgit2/include/git2.h"
#include "../include/repo.h"
#include "../include/reference.h"
#include "../include/oid.h"
#include "../include/error.h"
#include "../include/functions/string.h"
using namespace v8;
using namespace node;
void GitReference::Initialize(Handle<Object> target) {
HandleScope scope;
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(String::NewSymbol("Reference"));
NODE_SET_PROTOTYPE_METHOD(tpl, "oid", Oid);
NODE_SET_PROTOTYPE_METHOD(tpl, "lookup", Lookup);
constructor_template = Persistent<Function>::New(tpl->GetFunction());
target->Set(String::NewSymbol("Reference"), constructor_template);
}
git_reference* GitReference::GetValue() {
return this->ref;
}
void GitReference::SetValue(git_reference *ref) {
this->ref = ref;
}
Handle<Value> GitReference::New(const Arguments& args) {
HandleScope scope;
GitReference *ref = new GitReference();
ref->Wrap(args.This());
return args.This();
}
Handle<Value> GitReference::Oid(const Arguments& args) {
HandleScope scope;
if(args.Length() == 0 || !args[0]->IsFunction()) {
return ThrowException(Exception::Error(String::New("Callback is required and must be a Function.")));
}
OidBaton *baton = new OidBaton;
baton->request.data = baton;
baton->error = NULL;
baton->rawOid = NULL;
baton->rawRef = ObjectWrap::Unwrap<GitReference>(args.This())->GetValue();
baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[0]));
uv_queue_work(uv_default_loop(), &baton->request, OidWork, (uv_after_work_cb)OidAfterWork);
return Undefined();
}
void GitReference::OidWork(uv_work_t* req) {
OidBaton *baton = static_cast<OidBaton *>(req->data);
git_ref_t referenceType = git_reference_type(baton->rawRef);
if (referenceType == GIT_REF_INVALID) {
giterr_set_str(GITERR_INVALID, "Invalid reference type");
baton->error = giterr_last();
return;
}
if (referenceType == GIT_REF_SYMBOLIC) {
int returnCode = git_reference_resolve(&baton->rawRef, baton->rawRef);
if (returnCode != GIT_OK) {
baton->error = giterr_last();
return;
}
}
baton->rawOid = git_reference_target(baton->rawRef);
}
void GitReference::OidAfterWork(uv_work_t* req) {
HandleScope scope;
OidBaton *baton = static_cast<OidBaton *>(req->data);
if (baton->error) {
Local<Value> argv[1] = {
GitError::WrapError(baton->error)
};
TryCatch try_catch;
baton->callback->Call(Context::GetCurrent()->Global(), 1, argv);
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
} else {
Handle<Object> oid = GitOid::constructor_template->NewInstance();
GitOid *oidInstance = ObjectWrap::Unwrap<GitOid>(oid);
oidInstance->SetValue(*const_cast<git_oid *>(baton->rawOid));
Handle<Value> argv[2] = {
Local<Value>::New(Null()),
oid
};
TryCatch try_catch;
baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
}
delete req;
}
Handle<Value> GitReference::Lookup(const Arguments& args) {
HandleScope scope;
if(args.Length() == 0 || !args[0]->IsObject()) {
return ThrowException(Exception::Error(String::New("Repo is required and must be a Object.")));
}
if(args.Length() == 1 || !args[1]->IsString()) {
return ThrowException(Exception::Error(String::New("Name is required and must be a String.")));
}
if(args.Length() == 2 || !args[2]->IsFunction()) {
return ThrowException(Exception::Error(String::New("Callback is required and must be a Function.")));
}
LookupBaton *baton = new LookupBaton;
baton->request.data = baton;
baton->ref = ObjectWrap::Unwrap<GitReference>(args.This());
baton->ref->Ref();
baton->error = NULL;
baton->rawRepo = ObjectWrap::Unwrap<GitRepo>(args[0]->ToObject())->GetValue();
baton->name = stringArgToString(args[1]->ToString());
baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[2]));
uv_queue_work(uv_default_loop(), &baton->request, LookupWork, (uv_after_work_cb)LookupAfterWork);
return Undefined();
}
void GitReference::LookupWork(uv_work_t *req) {
LookupBaton *baton = static_cast<LookupBaton *>(req->data);
baton->rawRef = NULL;
int returnCode = git_reference_lookup(&baton->rawRef, baton->rawRepo, baton->name.c_str());
if (returnCode != GIT_OK) {
baton->error = giterr_last();
}
}
void GitReference::LookupAfterWork(uv_work_t *req) {
HandleScope scope;
LookupBaton *baton = static_cast<LookupBaton *>(req->data);
if (baton->error) {
Local<Value> argv[1] = {
GitError::WrapError(baton->error)
};
TryCatch try_catch;
baton->callback->Call(Context::GetCurrent()->Global(), 1, argv);
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
} else {
baton->ref->SetValue(baton->rawRef);
Handle<Value> argv[2] = {
Local<Value>::New(Null()),
baton->ref->handle_
};
TryCatch try_catch;
baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
}
baton->ref->Unref();
delete req;
}
Persistent<Function> GitReference::constructor_template;
<|endoftext|>
|
<commit_before>/*
* common.cpp -- Blackmagic Design DeckLink common functions
* Copyright (C) 2012 Dan Dennedy <[email protected]>
*
* 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 consumer library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "common.h"
#include <stdlib.h>
#include <unistd.h>
#ifdef __DARWIN__
char* getCString( DLString aDLString )
{
char* CString = (char*) malloc( 64 );
CFStringGetCString( aDLString, CString, 64, kCFStringEncodingMacRoman );
return CString;
}
void freeCString( char* aCString )
{
if ( aCString ) free( aCString );
}
void freeDLString( DLString aDLString )
{
if ( aDLString ) CFRelease( aDLString );
}
#elif defined(WIN32)
char* getCString( DLString aDLString )
{
char* CString = NULL;
if ( aDLString )
{
int size = WideCharToMultiByte( CP_UTF8, 0, aDLString, -1, NULL, 0, NULL, NULL );
if (size)
{
CString = new char[ size ];
size = WideCharToMultiByte( CP_UTF8, 0, aDLString, -1, CString, size, NULL, NULL );
if ( !size )
{
delete[] CString;
CString = NULL;
}
}
}
return CString;
}
void freeCString( char* aCString )
{
delete[] aCString;
}
void freeDLString( DLString aDLString )
{
if ( aDLString ) free( (void*) aDLString );
}
#else
char* getCString( DLString aDLString )
{
return aDLString? (char*) aDLString : NULL;
}
void freeCString( char* aCString )
{
}
void freeDLString( DLString aDLString )
{
if ( aDLString ) free( (void*) aDLString );
}
#endif
void swab2( const void *from, void *to, int n )
{
#if defined(USE_SSE)
#define SWAB_STEP 16
__asm__ volatile
(
"loop_start: \n\t"
/* load */
"movdqa 0(%[from]), %%xmm0 \n\t"
"add $0x10, %[from] \n\t"
/* duplicate to temp registers */
"movdqa %%xmm0, %%xmm1 \n\t"
/* shift right temp register */
"psrlw $8, %%xmm1 \n\t"
/* shift left main register */
"psllw $8, %%xmm0 \n\t"
/* compose them back */
"por %%xmm0, %%xmm1 \n\t"
/* save */
"movdqa %%xmm1, 0(%[to]) \n\t"
"add $0x10, %[to] \n\t"
"dec %[cnt] \n\t"
"jnz loop_start \n\t"
:
: [from]"r"(from), [to]"r"(to), [cnt]"r"(n / SWAB_STEP)
: "xmm0", "xmm1"
);
from = (unsigned char*) from + n - (n % SWAB_STEP);
to = (unsigned char*) to + n - (n % SWAB_STEP);
n = (n % SWAB_STEP);
#endif
swab(from, to, n);
};
<commit_msg>Fix asm compilation on some versions of gcc.<commit_after>/*
* common.cpp -- Blackmagic Design DeckLink common functions
* Copyright (C) 2012 Dan Dennedy <[email protected]>
*
* 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 consumer library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "common.h"
#include <stdlib.h>
#include <unistd.h>
#ifdef __DARWIN__
char* getCString( DLString aDLString )
{
char* CString = (char*) malloc( 64 );
CFStringGetCString( aDLString, CString, 64, kCFStringEncodingMacRoman );
return CString;
}
void freeCString( char* aCString )
{
if ( aCString ) free( aCString );
}
void freeDLString( DLString aDLString )
{
if ( aDLString ) CFRelease( aDLString );
}
#elif defined(WIN32)
char* getCString( DLString aDLString )
{
char* CString = NULL;
if ( aDLString )
{
int size = WideCharToMultiByte( CP_UTF8, 0, aDLString, -1, NULL, 0, NULL, NULL );
if (size)
{
CString = new char[ size ];
size = WideCharToMultiByte( CP_UTF8, 0, aDLString, -1, CString, size, NULL, NULL );
if ( !size )
{
delete[] CString;
CString = NULL;
}
}
}
return CString;
}
void freeCString( char* aCString )
{
delete[] aCString;
}
void freeDLString( DLString aDLString )
{
if ( aDLString ) free( (void*) aDLString );
}
#else
char* getCString( DLString aDLString )
{
return aDLString? (char*) aDLString : NULL;
}
void freeCString( char* aCString )
{
}
void freeDLString( DLString aDLString )
{
if ( aDLString ) free( (void*) aDLString );
}
#endif
void swab2( const void *from, void *to, int n )
{
#if defined(USE_SSE)
#define SWAB_STEP 16
__asm__ volatile
(
"loop_start: \n\t"
/* load */
"movdqa 0(%[from]), %%xmm0 \n\t"
"add $0x10, %[from] \n\t"
/* duplicate to temp registers */
"movdqa %%xmm0, %%xmm1 \n\t"
/* shift right temp register */
"psrlw $8, %%xmm1 \n\t"
/* shift left main register */
"psllw $8, %%xmm0 \n\t"
/* compose them back */
"por %%xmm0, %%xmm1 \n\t"
/* save */
"movdqa %%xmm1, 0(%[to]) \n\t"
"add $0x10, %[to] \n\t"
"dec %[cnt] \n\t"
"jnz loop_start \n\t"
:
: [from]"r"(from), [to]"r"(to), [cnt]"r"(n / SWAB_STEP)
//: "xmm0", "xmm1"
);
from = (unsigned char*) from + n - (n % SWAB_STEP);
to = (unsigned char*) to + n - (n % SWAB_STEP);
n = (n % SWAB_STEP);
#endif
swab(from, to, n);
};
<|endoftext|>
|
<commit_before>#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <xorg/gtest/xorg-gtest.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xfixes.h>
#include <X11/extensions/XInput2.h>
#include "barriers-common.h"
#include "xit-event.h"
#include "helpers.h"
using namespace xorg::testing::evemu;
class BarrierNotify : public BarrierTest {};
#define ASSERT_PTR_POS(x, y) \
QueryPointerPosition(dpy, &root_x, &root_y); \
ASSERT_EQ(x, root_x); \
ASSERT_EQ(y, root_y);
TEST_F(BarrierNotify, ReceivesNotifyEvents)
{
XORG_TESTCASE("Ensure that we receive BarrierNotify events\n"
"when barriers are hit.\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, 0, NULL);
XSync(dpy, False);
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1));
XISetMask(mask.mask, XI_BarrierHit);
XISelectEvents(dpy, root, &mask, 1);
free(mask.mask);
XSync(dpy, False);
dev->PlayOne(EV_REL, REL_X, -40, True);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(-40, event.ev->dx);
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_F(BarrierNotify, CorrectEventIDs)
{
XORG_TESTCASE("Ensure that barrier event IDs have correct and "
"sequential values, and that multiple chained hits "
"have the same event ID\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, 0, NULL);
XSync(dpy, False);
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1));
XISetMask(mask.mask, XI_BarrierHit);
XISetMask(mask.mask, XI_BarrierLeave);
XISelectEvents(dpy, root, &mask, 1);
free(mask.mask);
XSync(dpy, False);
/* Ensure we have a bunch of BarrierHits on our hands. */
for (int i = 0; i < 10; i++) {
dev->PlayOne(EV_REL, REL_X, -40, True);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(30, event.ev->root_y);
ASSERT_EQ(-40, event.ev->dx);
ASSERT_EQ(0, event.ev->dy);
ASSERT_EQ(1, event.ev->event_id);
}
/* Move outside the hitbox, and ensure that we
* get a BarrierNewEvent */
dev->PlayOne(EV_REL, REL_X, 20, True);
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierLeave);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(2, event.ev->event_id);
for (int i = 0; i < 10; i++) {
dev->PlayOne(EV_REL, REL_X, -40, True);
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(2, event.ev->event_id);
}
/* Ensure that we're still inside the hit box. Event ID
* should stay the same on such a minor change. */
dev->PlayOne(EV_REL, REL_X, 1, True);
for (int i = 0; i < 10; i++) {
dev->PlayOne(EV_REL, REL_X, -40, True);
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(2, event.ev->event_id);
}
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_F(BarrierNotify, BarrierReleases)
{
XORG_TESTCASE("Ensure that releasing barriers works without "
"erroring out and allows pointer movement over "
"the barrier, and that we properly get a "
"XI_BarrierPointerReleased.\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1));
XISetMask(mask.mask, XI_BarrierHit);
XISetMask(mask.mask, XI_BarrierPointerReleased);
XISetMask(mask.mask, XI_BarrierLeave);
XISelectEvents(dpy, root, &mask, 1);
free(mask.mask);
XSync(dpy, False);
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, 0, NULL);
XSync(dpy, False);
dev->PlayOne(EV_REL, REL_X, -40, True);
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(1, event.ev->event_id);
}
XIBarrierReleasePointer(dpy, VIRTUAL_CORE_POINTER_ID, barrier, 1);
XSync(dpy, False);
dev->PlayOne(EV_REL, REL_X, -40, True);
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierPointerReleased);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(1, event.ev->event_id);
}
/* Immediately afterwards, we should have a new event
* because we exited the hit box */
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierLeave);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(2, event.ev->event_id);
}
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_F(BarrierNotify, DestroyWindow)
{
XORG_TESTCASE("Create a window.\n"
"Set up a barrier using this window as drawable.\n"
"Select for barrier events.\n"
"Ensure events are received\n"
"Destroy the window.\n"
"Ensure events are not received anymore.\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
Window win = CreateWindow(dpy, root);
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, win, 20, 20, 20, 40, 0, 0, NULL);
XSync(dpy, False);
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1));
XISetMask(mask.mask, XI_BarrierHit);
XISelectEvents(dpy, win, &mask, 1);
free(mask.mask);
XSync(dpy, False);
dev->PlayOne(EV_REL, REL_X, -40, True);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(-40, event.ev->dx);
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
XDestroyWindow(dpy, win);
XSync(dpy, True);
dev->PlayOne(EV_REL, REL_X, -40, True);
double x, y;
QueryPointerPosition(dpy, &x, &y);
EXPECT_EQ(x, 20);
EXPECT_EQ(y, 30);
ASSERT_FALSE(xorg::testing::XServer::WaitForEventOfType(Display(),
GenericEvent,
xi2_opcode,
XI_BarrierHit,
500));
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_F(BarrierNotify, UnmapWindow)
{
XORG_TESTCASE("Create a window.\n"
"Set up a barrier using this window as drawable.\n"
"Select for barrier events.\n"
"Ensure events are received\n"
"Unmap the window.\n"
"Ensure events are still received.\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
Window win = CreateWindow(dpy, root);
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, win, 20, 20, 20, 40, 0, 0, NULL);
XSync(dpy, False);
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1));
XISetMask(mask.mask, XI_BarrierHit);
XISelectEvents(dpy, win, &mask, 1);
free(mask.mask);
XSync(dpy, False);
dev->PlayOne(EV_REL, REL_X, -40, True);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(-40, event.ev->dx);
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
XUnmapWindow(dpy, win);
XSync(dpy, True);
dev->PlayOne(EV_REL, REL_X, -40, True);
double x, y;
QueryPointerPosition(dpy, &x, &y);
EXPECT_EQ(x, 20);
EXPECT_EQ(y, 30);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(),
GenericEvent,
xi2_opcode,
XI_BarrierHit,
500));
XFixesDestroyPointerBarrier(dpy, barrier);
}
<commit_msg>server/barrier: add three more tests<commit_after>#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <xorg/gtest/xorg-gtest.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xfixes.h>
#include <X11/extensions/XInput2.h>
#include "barriers-common.h"
#include "xit-event.h"
#include "helpers.h"
using namespace xorg::testing::evemu;
class BarrierNotify : public BarrierTest {};
#define ASSERT_PTR_POS(x, y) \
QueryPointerPosition(dpy, &root_x, &root_y); \
ASSERT_EQ(x, root_x); \
ASSERT_EQ(y, root_y);
TEST_F(BarrierNotify, ReceivesNotifyEvents)
{
XORG_TESTCASE("Ensure that we receive BarrierNotify events\n"
"when barriers are hit.\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, 0, NULL);
XSync(dpy, False);
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1));
XISetMask(mask.mask, XI_BarrierHit);
XISelectEvents(dpy, root, &mask, 1);
free(mask.mask);
XSync(dpy, False);
dev->PlayOne(EV_REL, REL_X, -40, True);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(-40, event.ev->dx);
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_F(BarrierNotify, CorrectEventIDs)
{
XORG_TESTCASE("Ensure that barrier event IDs have correct and "
"sequential values, and that multiple chained hits "
"have the same event ID\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, 0, NULL);
XSync(dpy, False);
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1));
XISetMask(mask.mask, XI_BarrierHit);
XISetMask(mask.mask, XI_BarrierLeave);
XISelectEvents(dpy, root, &mask, 1);
free(mask.mask);
XSync(dpy, False);
/* Ensure we have a bunch of BarrierHits on our hands. */
for (int i = 0; i < 10; i++) {
dev->PlayOne(EV_REL, REL_X, -40, True);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(30, event.ev->root_y);
ASSERT_EQ(-40, event.ev->dx);
ASSERT_EQ(0, event.ev->dy);
ASSERT_EQ(1, event.ev->event_id);
}
/* Move outside the hitbox, and ensure that we
* get a BarrierNewEvent */
dev->PlayOne(EV_REL, REL_X, 20, True);
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierLeave);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(2, event.ev->event_id);
for (int i = 0; i < 10; i++) {
dev->PlayOne(EV_REL, REL_X, -40, True);
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(2, event.ev->event_id);
}
/* Ensure that we're still inside the hit box. Event ID
* should stay the same on such a minor change. */
dev->PlayOne(EV_REL, REL_X, 1, True);
for (int i = 0; i < 10; i++) {
dev->PlayOne(EV_REL, REL_X, -40, True);
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(2, event.ev->event_id);
}
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_F(BarrierNotify, BarrierReleases)
{
XORG_TESTCASE("Ensure that releasing barriers works without "
"erroring out and allows pointer movement over "
"the barrier, and that we properly get a "
"XI_BarrierPointerReleased.\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1));
XISetMask(mask.mask, XI_BarrierHit);
XISetMask(mask.mask, XI_BarrierPointerReleased);
XISetMask(mask.mask, XI_BarrierLeave);
XISelectEvents(dpy, root, &mask, 1);
free(mask.mask);
XSync(dpy, False);
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, 0, NULL);
XSync(dpy, False);
dev->PlayOne(EV_REL, REL_X, -40, True);
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(1, event.ev->event_id);
}
XIBarrierReleasePointer(dpy, VIRTUAL_CORE_POINTER_ID, barrier, 1);
XSync(dpy, False);
dev->PlayOne(EV_REL, REL_X, -40, True);
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierPointerReleased);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(1, event.ev->event_id);
}
/* Immediately afterwards, we should have a new event
* because we exited the hit box */
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierLeave);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(2, event.ev->event_id);
}
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_F(BarrierNotify, DestroyWindow)
{
XORG_TESTCASE("Create a window.\n"
"Set up a barrier using this window as drawable.\n"
"Select for barrier events.\n"
"Ensure events are received\n"
"Destroy the window.\n"
"Ensure events are not received anymore.\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
Window win = CreateWindow(dpy, root);
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, win, 20, 20, 20, 40, 0, 0, NULL);
XSync(dpy, False);
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1));
XISetMask(mask.mask, XI_BarrierHit);
XISelectEvents(dpy, win, &mask, 1);
free(mask.mask);
XSync(dpy, False);
dev->PlayOne(EV_REL, REL_X, -40, True);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(-40, event.ev->dx);
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
XDestroyWindow(dpy, win);
XSync(dpy, True);
dev->PlayOne(EV_REL, REL_X, -40, True);
double x, y;
QueryPointerPosition(dpy, &x, &y);
EXPECT_EQ(x, 20);
EXPECT_EQ(y, 30);
ASSERT_FALSE(xorg::testing::XServer::WaitForEventOfType(Display(),
GenericEvent,
xi2_opcode,
XI_BarrierHit,
500));
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_F(BarrierNotify, UnmapWindow)
{
XORG_TESTCASE("Create a window.\n"
"Set up a barrier using this window as drawable.\n"
"Select for barrier events.\n"
"Ensure events are received\n"
"Unmap the window.\n"
"Ensure events are still received.\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
Window win = CreateWindow(dpy, root);
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, win, 20, 20, 20, 40, 0, 0, NULL);
XSync(dpy, False);
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1));
XISetMask(mask.mask, XI_BarrierHit);
XISelectEvents(dpy, win, &mask, 1);
free(mask.mask);
XSync(dpy, False);
dev->PlayOne(EV_REL, REL_X, -40, True);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(-40, event.ev->dx);
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
XUnmapWindow(dpy, win);
XSync(dpy, True);
dev->PlayOne(EV_REL, REL_X, -40, True);
double x, y;
QueryPointerPosition(dpy, &x, &y);
EXPECT_EQ(x, 20);
EXPECT_EQ(y, 30);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(),
GenericEvent,
xi2_opcode,
XI_BarrierHit,
500));
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_F(BarrierNotify, EventsDuringActiveGrab)
{
XORG_TESTCASE("Set up a pointer barrier.\n"
"Actively grab the pointer.\n"
"Move pointer against barrier.\n"
"Expect events\n");
/* FIXME:
variations
- core, xi2 (xi1 not needed)
- barrier event masks set in grab mask
- owner_events true/false
- grab window == barrier window or other window
if OE is true and mask is set → event
if OE is false and mask is set → event
if OE is true and mask is not set, but set on window → event
if OE is false and mask is not set, but set on window → no event
*/
}
TEST_F(BarrierNotify, EventsDuringPassiveGrab)
{
XORG_TESTCASE("Set up a pointer barrier.\n"
"Trigger a passive pointer grab\n"
"Move pointer against barrier.\n"
"Expect events\n");
/* FIXME:
variations
- core, xi2 (xi1 not needed)
- barrier event masks set in grab mask
- owner_events true/false
- grab window == barrier window or other window
if OE is true and mask is set → event
if OE is false and mask is set → event
if OE is true and mask is not set, but set on window → event
if OE is false and mask is not set, but set on window → no event
*/
}
TEST_F(BarrierNotify, BarrierRandREventsVertical)
{
XORG_TESTCASE("Set up pointer barrier close to a screen.\n"
"Move the pointer against the barrier that the barrier blocks movement\n"
"Same movement must be restriced by the RandR dimensions"
"Ensure Barrier event root x/y are fully constrained");
#if 0
+-------------+
| |
| |
| |
| a | |
| y| |
+-----------+-+
x|
|b
Move a→b will clamp the barrier at X, but we want Y (i.e. including
RandR clamping)
#endif
::Display *dpy = Display();
XSynchronize(dpy, True);
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = new unsigned char[mask.mask_len]();
XISetMask(mask.mask, XI_BarrierHit);
XISetMask(mask.mask, XI_BarrierPointerReleased);
XISetMask(mask.mask, XI_BarrierLeave);
XISelectEvents(dpy, root, &mask, 1);
delete[] mask.mask;
int w = DisplayWidth(dpy, DefaultScreen(dpy));
int h = DisplayHeight(dpy, DefaultScreen(dpy));
XIWarpPointer(dpy, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, w - 40 , h - 30);
barrier = XFixesCreatePointerBarrier(dpy, root, w - 20, 0, w - 20, 4000, 0, 0, NULL);
dev->PlayOne(EV_REL, REL_X, 40, false);
dev->PlayOne(EV_REL, REL_Y, 100, true);
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(1, event.ev->event_id);
ASSERT_EQ(event.ev->root_x, w - 20 - 1);
ASSERT_LT(event.ev->root_y, h);
}
<|endoftext|>
|
<commit_before>#include "menu/menu.hpp"
#include <deque>
#include <memory>
#include <iostream>
#include <string>
namespace Menus
{
static void RenderWindow(NVGcontext* vg, int ix, int iy, int iw, int ih)
{
const float x = static_cast<float>(ix);
const float y = static_cast<float>(iy);
const float w = static_cast<float>(iw);
const float h = static_cast<float>(ih);
float rounding = 6.0f;
// black outline
nvgResetTransform(vg);
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(123, 123, 123, 255));
nvgRoundedRect(vg, x, y, w, h, rounding);
nvgFill(vg);
// white inner
float pad1 = 2.0f;
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(222, 222, 222, 255));
nvgRoundedRect(vg, x + pad1, y + pad1, w - pad1 - pad1, h - pad1 - pad1, rounding);
nvgFill(vg);
// black inner
pad1 = 5.0f;
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(74, 74, 74, 255));
nvgRoundedRect(vg, x + pad1, y + pad1, w - pad1 - pad1, h - pad1 - pad1, rounding);
nvgFill(vg);
// Gradient window fill
float pad2 = 7.0f;
nvgResetTransform(vg);
nvgTranslate(vg, pad2, pad2);
nvgBeginPath(vg);
NVGpaint paint = nvgLinearGradient(vg, x, y, w, h, nvgRGBA(0, 0, 155, 255), nvgRGBA(0, 0, 55, 255));
nvgFillPaint(vg, paint);
nvgRoundedRect(vg, x, y, w - pad2 - pad2, h - pad2 - pad2, rounding);
nvgFill(vg);
nvgResetTransform(vg);
}
}
static void DrawText(NVGcontext* vg, float xpos, float ypos, const char* msg, bool disable = false)
{
// nvgResetTransform(vg);
float fontSize = 36.0f;
nvgFontSize(vg, fontSize);
nvgFontBlur(vg, 0);
nvgFillColor(vg, nvgRGBA(0, 0, 0, 255));
nvgText(vg, xpos, ypos + fontSize, msg, nullptr);
nvgResetTransform(vg);
nvgFontSize(vg, fontSize);
nvgFontBlur(vg, 0);
if (!disable)
{
nvgFillColor(vg, nvgRGBA(230, 230, 230, 255));
}
else
{
nvgFillColor(vg, nvgRGBA(94, 94, 94, 255));
}
nvgText(vg, xpos - 2.0f, ypos - 2.0f + fontSize, msg, nullptr);
}
Menu::Menu()
{
}
static float Percent(float max, float percent)
{
return (max / 100.0f) * percent;
}
struct WindowRect
{
float x, y, w, h;
};
class Widget
{
public:
Widget()
{
}
virtual ~Widget()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget)
{
float xpos = Percent(screen.w, widget.x);
float ypos = Percent(screen.h, widget.y);
float w = Percent(screen.w, widget.w);
float h = Percent(screen.h, widget.h);
nvgBeginPath(vg);
nvgStrokeColor(vg, nvgRGBA(mR, mG, mB, 255));
nvgRect(vg, xpos + screen.x, ypos + screen.y, w, h);
nvgStroke(vg);
}
protected:
unsigned char mR = 250;
unsigned char mG = 0;
unsigned char mB = 255;
};
class Label : public Widget
{
public:
Label()
{
mR = 255;
mG = 255;
mB = 0;
}
Label(const std::string& text)
: mText(text)
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
if (!mText.empty())
{
float xpos = Percent(screen.w, widget.x);
float ypos = Percent(screen.h, widget.y);
DrawText(vg, xpos+ screen.x + 15, ypos + screen.y, mText.c_str());
}
Widget::Render(vg, screen, widget);
}
void SetText(const std::string& text)
{
mText = text;
}
private:
std::string mText;
};
class Container : public Widget
{
public:
Container()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
if (mWidget)
{
mWidget->Render(vg, screen, widget);
Widget::Render(vg, screen, widget);
}
}
void SetWidget(std::unique_ptr<Widget> w)
{
mWidget = std::move(w);
}
private:
std::unique_ptr<Widget> mWidget;
};
static float ToPercent(float current, float max)
{
return (current / max) * 100.0f;
}
class Window : public Container
{
public:
Window()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
float xpos = Percent(screen.w, widget.x);
float ypos = Percent(screen.h, widget.y);
float width = Percent(screen.w, widget.w);
float height = Percent(screen.h, widget.h);
mR = 0;
mG = 255;
mB = 0;
Widget::Render(vg, screen, widget);
Menus::RenderWindow(vg, xpos + screen.x, ypos + screen.y, width, height);
// Add N pixels for padding to child, but convert back to %
float hackWindowBorderAmount = 6.0f;
widget.x = ToPercent(xpos + hackWindowBorderAmount, screen.w);
widget.y = ToPercent(ypos + hackWindowBorderAmount, screen.h);
widget.w = ToPercent(width - (hackWindowBorderAmount * 2), screen.w);
widget.h = ToPercent(height - (hackWindowBorderAmount * 2), screen.h);
mR = 255;
mG = 0;
mB = 0;
Container::Render(vg, screen, widget);
}
};
class Cell : public Container
{
public:
Cell()
{
mR = 0;
mG = 0;
mB = 255;
}
void SetWidthHeightPercent(float wpercent, float hpercent)
{
mWidthPercent = wpercent;
mHeightPercent = hpercent;
}
void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
Container::Render(vg, screen, widget);
}
float WidthPercent() const
{
return mWidthPercent;
}
float HeightPercent() const
{
return mHeightPercent;
}
private:
float mWidthPercent = 1.0f;
float mHeightPercent = 1.0f;
};
class TableLayout : public Container
{
public:
TableLayout(int cols, int rows)
{
// Set up the table/grid
mCells.resize(rows);
for (int i = 0; i < rows; i++)
{
mCells[i].resize(cols);
}
// Make each cell take equal size
for (int x = 0; x < cols; x++)
{
for (int y = 0; y < rows; y++)
{
GetCell(x, y).SetWidthHeightPercent(100.0f / cols, 100.0f / rows);
}
}
}
Cell& GetCell(int x, int y)
{
return mCells[y][x];
}
void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
nvgResetTransform(vg);
// Calc the screen rect for the whole table
WindowRect tableRect;
tableRect.x = Percent(screen.w, widget.x) + screen.x;
tableRect.y = Percent(screen.h, widget.y) + screen.y;
tableRect.w = Percent(screen.w, widget.w);
tableRect.h = Percent(screen.h, widget.h);
float yPercent = 0.0f;
for (size_t y = 0; y < mCells.size(); y++)
{
float xPercent = 0.0f;
for (size_t x = 0; x < mCells[y].size(); x++)
{
mCells[y][x].Render(vg, tableRect, WindowRect{ xPercent, yPercent, mCells[y][x].WidthPercent(), mCells[y][x].HeightPercent() });
xPercent += mCells[y][x].WidthPercent();
}
yPercent += mCells[y][0].HeightPercent();
}
Container::Render(vg, screen, widget);
}
private:
std::deque<std::deque<Cell>> mCells;
float mXPos;
float mYPos;
float mWidth;
float mHeight;
};
void Menu::Render(NVGcontext* vg)
{
float screenW = 800.0f;
float screenH = 600.0f;
WindowRect screen = { 50.0f, 50.0f, screenW-100.0f, screenH-100.0f };
// WindowRect screen = { 0.0f, 0.0f, screenW, screenH };
nvgBeginFrame(vg, screenW, screenH, 1.0f);
nvgResetTransform(vg);
// Screen rect
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(128, 128, 0, 255));
nvgRect(vg, screen.x, screen.y, screen.w, screen.h);
nvgFill(vg);
nvgResetTransform(vg);
TableLayout l(1, 1);
l.GetCell(0, 0).SetWidthHeightPercent(100, 100);
auto txt1 = std::make_unique<Window>();
txt1->SetWidget(std::make_unique<Label>("Could be the end of the world..."));
l.GetCell(0, 0).SetWidget(std::move(txt1));
l.Render(vg, screen, WindowRect{ 1, 70, 65, 10 });
TableLayout layout2(2, 1);
layout2.GetCell(0, 0).SetWidthHeightPercent(75, 100);
auto txt2 = std::make_unique<Window>();
txt2->SetWidget(std::make_unique<Label>("Checking save data file."));
layout2.GetCell(0, 0).SetWidget(std::move(txt2));
layout2.GetCell(1, 0).SetWidthHeightPercent(25, 100);
auto txt3 = std::make_unique<Window>();
txt3->SetWidget(std::make_unique<Label>("Load"));
layout2.GetCell(1, 0).SetWidget(std::move(txt3));
layout2.Render(vg, screen, WindowRect{ 0.0f, 0.0f, 100.0f, 10.8f });
auto layout = std::make_unique<TableLayout>(5, 2);
int saveNum = 0;
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 2; y++)
{
layout->GetCell(x, y).SetWidget(std::make_unique<Label>("Save " + std::to_string(++saveNum)));
}
}
Window saves;
saves.SetWidget(std::move(layout));
saves.Render(vg, screen, WindowRect{ 14.0f, 42.0f, 100.0f - (14.0f * 2), 14.0f });
Window test;
test.SetWidget(std::make_unique<Label>("Testing direct window"));
test.Render(vg, screen, WindowRect{ 2.0f, 85.0f, 50.0f, 10.0f });
// Temp cursor
nvgResetTransform(vg);
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(255, 255, 255, 255));
nvgRect(vg, mCursorXPos, mCursorYPos, 25, 25);
nvgFill(vg);
nvgEndFrame(vg);
}
void Menu::Update()
{
}
void Menu::HandleInput(const bool(&buttons)[SDL_CONTROLLER_BUTTON_MAX], const bool(&oldbuttons)[SDL_CONTROLLER_BUTTON_MAX])
{
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_LEFT] && buttons[SDL_CONTROLLER_BUTTON_DPAD_LEFT])
{
mCursorXPos -= 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_RIGHT] && buttons[SDL_CONTROLLER_BUTTON_DPAD_RIGHT])
{
mCursorXPos += 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_UP] && buttons[SDL_CONTROLLER_BUTTON_DPAD_UP])
{
mCursorYPos -= 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_DOWN] && buttons[SDL_CONTROLLER_BUTTON_DPAD_DOWN])
{
mCursorYPos += 40.0f;
}
}
<commit_msg>remove text positioning hacks<commit_after>#include "menu/menu.hpp"
#include <deque>
#include <memory>
#include <iostream>
#include <string>
namespace Menus
{
static void RenderWindow(NVGcontext* vg, int ix, int iy, int iw, int ih)
{
const float x = static_cast<float>(ix);
const float y = static_cast<float>(iy);
const float w = static_cast<float>(iw);
const float h = static_cast<float>(ih);
float rounding = 6.0f;
// black outline
nvgResetTransform(vg);
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(123, 123, 123, 255));
nvgRoundedRect(vg, x, y, w, h, rounding);
nvgFill(vg);
// white inner
float pad1 = 2.0f;
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(222, 222, 222, 255));
nvgRoundedRect(vg, x + pad1, y + pad1, w - pad1 - pad1, h - pad1 - pad1, rounding);
nvgFill(vg);
// black inner
pad1 = 5.0f;
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(74, 74, 74, 255));
nvgRoundedRect(vg, x + pad1, y + pad1, w - pad1 - pad1, h - pad1 - pad1, rounding);
nvgFill(vg);
// Gradient window fill
float pad2 = 7.0f;
nvgResetTransform(vg);
nvgTranslate(vg, pad2, pad2);
nvgBeginPath(vg);
NVGpaint paint = nvgLinearGradient(vg, x, y, w, h, nvgRGBA(0, 0, 155, 255), nvgRGBA(0, 0, 55, 255));
nvgFillPaint(vg, paint);
nvgRoundedRect(vg, x, y, w - pad2 - pad2, h - pad2 - pad2, rounding);
nvgFill(vg);
nvgResetTransform(vg);
}
}
static void DrawText(NVGcontext* vg, float xpos, float ypos, const char* msg, bool disable = false)
{
// nvgResetTransform(vg);
float fontSize = 36.0f;
nvgFontSize(vg, fontSize);
nvgFontBlur(vg, 0);
nvgFillColor(vg, nvgRGBA(0, 0, 0, 255));
nvgText(vg, xpos, ypos, msg, nullptr);
nvgResetTransform(vg);
nvgFontSize(vg, fontSize);
nvgFontBlur(vg, 0);
if (!disable)
{
nvgFillColor(vg, nvgRGBA(230, 230, 230, 255));
}
else
{
nvgFillColor(vg, nvgRGBA(94, 94, 94, 255));
}
nvgText(vg, xpos - 2.0f, ypos - 2.0f, msg, nullptr);
}
Menu::Menu()
{
}
static float Percent(float max, float percent)
{
return (max / 100.0f) * percent;
}
struct WindowRect
{
float x, y, w, h;
};
class Widget
{
public:
Widget()
{
}
virtual ~Widget()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget)
{
float xpos = Percent(screen.w, widget.x);
float ypos = Percent(screen.h, widget.y);
float w = Percent(screen.w, widget.w);
float h = Percent(screen.h, widget.h);
nvgBeginPath(vg);
nvgStrokeColor(vg, nvgRGBA(mR, mG, mB, 255));
nvgRect(vg, xpos + screen.x, ypos + screen.y, w, h);
nvgStroke(vg);
}
protected:
unsigned char mR = 250;
unsigned char mG = 0;
unsigned char mB = 255;
};
class Label : public Widget
{
public:
Label()
{
mR = 255;
mG = 255;
mB = 0;
}
Label(const std::string& text)
: mText(text)
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
if (!mText.empty())
{
float xpos = Percent(screen.w, widget.x);
float ypos = Percent(screen.h, widget.y);
DrawText(vg, xpos+screen.x, ypos + screen.y, mText.c_str());
}
Widget::Render(vg, screen, widget);
}
void SetText(const std::string& text)
{
mText = text;
}
private:
std::string mText;
};
class Container : public Widget
{
public:
Container()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
if (mWidget)
{
mWidget->Render(vg, screen, widget);
Widget::Render(vg, screen, widget);
}
}
void SetWidget(std::unique_ptr<Widget> w)
{
mWidget = std::move(w);
}
private:
std::unique_ptr<Widget> mWidget;
};
static float ToPercent(float current, float max)
{
return (current / max) * 100.0f;
}
class Window : public Container
{
public:
Window()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
float xpos = Percent(screen.w, widget.x);
float ypos = Percent(screen.h, widget.y);
float width = Percent(screen.w, widget.w);
float height = Percent(screen.h, widget.h);
mR = 0;
mG = 255;
mB = 0;
Widget::Render(vg, screen, widget);
Menus::RenderWindow(vg, xpos + screen.x, ypos + screen.y, width, height);
// Add N pixels for padding to child, but convert back to %
float hackWindowBorderAmount = 6.0f;
widget.x = ToPercent(xpos + hackWindowBorderAmount, screen.w);
widget.y = ToPercent(ypos + hackWindowBorderAmount, screen.h);
widget.w = ToPercent(width - (hackWindowBorderAmount * 2), screen.w);
widget.h = ToPercent(height - (hackWindowBorderAmount * 2), screen.h);
mR = 255;
mG = 0;
mB = 0;
Container::Render(vg, screen, widget);
}
};
class Cell : public Container
{
public:
Cell()
{
mR = 0;
mG = 0;
mB = 255;
}
void SetWidthHeightPercent(float wpercent, float hpercent)
{
mWidthPercent = wpercent;
mHeightPercent = hpercent;
}
void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
Container::Render(vg, screen, widget);
}
float WidthPercent() const
{
return mWidthPercent;
}
float HeightPercent() const
{
return mHeightPercent;
}
private:
float mWidthPercent = 1.0f;
float mHeightPercent = 1.0f;
};
class TableLayout : public Container
{
public:
TableLayout(int cols, int rows)
{
// Set up the table/grid
mCells.resize(rows);
for (int i = 0; i < rows; i++)
{
mCells[i].resize(cols);
}
// Make each cell take equal size
for (int x = 0; x < cols; x++)
{
for (int y = 0; y < rows; y++)
{
GetCell(x, y).SetWidthHeightPercent(100.0f / cols, 100.0f / rows);
}
}
}
Cell& GetCell(int x, int y)
{
return mCells[y][x];
}
void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
nvgResetTransform(vg);
// Calc the screen rect for the whole table
WindowRect tableRect;
tableRect.x = Percent(screen.w, widget.x) + screen.x;
tableRect.y = Percent(screen.h, widget.y) + screen.y;
tableRect.w = Percent(screen.w, widget.w);
tableRect.h = Percent(screen.h, widget.h);
float yPercent = 0.0f;
for (size_t y = 0; y < mCells.size(); y++)
{
float xPercent = 0.0f;
for (size_t x = 0; x < mCells[y].size(); x++)
{
mCells[y][x].Render(vg, tableRect, WindowRect{ xPercent, yPercent, mCells[y][x].WidthPercent(), mCells[y][x].HeightPercent() });
xPercent += mCells[y][x].WidthPercent();
}
yPercent += mCells[y][0].HeightPercent();
}
Container::Render(vg, screen, widget);
}
private:
std::deque<std::deque<Cell>> mCells;
float mXPos;
float mYPos;
float mWidth;
float mHeight;
};
void Menu::Render(NVGcontext* vg)
{
float screenW = 800.0f;
float screenH = 600.0f;
WindowRect screen = { 50.0f, 50.0f, screenW-100.0f, screenH-100.0f };
// WindowRect screen = { 0.0f, 0.0f, screenW, screenH };
nvgBeginFrame(vg, screenW, screenH, 1.0f);
nvgResetTransform(vg);
// Screen rect
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(128, 128, 0, 255));
nvgRect(vg, screen.x, screen.y, screen.w, screen.h);
nvgFill(vg);
nvgResetTransform(vg);
TableLayout l(1, 1);
l.GetCell(0, 0).SetWidthHeightPercent(100, 100);
auto txt1 = std::make_unique<Window>();
txt1->SetWidget(std::make_unique<Label>("Could be the end of the world..."));
l.GetCell(0, 0).SetWidget(std::move(txt1));
l.Render(vg, screen, WindowRect{ 1, 70, 65, 10 });
TableLayout layout2(2, 1);
layout2.GetCell(0, 0).SetWidthHeightPercent(75, 100);
auto txt2 = std::make_unique<Window>();
txt2->SetWidget(std::make_unique<Label>("Checking save data file."));
layout2.GetCell(0, 0).SetWidget(std::move(txt2));
layout2.GetCell(1, 0).SetWidthHeightPercent(25, 100);
auto txt3 = std::make_unique<Window>();
txt3->SetWidget(std::make_unique<Label>("Load"));
layout2.GetCell(1, 0).SetWidget(std::move(txt3));
layout2.Render(vg, screen, WindowRect{ 0.0f, 0.0f, 100.0f, 10.8f });
auto layout = std::make_unique<TableLayout>(5, 2);
int saveNum = 0;
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 2; y++)
{
layout->GetCell(x, y).SetWidget(std::make_unique<Label>("Save " + std::to_string(++saveNum)));
}
}
Window saves;
saves.SetWidget(std::move(layout));
saves.Render(vg, screen, WindowRect{ 14.0f, 42.0f, 100.0f - (14.0f * 2), 14.0f });
Window test;
test.SetWidget(std::make_unique<Label>("Testing direct window"));
test.Render(vg, screen, WindowRect{ 2.0f, 85.0f, 50.0f, 10.0f });
// Temp cursor
nvgResetTransform(vg);
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(255, 255, 255, 255));
nvgRect(vg, mCursorXPos, mCursorYPos, 25, 25);
nvgFill(vg);
nvgEndFrame(vg);
}
void Menu::Update()
{
}
void Menu::HandleInput(const bool(&buttons)[SDL_CONTROLLER_BUTTON_MAX], const bool(&oldbuttons)[SDL_CONTROLLER_BUTTON_MAX])
{
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_LEFT] && buttons[SDL_CONTROLLER_BUTTON_DPAD_LEFT])
{
mCursorXPos -= 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_RIGHT] && buttons[SDL_CONTROLLER_BUTTON_DPAD_RIGHT])
{
mCursorXPos += 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_UP] && buttons[SDL_CONTROLLER_BUTTON_DPAD_UP])
{
mCursorYPos -= 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_DOWN] && buttons[SDL_CONTROLLER_BUTTON_DPAD_DOWN])
{
mCursorYPos += 40.0f;
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <algorithm>
#include "caf/buffered_downstream_manager.hpp"
#include "caf/detail/algorithms.hpp"
#include "caf/detail/path_state.hpp"
#include "caf/detail/select_all.hpp"
#include "caf/detail/unordered_flat_map.hpp"
#include "caf/outbound_path.hpp"
#include "caf/raise_error.hpp"
namespace caf {
template <class T, class Filter = unit_t, class Select = detail::select_all>
class broadcast_downstream_manager : public buffered_downstream_manager<T> {
public:
// -- member types -----------------------------------------------------------
/// Base type.
using super = buffered_downstream_manager<T>;
/// Type of `paths_`.
using typename super::map_type;
/// Unique pointer to an outbound path.
using typename super::unique_path_ptr;
/// Enables or disables output per path.
using filter_type = Filter;
/// Function object for evaluating filters.
using select_type = Select;
/// Container for caching `T`s per path with active filter.
using path_state = detail::path_state<Filter, T>;
/// Maps slot IDs to caches.
using state_map_type = detail::unordered_flat_map<stream_slot, path_state>;
// -- constructors, destructors, and assignment operators --------------------
broadcast_downstream_manager(stream_manager* parent)
: super(parent, type_id_v<T>) {
// nop
}
// -- properties -------------------------------------------------------------
template <class... Ts>
bool push_to(stream_slot slot, Ts&&... xs) {
auto old_size = buffered();
if (auto i = states().find(slot); i != states().end()) {
i->second.buf.emplace_back(std::forward<Ts>(xs)...);
auto new_size = buffered();
this->generated_messages(new_size - old_size);
return true;
}
return false;
}
size_t buffered() const noexcept override {
// We have a central buffer, but also an additional buffer at each path. We
// return the maximum size to reflect the current worst case.
size_t central_buf = this->buf_.size();
size_t max_path_buf = 0;
for (auto& kvp : state_map_)
max_path_buf = std::max(max_path_buf, kvp.second.buf.size());
return central_buf + max_path_buf;
}
/// Returns the number of buffered elements for this specific slot, ignoring
/// the central buffer.
size_t buffered(stream_slot slot) const noexcept override {
auto i = state_map_.find(slot);
return i != state_map_.end() ? i->second.buf.size() : 0u;
}
int32_t max_capacity() const noexcept override {
// The maximum capacity is limited by the slowest downstream path.
auto result = std::numeric_limits<int32_t>::max();
for (auto& kvp : this->paths_) {
auto mc = kvp.second->max_capacity;
// max_capacity is 0 if and only if we didn't receive an ack_batch yet.
if (mc > 0)
result = std::min(result, mc);
}
return result;
}
/// Sets the filter for `slot` to `filter`. Inserts a new element if `slot`
/// is a new path.
void set_filter(stream_slot slot, filter_type new_filter) {
CAF_LOG_TRACE(CAF_ARG(slot) << CAF_ARG(new_filter));
filter(slot) = std::move(new_filter);
}
/// Returns the filter for `slot`. Inserts a new element if `slot` is a new
/// path.
filter_type& filter(stream_slot slot) {
auto i = state_map_.find(slot);
if (i != state_map_.end())
return i->second.filter;
CAF_RAISE_ERROR("invalid slot");
}
/// Returns whether all filters satisfy the predicate as if applying
/// `std::all_of`.
template <class UnaryPredicate>
bool all_filters(UnaryPredicate predicate) {
return std::all_of(state_map_.begin(), state_map_.end(),
[&](const typename state_map_type::value_type& kvp) {
return predicate(kvp.second.filter);
});
}
/// Returns whether any filter satisfies the predicate as if applying
/// `std::any_of`.
template <class UnaryPredicate>
bool any_filter(UnaryPredicate predicate) {
return std::any_of(state_map_.begin(), state_map_.end(),
[&](const typename state_map_type::value_type& kvp) {
return predicate(kvp.second.filter);
});
}
/// Returns whether no filter satisfies the predicate as if applying
/// `std::none_of`.
template <class UnaryPredicate>
bool no_filter(UnaryPredicate predicate) {
return std::none_of(state_map_.begin(), state_map_.end(),
[&](const typename state_map_type::value_type& kvp) {
return predicate(kvp.second.filter);
});
}
/// Returns the broadcast states for all paths.
state_map_type& states() {
return state_map_;
}
/// Returns the broadcast states for all paths.
const state_map_type& states() const {
return state_map_;
}
/// Returns the selector for filtering outgoing data.
select_type& selector() {
return select_;
}
/// Returns the selector for filtering outgoing data.
const select_type& selector() const {
return select_;
}
// -- overridden functions ---------------------------------------------------
bool insert_path(unique_path_ptr ptr) override {
CAF_LOG_TRACE(CAF_ARG(ptr));
// Make sure state_map_ and paths_ are always equally sorted, otherwise
// we'll run into UB when calling `zip_foreach`.
CAF_ASSERT(state_map_.size() == this->paths_.size());
auto slot = ptr->slots.sender;
// Append to the regular path map.
if (!super::insert_path(std::move(ptr))) {
CAF_LOG_DEBUG("unable to insert path at slot" << slot);
return false;
}
// Append to the state map.
if (!state_map_.emplace(slot, path_state{}).second) {
CAF_LOG_DEBUG("unable to add state for slot" << slot);
super::remove_path(slot, none, true);
return false;
}
return true;
}
void emit_batches() override {
CAF_LOG_TRACE(CAF_ARG2("buffered", this->buffered())
<< CAF_ARG2("paths", this->paths_.size()));
emit_batches_impl(false);
}
void force_emit_batches() override {
CAF_LOG_TRACE(CAF_ARG2("buffered", this->buffered())
<< CAF_ARG2("paths", this->paths_.size()));
emit_batches_impl(true);
}
/// Forces the manager flush its buffer to the individual path buffers.
void fan_out_flush() {
auto old_size = buffered();
auto& buf = this->buf_;
auto f = [&](typename map_type::value_type& x,
typename state_map_type::value_type& y) {
// Don't push new data into a closing path.
if (x.second->closing)
return;
// Push data from the global buffer to path buffers.
auto& st = y.second;
if constexpr (std::is_same<select_type, detail::select_all>::value) {
st.buf.insert(st.buf.end(), buf.begin(), buf.end());
} else {
for (auto& piece : buf)
if (select_(st.filter, piece))
st.buf.emplace_back(piece);
}
};
detail::zip_foreach(f, this->paths_.container(), state_map_.container());
buf.clear();
// We may drop messages due to filtering or because all paths are closed.
auto new_size = buffered();
CAF_ASSERT(old_size >= new_size);
this->dropped_messages(old_size - new_size);
}
protected:
void about_to_erase(outbound_path* ptr, bool silent, error* reason) override {
CAF_ASSERT(ptr != nullptr);
CAF_LOG_TRACE(CAF_ARG2("slot", ptr->slots.sender)
<< CAF_ARG(silent) << CAF_ARG(reason));
state_map_.erase(ptr->slots.sender);
super::about_to_erase(ptr, silent, reason);
}
private:
void emit_batches_impl(bool force_underfull) {
CAF_ASSERT(this->paths_.size() <= state_map_.size());
if (this->paths_.empty())
return;
auto old_size = buffered();
// Calculate the chunk size, i.e., how many more items we can put to our
// caches at the most.
auto not_closing = [&](typename map_type::value_type& x,
typename state_map_type::value_type&) {
return !x.second->closing;
};
// Returns the minimum of `interim` and `get_credit(x) - get_cache_size(y)`.
auto f = [&](size_t interim, typename map_type::value_type& x,
typename state_map_type::value_type& y) {
auto credit = static_cast<size_t>(x.second->open_credit);
auto cache_size = y.second.buf.size();
return std::min(interim, credit > cache_size ? credit - cache_size : 0u);
};
auto chunk_size
= detail::zip_fold_if(f, not_closing, std::numeric_limits<size_t>::max(),
this->paths_.container(), state_map_.container());
if (chunk_size == std::numeric_limits<size_t>::max()) {
// All paths are closing, simply try forcing out more data and return.
auto g = [&](typename map_type::value_type& x,
typename state_map_type::value_type& y) {
// Always force batches on closing paths.
x.second->emit_batches(this->self(), y.second.buf, true);
};
detail::zip_foreach(g, this->paths_.container(), state_map_.container());
return;
}
auto chunk = this->get_chunk(chunk_size);
if (chunk.empty()) {
auto g = [&](typename map_type::value_type& x,
typename state_map_type::value_type& y) {
// Always force batches on closing paths.
x.second->emit_batches(this->self(), y.second.buf,
force_underfull || x.second->closing);
};
detail::zip_foreach(g, this->paths_.container(), state_map_.container());
} else {
auto g = [&](typename map_type::value_type& x,
typename state_map_type::value_type& y) {
auto& st = y.second;
// Don't enqueue new data into a closing path.
if (!x.second->closing) {
// Push data from the global buffer to path buffers.
// TODO: replace with `if constexpr` when switching to C++17
if (std::is_same<select_type, detail::select_all>::value) {
st.buf.insert(st.buf.end(), chunk.begin(), chunk.end());
} else {
for (auto& piece : chunk)
if (select_(st.filter, piece))
st.buf.emplace_back(piece);
}
}
// Always force batches on closing paths.
x.second->emit_batches(this->self(), st.buf,
force_underfull || x.second->closing);
};
detail::zip_foreach(g, this->paths_.container(), state_map_.container());
}
auto new_size = buffered();
CAF_ASSERT(old_size >= new_size);
this->shipped_messages(old_size - new_size);
}
state_map_type state_map_;
select_type select_;
};
} // namespace caf
<commit_msg>Fix formatting<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <algorithm>
#include "caf/buffered_downstream_manager.hpp"
#include "caf/detail/algorithms.hpp"
#include "caf/detail/path_state.hpp"
#include "caf/detail/select_all.hpp"
#include "caf/detail/unordered_flat_map.hpp"
#include "caf/outbound_path.hpp"
#include "caf/raise_error.hpp"
namespace caf {
template <class T, class Filter = unit_t, class Select = detail::select_all>
class broadcast_downstream_manager : public buffered_downstream_manager<T> {
public:
// -- member types -----------------------------------------------------------
/// Base type.
using super = buffered_downstream_manager<T>;
/// Type of `paths_`.
using typename super::map_type;
/// Unique pointer to an outbound path.
using typename super::unique_path_ptr;
/// Enables or disables output per path.
using filter_type = Filter;
/// Function object for evaluating filters.
using select_type = Select;
/// Container for caching `T`s per path with active filter.
using path_state = detail::path_state<Filter, T>;
/// Maps slot IDs to caches.
using state_map_type = detail::unordered_flat_map<stream_slot, path_state>;
// -- constructors, destructors, and assignment operators --------------------
broadcast_downstream_manager(stream_manager* parent)
: super(parent, type_id_v<T>) {
// nop
}
// -- properties -------------------------------------------------------------
template <class... Ts>
bool push_to(stream_slot slot, Ts&&... xs) {
auto old_size = buffered();
if (auto i = states().find(slot); i != states().end()) {
i->second.buf.emplace_back(std::forward<Ts>(xs)...);
auto new_size = buffered();
this->generated_messages(new_size - old_size);
return true;
}
return false;
}
size_t buffered() const noexcept override {
// We have a central buffer, but also an additional buffer at each path. We
// return the maximum size to reflect the current worst case.
size_t central_buf = this->buf_.size();
size_t max_path_buf = 0;
for (auto& kvp : state_map_)
max_path_buf = std::max(max_path_buf, kvp.second.buf.size());
return central_buf + max_path_buf;
}
/// Returns the number of buffered elements for this specific slot, ignoring
/// the central buffer.
size_t buffered(stream_slot slot) const noexcept override {
auto i = state_map_.find(slot);
return i != state_map_.end() ? i->second.buf.size() : 0u;
}
int32_t max_capacity() const noexcept override {
// The maximum capacity is limited by the slowest downstream path.
auto result = std::numeric_limits<int32_t>::max();
for (auto& kvp : this->paths_) {
auto mc = kvp.second->max_capacity;
// max_capacity is 0 if and only if we didn't receive an ack_batch yet.
if (mc > 0)
result = std::min(result, mc);
}
return result;
}
/// Sets the filter for `slot` to `filter`. Inserts a new element if `slot`
/// is a new path.
void set_filter(stream_slot slot, filter_type new_filter) {
CAF_LOG_TRACE(CAF_ARG(slot) << CAF_ARG(new_filter));
filter(slot) = std::move(new_filter);
}
/// Returns the filter for `slot`. Inserts a new element if `slot` is a new
/// path.
filter_type& filter(stream_slot slot) {
auto i = state_map_.find(slot);
if (i != state_map_.end())
return i->second.filter;
CAF_RAISE_ERROR("invalid slot");
}
/// Returns whether all filters satisfy the predicate as if applying
/// `std::all_of`.
template <class UnaryPredicate>
bool all_filters(UnaryPredicate predicate) {
return std::all_of(state_map_.begin(), state_map_.end(),
[&](const typename state_map_type::value_type& kvp) {
return predicate(kvp.second.filter);
});
}
/// Returns whether any filter satisfies the predicate as if applying
/// `std::any_of`.
template <class UnaryPredicate>
bool any_filter(UnaryPredicate predicate) {
return std::any_of(state_map_.begin(), state_map_.end(),
[&](const typename state_map_type::value_type& kvp) {
return predicate(kvp.second.filter);
});
}
/// Returns whether no filter satisfies the predicate as if applying
/// `std::none_of`.
template <class UnaryPredicate>
bool no_filter(UnaryPredicate predicate) {
return std::none_of(state_map_.begin(), state_map_.end(),
[&](const typename state_map_type::value_type& kvp) {
return predicate(kvp.second.filter);
});
}
/// Returns the broadcast states for all paths.
state_map_type& states() {
return state_map_;
}
/// Returns the broadcast states for all paths.
const state_map_type& states() const {
return state_map_;
}
/// Returns the selector for filtering outgoing data.
select_type& selector() {
return select_;
}
/// Returns the selector for filtering outgoing data.
const select_type& selector() const {
return select_;
}
// -- overridden functions ---------------------------------------------------
bool insert_path(unique_path_ptr ptr) override {
CAF_LOG_TRACE(CAF_ARG(ptr));
// Make sure state_map_ and paths_ are always equally sorted, otherwise
// we'll run into UB when calling `zip_foreach`.
CAF_ASSERT(state_map_.size() == this->paths_.size());
auto slot = ptr->slots.sender;
// Append to the regular path map.
if (!super::insert_path(std::move(ptr))) {
CAF_LOG_DEBUG("unable to insert path at slot" << slot);
return false;
}
// Append to the state map.
if (!state_map_.emplace(slot, path_state{}).second) {
CAF_LOG_DEBUG("unable to add state for slot" << slot);
super::remove_path(slot, none, true);
return false;
}
return true;
}
void emit_batches() override {
CAF_LOG_TRACE(CAF_ARG2("buffered", this->buffered())
<< CAF_ARG2("paths", this->paths_.size()));
emit_batches_impl(false);
}
void force_emit_batches() override {
CAF_LOG_TRACE(CAF_ARG2("buffered", this->buffered())
<< CAF_ARG2("paths", this->paths_.size()));
emit_batches_impl(true);
}
/// Forces the manager flush its buffer to the individual path buffers.
void fan_out_flush() {
auto old_size = buffered();
auto& buf = this->buf_;
auto f = [&](typename map_type::value_type& x,
typename state_map_type::value_type& y) {
// Don't push new data into a closing path.
if (x.second->closing)
return;
// Push data from the global buffer to path buffers.
auto& st = y.second;
if constexpr (std::is_same<select_type, detail::select_all>::value) {
st.buf.insert(st.buf.end(), buf.begin(), buf.end());
} else {
for (auto& piece : buf)
if (select_(st.filter, piece))
st.buf.emplace_back(piece);
}
};
detail::zip_foreach(f, this->paths_.container(), state_map_.container());
buf.clear();
// We may drop messages due to filtering or because all paths are closed.
auto new_size = buffered();
CAF_ASSERT(old_size >= new_size);
this->dropped_messages(old_size - new_size);
}
protected:
void about_to_erase(outbound_path* ptr, bool silent, error* reason) override {
CAF_ASSERT(ptr != nullptr);
CAF_LOG_TRACE(CAF_ARG2("slot", ptr->slots.sender)
<< CAF_ARG(silent) << CAF_ARG(reason));
state_map_.erase(ptr->slots.sender);
super::about_to_erase(ptr, silent, reason);
}
private:
void emit_batches_impl(bool force_underfull) {
CAF_ASSERT(this->paths_.size() <= state_map_.size());
if (this->paths_.empty())
return;
auto old_size = buffered();
// Calculate the chunk size, i.e., how many more items we can put to our
// caches at the most.
auto not_closing = [&](typename map_type::value_type& x,
typename state_map_type::value_type&) {
return !x.second->closing;
};
// Returns the minimum of `interim` and `get_credit(x) - get_cache_size(y)`.
auto f = [&](size_t interim, typename map_type::value_type& x,
typename state_map_type::value_type& y) {
auto credit = static_cast<size_t>(x.second->open_credit);
auto cache_size = y.second.buf.size();
return std::min(interim, credit > cache_size ? credit - cache_size : 0u);
};
auto chunk_size
= detail::zip_fold_if(f, not_closing, std::numeric_limits<size_t>::max(),
this->paths_.container(), state_map_.container());
if (chunk_size == std::numeric_limits<size_t>::max()) {
// All paths are closing, simply try forcing out more data and return.
auto g = [&](typename map_type::value_type& x,
typename state_map_type::value_type& y) {
// Always force batches on closing paths.
x.second->emit_batches(this->self(), y.second.buf, true);
};
detail::zip_foreach(g, this->paths_.container(), state_map_.container());
return;
}
auto chunk = this->get_chunk(chunk_size);
if (chunk.empty()) {
auto g = [&](typename map_type::value_type& x,
typename state_map_type::value_type& y) {
// Always force batches on closing paths.
x.second->emit_batches(this->self(), y.second.buf,
force_underfull || x.second->closing);
};
detail::zip_foreach(g, this->paths_.container(), state_map_.container());
} else {
auto g = [&](typename map_type::value_type& x,
typename state_map_type::value_type& y) {
auto& st = y.second;
// Don't enqueue new data into a closing path.
if (!x.second->closing) {
// Push data from the global buffer to path buffers.
// TODO: replace with `if constexpr` when switching to C++17
if (std::is_same<select_type, detail::select_all>::value) {
st.buf.insert(st.buf.end(), chunk.begin(), chunk.end());
} else {
for (auto& piece : chunk)
if (select_(st.filter, piece))
st.buf.emplace_back(piece);
}
}
// Always force batches on closing paths.
x.second->emit_batches(this->self(), st.buf,
force_underfull || x.second->closing);
};
detail::zip_foreach(g, this->paths_.container(), state_map_.container());
}
auto new_size = buffered();
CAF_ASSERT(old_size >= new_size);
this->shipped_messages(old_size - new_size);
}
state_map_type state_map_;
select_type select_;
};
} // namespace caf
<|endoftext|>
|
<commit_before>#include "menu/menu.hpp"
#include <deque>
#include <memory>
#include <iostream>
#include <string>
namespace Menus
{
static void RenderWindow(NVGcontext* vg, int ix, int iy, int iw, int ih)
{
const float x = static_cast<float>(ix);
const float y = static_cast<float>(iy);
const float w = static_cast<float>(iw);
const float h = static_cast<float>(ih);
float rounding = 6.0f;
// black outline
nvgResetTransform(vg);
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(123, 123, 123, 255));
nvgRoundedRect(vg, x, y, w, h, rounding);
nvgFill(vg);
// white inner
float pad1 = 2.0f;
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(222, 222, 222, 255));
nvgRoundedRect(vg, x + pad1, y + pad1, w - pad1 - pad1, h - pad1 - pad1, rounding);
nvgFill(vg);
// black inner
pad1 = 5.0f;
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(74, 74, 74, 255));
nvgRoundedRect(vg, x + pad1, y + pad1, w - pad1 - pad1, h - pad1 - pad1, rounding);
nvgFill(vg);
// Gradient window fill
float pad2 = 7.0f;
nvgResetTransform(vg);
nvgTranslate(vg, pad2, pad2);
nvgBeginPath(vg);
NVGpaint paint = nvgLinearGradient(vg, x, y, w, h, nvgRGBA(0, 0, 155, 255), nvgRGBA(0, 0, 55, 255));
nvgFillPaint(vg, paint);
nvgRoundedRect(vg, x, y, w - pad2 - pad2, h - pad2 - pad2, rounding);
nvgFill(vg);
}
}
static void DrawText(NVGcontext* vg, float xpos, float ypos, const char* msg, bool disable = false)
{
nvgResetTransform(vg);
// nvgTranslate(vg, 0.5f, 0.5f);
float fontSize = 36.0f;
nvgFontSize(vg, fontSize);
nvgFontBlur(vg, 0);
nvgFillColor(vg, nvgRGBA(0, 0, 0, 255));
nvgText(vg, xpos, ypos + fontSize, msg, nullptr);
nvgResetTransform(vg);
nvgFontSize(vg, fontSize);
nvgFontBlur(vg, 0);
if (!disable)
{
nvgFillColor(vg, nvgRGBA(230, 230, 230, 255));
}
else
{
nvgFillColor(vg, nvgRGBA(94, 94, 94, 255));
}
nvgText(vg, xpos - 2.0f, ypos - 2.0f + fontSize, msg, nullptr);
/*
nvgResetTransform(vg);
nvgBeginPath(vg);
NVGpaint paint = nvgLinearGradient(vg, 100.0f, 100.0f, 100.0f + 15, 120.0f + 15, nvgRGBA(0, 0, 0, 255), nvgRGBA(0, 255, 0, 155));
nvgFillPaint(vg, paint);
nvgFillPaint(vg, paint);
nvgCircle(vg, 100.0f, 120.0f, 10.0f);
nvgFill(vg);
*/
}
Menu::Menu()
{
}
static float Percent(float max, float percent)
{
return (max / 100.0f) * percent;
}
struct WindowRect
{
float x, y, w, h;
};
class Widget
{
public:
Widget()
{
}
virtual ~Widget()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) = 0;
private:
};
class Label : public Widget
{
public:
Label()
{
}
Label(const std::string& text)
: mText(text)
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
if (!mText.empty())
{
float xpos = Percent(screen.w, widget.x);
float ypos = Percent(screen.h, widget.y);
DrawText(vg, xpos+ screen.x + 15, ypos + screen.y, mText.c_str());
}
}
void SetText(const std::string& text)
{
mText = text;
}
private:
std::string mText;
};
class Container : public Widget
{
public:
Container()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
if (mWidget)
{
mWidget->Render(vg, screen, widget);
}
}
void SetWidget(std::unique_ptr<Widget> w)
{
mWidget = std::move(w);
}
private:
std::unique_ptr<Widget> mWidget;
};
class Window : public Container
{
public:
Window()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
float xpos = Percent(screen.w, widget.x);
float ypos = Percent(screen.h, widget.y);
float width = Percent(screen.w, widget.w);
float height = Percent(screen.h, widget.h);
Menus::RenderWindow(vg, xpos + screen.x, ypos + screen.y, width, height);
Container::Render(vg, screen, widget);
}
};
class Cell : public Container
{
public:
Cell()
{
}
void SetWidthHeightPercent(float wpercent, float hpercent)
{
mWidthPercent = wpercent;
mHeightPercent = hpercent;
}
void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
Container::Render(vg, screen, widget);
}
float WidthPercent() const
{
return mWidthPercent;
}
float HeightPercent() const
{
return mHeightPercent;
}
private:
float mWidthPercent = 1.0f;
float mHeightPercent = 1.0f;
};
class TableLayout : public Container
{
public:
TableLayout(int cols, int rows)
{
// Set up the table/grid
mCells.resize(rows);
for (int i = 0; i < rows; i++)
{
mCells[i].resize(cols);
}
// Make each cell take equal size
for (int x = 0; x < cols; x++)
{
for (int y = 0; y < rows; y++)
{
GetCell(x, y).SetWidthHeightPercent(100.0f / cols, 100.0f / rows);
}
}
}
Cell& GetCell(int x, int y)
{
return mCells[y][x];
}
void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
nvgResetTransform(vg);
// Calc the screen rect for the whole table
WindowRect tableRect;
tableRect.x = Percent(screen.w, widget.x);
tableRect.y = Percent(screen.h, widget.y);
tableRect.w = Percent(screen.w, widget.w);
tableRect.h = Percent(screen.h, widget.h);
float yPercent = 0.0f;
for (size_t y = 0; y < mCells.size(); y++)
{
float xPercent = 0.0f;
for (size_t x = 0; x < mCells[y].size(); x++)
{
mCells[y][x].Render(vg, tableRect, WindowRect{ xPercent, yPercent, mCells[y][x].WidthPercent(), mCells[y][x].HeightPercent() });
xPercent += mCells[y][x].WidthPercent();
}
yPercent += mCells[y][0].HeightPercent();
}
Container::Render(vg, screen, widget);
}
private:
std::deque<std::deque<Cell>> mCells;
float mXPos;
float mYPos;
float mWidth;
float mHeight;
};
void Menu::Render(NVGcontext* vg)
{
float screenW = 800.0f;
float screenH = 600.0f;
WindowRect screen = { 0.0f, 0.0f, screenW, screenH };
nvgBeginFrame(vg, screenW, screenH, 1.0f);
nvgResetTransform(vg);
TableLayout l(1, 1);
l.GetCell(0, 0).SetWidthHeightPercent(100, 100);
auto txt1 = std::make_unique<Window>();
txt1->SetWidget(std::make_unique<Label>("Could be the end of the world..."));
l.GetCell(0, 0).SetWidget(std::move(txt1));
l.Render(vg, screen, WindowRect{ 2, 70, 55, 8 });
TableLayout layout2(2, 1);
layout2.GetCell(0, 0).SetWidthHeightPercent(75, 100);
auto txt2 = std::make_unique<Window>();
txt2->SetWidget(std::make_unique<Label>("Checking save data file."));
layout2.GetCell(0, 0).SetWidget(std::move(txt2));
layout2.GetCell(1, 0).SetWidthHeightPercent(25, 100);
auto txt3 = std::make_unique<Window>();
txt3->SetWidget(std::make_unique<Label>("Load"));
layout2.GetCell(1, 0).SetWidget(std::move(txt3));
layout2.Render(vg, screen, WindowRect{ 0.0f, 0.0f, 100.0f, 10.8f });
auto layout = std::make_unique<TableLayout>(5, 2);
int saveNum = 0;
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 2; y++)
{
layout->GetCell(x, y).SetWidget(std::make_unique<Label>("Save " + std::to_string(++saveNum)));
}
}
Window saves;
saves.SetWidget(std::move(layout));
saves.Render(vg, screen, WindowRect{ 14.0f, 42.0f, 100.0f - (14.0f * 2), 14.0f });
Window test;
test.SetWidget(std::make_unique<Label>("Testing direct window"));
test.Render(vg, screen, WindowRect{ 40.0f, 80.0f, 40.0f, 9.0f });
// Temp cursor
nvgResetTransform(vg);
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(255, 255, 255, 255));
nvgRect(vg, mCursorXPos, mCursorYPos, 25, 25);
nvgFill(vg);
nvgEndFrame(vg);
}
void Menu::Update()
{
}
void Menu::HandleInput(const bool(&buttons)[SDL_CONTROLLER_BUTTON_MAX], const bool(&oldbuttons)[SDL_CONTROLLER_BUTTON_MAX])
{
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_LEFT] && buttons[SDL_CONTROLLER_BUTTON_DPAD_LEFT])
{
mCursorXPos -= 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_RIGHT] && buttons[SDL_CONTROLLER_BUTTON_DPAD_RIGHT])
{
mCursorXPos += 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_UP] && buttons[SDL_CONTROLLER_BUTTON_DPAD_UP])
{
mCursorYPos -= 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_DOWN] && buttons[SDL_CONTROLLER_BUTTON_DPAD_DOWN])
{
mCursorYPos += 40.0f;
}
}
<commit_msg>debug draw<commit_after>#include "menu/menu.hpp"
#include <deque>
#include <memory>
#include <iostream>
#include <string>
namespace Menus
{
static void RenderWindow(NVGcontext* vg, int ix, int iy, int iw, int ih)
{
const float x = static_cast<float>(ix);
const float y = static_cast<float>(iy);
const float w = static_cast<float>(iw);
const float h = static_cast<float>(ih);
float rounding = 6.0f;
// black outline
nvgResetTransform(vg);
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(123, 123, 123, 255));
nvgRoundedRect(vg, x, y, w, h, rounding);
nvgFill(vg);
// white inner
float pad1 = 2.0f;
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(222, 222, 222, 255));
nvgRoundedRect(vg, x + pad1, y + pad1, w - pad1 - pad1, h - pad1 - pad1, rounding);
nvgFill(vg);
// black inner
pad1 = 5.0f;
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(74, 74, 74, 255));
nvgRoundedRect(vg, x + pad1, y + pad1, w - pad1 - pad1, h - pad1 - pad1, rounding);
nvgFill(vg);
// Gradient window fill
float pad2 = 7.0f;
nvgResetTransform(vg);
nvgTranslate(vg, pad2, pad2);
nvgBeginPath(vg);
NVGpaint paint = nvgLinearGradient(vg, x, y, w, h, nvgRGBA(0, 0, 155, 255), nvgRGBA(0, 0, 55, 255));
nvgFillPaint(vg, paint);
nvgRoundedRect(vg, x, y, w - pad2 - pad2, h - pad2 - pad2, rounding);
nvgFill(vg);
}
}
static void DrawText(NVGcontext* vg, float xpos, float ypos, const char* msg, bool disable = false)
{
nvgResetTransform(vg);
// nvgTranslate(vg, 0.5f, 0.5f);
float fontSize = 36.0f;
nvgFontSize(vg, fontSize);
nvgFontBlur(vg, 0);
nvgFillColor(vg, nvgRGBA(0, 0, 0, 255));
nvgText(vg, xpos, ypos + fontSize, msg, nullptr);
nvgResetTransform(vg);
nvgFontSize(vg, fontSize);
nvgFontBlur(vg, 0);
if (!disable)
{
nvgFillColor(vg, nvgRGBA(230, 230, 230, 255));
}
else
{
nvgFillColor(vg, nvgRGBA(94, 94, 94, 255));
}
nvgText(vg, xpos - 2.0f, ypos - 2.0f + fontSize, msg, nullptr);
/*
nvgResetTransform(vg);
nvgBeginPath(vg);
NVGpaint paint = nvgLinearGradient(vg, 100.0f, 100.0f, 100.0f + 15, 120.0f + 15, nvgRGBA(0, 0, 0, 255), nvgRGBA(0, 255, 0, 155));
nvgFillPaint(vg, paint);
nvgFillPaint(vg, paint);
nvgCircle(vg, 100.0f, 120.0f, 10.0f);
nvgFill(vg);
*/
}
Menu::Menu()
{
}
static float Percent(float max, float percent)
{
return (max / 100.0f) * percent;
}
struct WindowRect
{
float x, y, w, h;
};
class Widget
{
public:
Widget()
{
}
virtual ~Widget()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget)
{
float xpos = Percent(screen.w, widget.x);
float ypos = Percent(screen.h, widget.y);
float w = Percent(screen.w, widget.w);
float h = Percent(screen.h, widget.h);
nvgBeginPath(vg);
nvgStrokeColor(vg, nvgRGBA(255, 0, 255, 255));
nvgRect(vg, xpos + screen.x, ypos + screen.y, w, h);
nvgStroke(vg);
}
private:
};
class Label : public Widget
{
public:
Label()
{
}
Label(const std::string& text)
: mText(text)
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
if (!mText.empty())
{
float xpos = Percent(screen.w, widget.x);
float ypos = Percent(screen.h, widget.y);
DrawText(vg, xpos+ screen.x + 15, ypos + screen.y, mText.c_str());
}
Widget::Render(vg, screen, widget);
}
void SetText(const std::string& text)
{
mText = text;
}
private:
std::string mText;
};
class Container : public Widget
{
public:
Container()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
if (mWidget)
{
mWidget->Render(vg, screen, widget);
}
Widget::Render(vg, screen, widget);
}
void SetWidget(std::unique_ptr<Widget> w)
{
mWidget = std::move(w);
}
private:
std::unique_ptr<Widget> mWidget;
};
class Window : public Container
{
public:
Window()
{
}
virtual void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
float xpos = Percent(screen.w, widget.x);
float ypos = Percent(screen.h, widget.y);
float width = Percent(screen.w, widget.w);
float height = Percent(screen.h, widget.h);
Widget::Render(vg, screen, widget);
Menus::RenderWindow(vg, xpos + screen.x, ypos + screen.y, width, height);
// TODO: Make screen rect smaller by the window border amount
float hackWindowBorderAmount = 0.0f;
screen.x += hackWindowBorderAmount;
screen.y += hackWindowBorderAmount;
// screen.w = screen.w - 19.0f;
// screen.h -= hackWindowBorderAmount*2;
Container::Render(vg, screen, widget);
}
};
class Cell : public Container
{
public:
Cell()
{
}
void SetWidthHeightPercent(float wpercent, float hpercent)
{
mWidthPercent = wpercent;
mHeightPercent = hpercent;
}
void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
Container::Render(vg, screen, widget);
}
float WidthPercent() const
{
return mWidthPercent;
}
float HeightPercent() const
{
return mHeightPercent;
}
private:
float mWidthPercent = 1.0f;
float mHeightPercent = 1.0f;
};
class TableLayout : public Container
{
public:
TableLayout(int cols, int rows)
{
// Set up the table/grid
mCells.resize(rows);
for (int i = 0; i < rows; i++)
{
mCells[i].resize(cols);
}
// Make each cell take equal size
for (int x = 0; x < cols; x++)
{
for (int y = 0; y < rows; y++)
{
GetCell(x, y).SetWidthHeightPercent(100.0f / cols, 100.0f / rows);
}
}
}
Cell& GetCell(int x, int y)
{
return mCells[y][x];
}
void Render(NVGcontext* vg, WindowRect screen, WindowRect widget) override
{
nvgResetTransform(vg);
// Calc the screen rect for the whole table
WindowRect tableRect;
tableRect.x = Percent(screen.w, widget.x);
tableRect.y = Percent(screen.h, widget.y);
tableRect.w = Percent(screen.w, widget.w);
tableRect.h = Percent(screen.h, widget.h);
float yPercent = 0.0f;
for (size_t y = 0; y < mCells.size(); y++)
{
float xPercent = 0.0f;
for (size_t x = 0; x < mCells[y].size(); x++)
{
mCells[y][x].Render(vg, tableRect, WindowRect{ xPercent, yPercent, mCells[y][x].WidthPercent(), mCells[y][x].HeightPercent() });
xPercent += mCells[y][x].WidthPercent();
}
yPercent += mCells[y][0].HeightPercent();
}
Container::Render(vg, screen, widget);
}
private:
std::deque<std::deque<Cell>> mCells;
float mXPos;
float mYPos;
float mWidth;
float mHeight;
};
void Menu::Render(NVGcontext* vg)
{
float screenW = 800.0f;
float screenH = 600.0f;
WindowRect screen = { 0.0f, 0.0f, screenW, screenH };
nvgBeginFrame(vg, screenW, screenH, 1.0f);
nvgResetTransform(vg);
TableLayout l(1, 1);
l.GetCell(0, 0).SetWidthHeightPercent(100, 100);
auto txt1 = std::make_unique<Window>();
txt1->SetWidget(std::make_unique<Label>("Could be the end of the world..."));
l.GetCell(0, 0).SetWidget(std::move(txt1));
l.Render(vg, screen, WindowRect{ 2, 70, 55, 8 });
TableLayout layout2(2, 1);
layout2.GetCell(0, 0).SetWidthHeightPercent(75, 100);
auto txt2 = std::make_unique<Window>();
txt2->SetWidget(std::make_unique<Label>("Checking save data file."));
layout2.GetCell(0, 0).SetWidget(std::move(txt2));
layout2.GetCell(1, 0).SetWidthHeightPercent(25, 100);
auto txt3 = std::make_unique<Window>();
txt3->SetWidget(std::make_unique<Label>("Load"));
layout2.GetCell(1, 0).SetWidget(std::move(txt3));
layout2.Render(vg, screen, WindowRect{ 0.0f, 0.0f, 100.0f, 10.8f });
auto layout = std::make_unique<TableLayout>(5, 2);
int saveNum = 0;
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 2; y++)
{
layout->GetCell(x, y).SetWidget(std::make_unique<Label>("Save " + std::to_string(++saveNum)));
}
}
Window saves;
saves.SetWidget(std::move(layout));
saves.Render(vg, screen, WindowRect{ 14.0f, 42.0f, 100.0f - (14.0f * 2), 14.0f });
Window test;
test.SetWidget(std::make_unique<Label>("Testing direct window"));
test.Render(vg, screen, WindowRect{ 40.0f, 80.0f, 40.0f, 9.0f });
// Temp cursor
nvgResetTransform(vg);
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(255, 255, 255, 255));
nvgRect(vg, mCursorXPos, mCursorYPos, 25, 25);
nvgFill(vg);
nvgEndFrame(vg);
}
void Menu::Update()
{
}
void Menu::HandleInput(const bool(&buttons)[SDL_CONTROLLER_BUTTON_MAX], const bool(&oldbuttons)[SDL_CONTROLLER_BUTTON_MAX])
{
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_LEFT] && buttons[SDL_CONTROLLER_BUTTON_DPAD_LEFT])
{
mCursorXPos -= 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_RIGHT] && buttons[SDL_CONTROLLER_BUTTON_DPAD_RIGHT])
{
mCursorXPos += 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_UP] && buttons[SDL_CONTROLLER_BUTTON_DPAD_UP])
{
mCursorYPos -= 40.0f;
}
if (!oldbuttons[SDL_CONTROLLER_BUTTON_DPAD_DOWN] && buttons[SDL_CONTROLLER_BUTTON_DPAD_DOWN])
{
mCursorYPos += 40.0f;
}
}
<|endoftext|>
|
<commit_before>#include "stdio.h"
#include "iostream.h"
#include "trie.h"
#include "grimoire/trie.h"
namespace marisa {
Trie::Trie() : trie_() {}
Trie::~Trie() {}
void Trie::build(Keyset &keyset, int config_flags) {
scoped_ptr<grimoire::LoudsTrie> temp(new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
temp->build(keyset, config_flags);
trie_.swap(temp);
}
void Trie::mmap(const char *filename) {
MARISA_THROW_IF(filename == NULL, MARISA_NULL_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Mapper mapper;
mapper.open(filename);
temp->map(mapper);
trie_.swap(temp);
}
void Trie::map(const void *ptr, std::size_t size) {
MARISA_THROW_IF((ptr == NULL) && (size != 0), MARISA_NULL_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Mapper mapper;
mapper.open(ptr, size);
temp->map(mapper);
trie_.swap(temp);
}
void Trie::load(const char *filename) {
MARISA_THROW_IF(filename == NULL, MARISA_NULL_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Reader reader;
reader.open(filename);
temp->read(reader);
trie_.swap(temp);
}
void Trie::read(int fd) {
MARISA_THROW_IF(fd == -1, MARISA_CODE_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Reader reader;
reader.open(fd);
temp->read(reader);
trie_.swap(temp);
}
void Trie::save(const char *filename) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
MARISA_THROW_IF(filename == NULL, MARISA_NULL_ERROR);
grimoire::Writer writer;
writer.open(filename);
trie_->write(writer);
}
void Trie::write(int fd) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
MARISA_THROW_IF(fd == -1, MARISA_CODE_ERROR);
grimoire::Writer writer;
writer.open(fd);
trie_->write(writer);
}
bool Trie::lookup(Agent &agent) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
if (!agent.has_state()) {
agent.init_state();
}
return trie_->lookup(agent);
}
void Trie::reverse_lookup(Agent &agent) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
if (!agent.has_state()) {
agent.init_state();
}
trie_->reverse_lookup(agent);
}
bool Trie::common_prefix_search(Agent &agent) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
if (!agent.has_state()) {
agent.init_state();
}
return trie_->common_prefix_search(agent);
}
bool Trie::predictive_search(Agent &agent) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
if (!agent.has_state()) {
agent.init_state();
}
return trie_->predictive_search(agent);
}
std::size_t Trie::num_tries() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->num_tries();
}
std::size_t Trie::num_keys() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->num_keys();
}
std::size_t Trie::num_nodes() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->num_nodes();
}
TailMode Trie::tail_mode() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->tail_mode();
}
NodeOrder Trie::node_order() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->node_order();
}
bool Trie::empty() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->empty();
}
std::size_t Trie::size() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->size();
}
std::size_t Trie::total_size() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->total_size();
}
std::size_t Trie::io_size() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->io_size();
}
void Trie::clear() {
Trie().swap(*this);
}
void Trie::swap(Trie &rhs) {
trie_.swap(rhs.trie_);
}
BytesTrie::BytesTrie() {
// fill in this constructor
}
/*
* Return a list of payloads (as byte objects) for a given key.
*/
void BytesTrie::get(std::vector< std::vector<char> > *results, const char *prefix) {
// allocate a new buffer
int b_prefix_len = strlen(prefix)+2;
char *b_prefix = new char[b_prefix_len];
strcpy(b_prefix, prefix);
b_prefix[b_prefix_len-2] = 0xff; // Default value separator
b_prefix[b_prefix_len-1] = 0x00; // Default value separator
size_t prefix_len = strlen(b_prefix);
marisa::Agent ag;
ag.set_query(b_prefix);
while (this->predictive_search(ag)) {
// we need to copy the char* into a vector<char> to store
// a byte array
const char *tmp = ag.key().ptr()+b_prefix_len-1;
std::vector<char> byte_array(tmp, tmp+strlen(tmp));
results->push_back(byte_array);
}
delete b_prefix;
}
RecordTrie::RecordTrie(const char *fmt) {
_fmt.assign(fmt, strlen(fmt));
}
void RecordTrie::getRecord(std::vector<marisa::Record> *result, const char* b_prefix) {
// TODO:
}
} // namespace marisa
#include <iostream>
namespace marisa {
class TrieIO {
public:
static void fread(std::FILE *file, Trie *trie) {
MARISA_THROW_IF(trie == NULL, MARISA_NULL_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(
new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Reader reader;
reader.open(file);
temp->read(reader);
trie->trie_.swap(temp);
}
static void fwrite(std::FILE *file, const Trie &trie) {
MARISA_THROW_IF(file == NULL, MARISA_NULL_ERROR);
MARISA_THROW_IF(trie.trie_.get() == NULL, MARISA_STATE_ERROR);
grimoire::Writer writer;
writer.open(file);
trie.trie_->write(writer);
}
static std::istream &read(std::istream &stream, Trie *trie) {
MARISA_THROW_IF(trie == NULL, MARISA_NULL_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(
new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Reader reader;
reader.open(stream);
temp->read(reader);
trie->trie_.swap(temp);
return stream;
}
static std::ostream &write(std::ostream &stream, const Trie &trie) {
MARISA_THROW_IF(trie.trie_.get() == NULL, MARISA_STATE_ERROR);
grimoire::Writer writer;
writer.open(stream);
trie.trie_->write(writer);
return stream;
}
};
void fread(std::FILE *file, Trie *trie) {
MARISA_THROW_IF(file == NULL, MARISA_NULL_ERROR);
MARISA_THROW_IF(trie == NULL, MARISA_NULL_ERROR);
TrieIO::fread(file, trie);
}
void fwrite(std::FILE *file, const Trie &trie) {
MARISA_THROW_IF(file == NULL, MARISA_NULL_ERROR);
TrieIO::fwrite(file, trie);
}
std::istream &read(std::istream &stream, Trie *trie) {
MARISA_THROW_IF(trie == NULL, MARISA_NULL_ERROR);
return TrieIO::read(stream, trie);
}
std::ostream &write(std::ostream &stream, const Trie &trie) {
return TrieIO::write(stream, trie);
}
std::istream &operator>>(std::istream &stream, Trie &trie) {
return read(stream, &trie);
}
std::ostream &operator<<(std::ostream &stream, const Trie &trie) {
return write(stream, trie);
}
} // namespace marisa
<commit_msg>Got rid of heap allocated byte buffer to prevent the possibility of memory leak.<commit_after>#include "stdio.h"
#include "iostream.h"
#include "trie.h"
#include "grimoire/trie.h"
namespace marisa {
Trie::Trie() : trie_() {}
Trie::~Trie() {}
void Trie::build(Keyset &keyset, int config_flags) {
scoped_ptr<grimoire::LoudsTrie> temp(new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
temp->build(keyset, config_flags);
trie_.swap(temp);
}
void Trie::mmap(const char *filename) {
MARISA_THROW_IF(filename == NULL, MARISA_NULL_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Mapper mapper;
mapper.open(filename);
temp->map(mapper);
trie_.swap(temp);
}
void Trie::map(const void *ptr, std::size_t size) {
MARISA_THROW_IF((ptr == NULL) && (size != 0), MARISA_NULL_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Mapper mapper;
mapper.open(ptr, size);
temp->map(mapper);
trie_.swap(temp);
}
void Trie::load(const char *filename) {
MARISA_THROW_IF(filename == NULL, MARISA_NULL_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Reader reader;
reader.open(filename);
temp->read(reader);
trie_.swap(temp);
}
void Trie::read(int fd) {
MARISA_THROW_IF(fd == -1, MARISA_CODE_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Reader reader;
reader.open(fd);
temp->read(reader);
trie_.swap(temp);
}
void Trie::save(const char *filename) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
MARISA_THROW_IF(filename == NULL, MARISA_NULL_ERROR);
grimoire::Writer writer;
writer.open(filename);
trie_->write(writer);
}
void Trie::write(int fd) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
MARISA_THROW_IF(fd == -1, MARISA_CODE_ERROR);
grimoire::Writer writer;
writer.open(fd);
trie_->write(writer);
}
bool Trie::lookup(Agent &agent) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
if (!agent.has_state()) {
agent.init_state();
}
return trie_->lookup(agent);
}
void Trie::reverse_lookup(Agent &agent) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
if (!agent.has_state()) {
agent.init_state();
}
trie_->reverse_lookup(agent);
}
bool Trie::common_prefix_search(Agent &agent) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
if (!agent.has_state()) {
agent.init_state();
}
return trie_->common_prefix_search(agent);
}
bool Trie::predictive_search(Agent &agent) const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
if (!agent.has_state()) {
agent.init_state();
}
return trie_->predictive_search(agent);
}
std::size_t Trie::num_tries() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->num_tries();
}
std::size_t Trie::num_keys() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->num_keys();
}
std::size_t Trie::num_nodes() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->num_nodes();
}
TailMode Trie::tail_mode() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->tail_mode();
}
NodeOrder Trie::node_order() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->node_order();
}
bool Trie::empty() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->empty();
}
std::size_t Trie::size() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->size();
}
std::size_t Trie::total_size() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->total_size();
}
std::size_t Trie::io_size() const {
MARISA_THROW_IF(trie_.get() == NULL, MARISA_STATE_ERROR);
return trie_->io_size();
}
void Trie::clear() {
Trie().swap(*this);
}
void Trie::swap(Trie &rhs) {
trie_.swap(rhs.trie_);
}
BytesTrie::BytesTrie() {
// fill in this constructor
}
/*
* Return a list of payloads (as byte objects) for a given key.
*/
void BytesTrie::get(std::vector< std::vector<char> > *results, const char *prefix) {
// allocate a new buffer
int b_prefix_len = strlen(prefix)+2;
char b_prefix[b_prefix_len];
strcpy(b_prefix, prefix);
b_prefix[b_prefix_len-2] = 0xff; // Default value separator
b_prefix[b_prefix_len-1] = 0x00; // Default value separator
size_t prefix_len = strlen(b_prefix);
marisa::Agent ag;
ag.set_query(b_prefix);
while (this->predictive_search(ag)) {
// we need to copy the char* into a vector<char> to store
// a byte array
const char *tmp = ag.key().ptr()+b_prefix_len-1;
std::vector<char> byte_array(tmp, tmp+strlen(tmp));
results->push_back(byte_array);
}
}
RecordTrie::RecordTrie(const char *fmt) {
_fmt.assign(fmt, strlen(fmt));
}
void RecordTrie::getRecord(std::vector<marisa::Record> *result, const char* b_prefix) {
// TODO:
}
} // namespace marisa
#include <iostream>
namespace marisa {
class TrieIO {
public:
static void fread(std::FILE *file, Trie *trie) {
MARISA_THROW_IF(trie == NULL, MARISA_NULL_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(
new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Reader reader;
reader.open(file);
temp->read(reader);
trie->trie_.swap(temp);
}
static void fwrite(std::FILE *file, const Trie &trie) {
MARISA_THROW_IF(file == NULL, MARISA_NULL_ERROR);
MARISA_THROW_IF(trie.trie_.get() == NULL, MARISA_STATE_ERROR);
grimoire::Writer writer;
writer.open(file);
trie.trie_->write(writer);
}
static std::istream &read(std::istream &stream, Trie *trie) {
MARISA_THROW_IF(trie == NULL, MARISA_NULL_ERROR);
scoped_ptr<grimoire::LoudsTrie> temp(
new (std::nothrow) grimoire::LoudsTrie);
MARISA_THROW_IF(temp.get() == NULL, MARISA_MEMORY_ERROR);
grimoire::Reader reader;
reader.open(stream);
temp->read(reader);
trie->trie_.swap(temp);
return stream;
}
static std::ostream &write(std::ostream &stream, const Trie &trie) {
MARISA_THROW_IF(trie.trie_.get() == NULL, MARISA_STATE_ERROR);
grimoire::Writer writer;
writer.open(stream);
trie.trie_->write(writer);
return stream;
}
};
void fread(std::FILE *file, Trie *trie) {
MARISA_THROW_IF(file == NULL, MARISA_NULL_ERROR);
MARISA_THROW_IF(trie == NULL, MARISA_NULL_ERROR);
TrieIO::fread(file, trie);
}
void fwrite(std::FILE *file, const Trie &trie) {
MARISA_THROW_IF(file == NULL, MARISA_NULL_ERROR);
TrieIO::fwrite(file, trie);
}
std::istream &read(std::istream &stream, Trie *trie) {
MARISA_THROW_IF(trie == NULL, MARISA_NULL_ERROR);
return TrieIO::read(stream, trie);
}
std::ostream &write(std::ostream &stream, const Trie &trie) {
return TrieIO::write(stream, trie);
}
std::istream &operator>>(std::istream &stream, Trie &trie) {
return read(stream, &trie);
}
std::ostream &operator<<(std::ostream &stream, const Trie &trie) {
return write(stream, trie);
}
} // namespace marisa
<|endoftext|>
|
<commit_before>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2021, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <gtest/gtest.h>
#include <mrpt/hwdrivers/CVelodyneScanner.h>
#include <mrpt/system/filesystem.h>
#include <test_mrpt_common.h>
using namespace mrpt;
using namespace mrpt::hwdrivers;
using namespace std;
#include <mrpt/config.h>
#if MRPT_HAS_LIBPCAP
TEST(CVelodyneScanner, sample_vlp16_dataset)
{
const string fil =
UNITTEST_BASEDIR + string("/tests/sample_velodyne_vlp16_gps.pcap");
if (!mrpt::system::fileExists(fil))
{
std::cerr << "WARNING: Skipping test due to missing file: " << fil
<< "\n";
return;
}
CVelodyneScanner velodyne;
velodyne.setModelName(mrpt::hwdrivers::CVelodyneScanner::VLP16);
velodyne.setPCAPInputFile(fil);
velodyne.setPCAPInputFileReadOnce(true);
velodyne.enableVerbose(false);
velodyne.setPCAPVerbosity(false);
velodyne.initialize();
size_t nScans = 0, nGPS = 0;
bool rx_ok = true;
for (size_t i = 0; i < 1000 && rx_ok; i++)
{
mrpt::obs::CObservationVelodyneScan::Ptr scan;
mrpt::obs::CObservationGPS::Ptr gps;
rx_ok = velodyne.getNextObservation(scan, gps);
if (scan)
{
nScans++;
scan->generatePointCloud();
}
if (gps) nGPS++;
};
EXPECT_EQ(nScans, 4U);
EXPECT_GT(nGPS, 0U);
}
TEST(CVelodyneScanner, sample_hdl32_dataset)
{
const string fil =
UNITTEST_BASEDIR + string("/tests/sample_velodyne_hdl32.pcap");
if (!mrpt::system::fileExists(fil))
{
std::cerr << "WARNING: Skipping test due to missing file: " << fil
<< "\n";
return;
}
CVelodyneScanner velodyne;
velodyne.setModelName(mrpt::hwdrivers::CVelodyneScanner::HDL32);
velodyne.setPCAPInputFile(fil);
velodyne.setPCAPInputFileReadOnce(true);
velodyne.enableVerbose(false);
velodyne.setPCAPVerbosity(false);
velodyne.initialize();
size_t nScans = 0;
// size_t nGPS=0;
bool rx_ok = true;
for (size_t i = 0; i < 1000 && rx_ok; i++)
{
mrpt::obs::CObservationVelodyneScan::Ptr scan;
mrpt::obs::CObservationGPS::Ptr gps;
rx_ok = velodyne.getNextObservation(scan, gps);
if (scan) nScans++;
// if (gps) nGPS++;
};
EXPECT_EQ(nScans, 3U);
}
#endif // MRPT_HAS_LIBPCAP
<commit_msg>fix failing unit tests if build w/o tinyxml2<commit_after>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2021, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <gtest/gtest.h>
#include <mrpt/hwdrivers/CVelodyneScanner.h>
#include <mrpt/system/filesystem.h>
#include <test_mrpt_common.h>
using namespace mrpt;
using namespace mrpt::hwdrivers;
using namespace std;
#include <mrpt/config.h>
#if MRPT_HAS_LIBPCAP && MRPT_HAS_TINYXML2
TEST(CVelodyneScanner, sample_vlp16_dataset)
{
const string fil =
UNITTEST_BASEDIR + string("/tests/sample_velodyne_vlp16_gps.pcap");
if (!mrpt::system::fileExists(fil))
{
std::cerr << "WARNING: Skipping test due to missing file: " << fil
<< "\n";
return;
}
CVelodyneScanner velodyne;
velodyne.setModelName(mrpt::hwdrivers::CVelodyneScanner::VLP16);
velodyne.setPCAPInputFile(fil);
velodyne.setPCAPInputFileReadOnce(true);
velodyne.enableVerbose(false);
velodyne.setPCAPVerbosity(false);
velodyne.initialize();
size_t nScans = 0, nGPS = 0;
bool rx_ok = true;
for (size_t i = 0; i < 1000 && rx_ok; i++)
{
mrpt::obs::CObservationVelodyneScan::Ptr scan;
mrpt::obs::CObservationGPS::Ptr gps;
rx_ok = velodyne.getNextObservation(scan, gps);
if (scan)
{
nScans++;
scan->generatePointCloud();
}
if (gps) nGPS++;
};
EXPECT_EQ(nScans, 4U);
EXPECT_GT(nGPS, 0U);
}
TEST(CVelodyneScanner, sample_hdl32_dataset)
{
const string fil =
UNITTEST_BASEDIR + string("/tests/sample_velodyne_hdl32.pcap");
if (!mrpt::system::fileExists(fil))
{
std::cerr << "WARNING: Skipping test due to missing file: " << fil
<< "\n";
return;
}
CVelodyneScanner velodyne;
velodyne.setModelName(mrpt::hwdrivers::CVelodyneScanner::HDL32);
velodyne.setPCAPInputFile(fil);
velodyne.setPCAPInputFileReadOnce(true);
velodyne.enableVerbose(false);
velodyne.setPCAPVerbosity(false);
velodyne.initialize();
size_t nScans = 0;
// size_t nGPS=0;
bool rx_ok = true;
for (size_t i = 0; i < 1000 && rx_ok; i++)
{
mrpt::obs::CObservationVelodyneScan::Ptr scan;
mrpt::obs::CObservationGPS::Ptr gps;
rx_ok = velodyne.getNextObservation(scan, gps);
if (scan) nScans++;
// if (gps) nGPS++;
};
EXPECT_EQ(nScans, 3U);
}
#endif // MRPT_HAS_LIBPCAP
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** Copyright (c) 2014 BogDan Vatra <[email protected]>
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "androidpackagecreationwidget.h"
#include "androidpackagecreationstep.h"
#include "androidconfigurations.h"
#include "androidcreatekeystorecertificate.h"
#include "androidmanager.h"
#include "androiddeploystep.h"
#include "androidglobal.h"
#include "ui_androidpackagecreationwidget.h"
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <qmakeprojectmanager/qmakebuildconfiguration.h>
#include <qmakeprojectmanager/qmakestep.h>
#include <QTimer>
#include <QFileDialog>
#include <QFileSystemWatcher>
#include <QMessageBox>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
namespace Android {
namespace Internal {
using namespace ProjectExplorer;
using namespace QmakeProjectManager;
///////////////////////////// CheckModel /////////////////////////////
CheckModel::CheckModel(QObject *parent)
: QAbstractListModel(parent)
{
}
void CheckModel::setAvailableItems(const QStringList &items)
{
beginResetModel();
m_availableItems = items;
endResetModel();
}
void CheckModel::setCheckedItems(const QStringList &items)
{
m_checkedItems = items;
if (rowCount())
emit dataChanged(index(0), index(rowCount()-1));
}
const QStringList &CheckModel::checkedItems()
{
return m_checkedItems;
}
QVariant CheckModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
switch (role) {
case Qt::CheckStateRole:
return m_checkedItems.contains(m_availableItems.at(index.row())) ? Qt::Checked : Qt::Unchecked;
case Qt::DisplayRole:
return m_availableItems.at(index.row());
}
return QVariant();
}
void CheckModel::moveUp(int index)
{
beginMoveRows(QModelIndex(), index, index, QModelIndex(), index - 1);
const QString &item1 = m_availableItems[index];
const QString &item2 = m_availableItems[index - 1];
m_availableItems.swap(index, index - 1);
index = m_checkedItems.indexOf(item1);
int index2 = m_checkedItems.indexOf(item2);
if (index > -1 && index2 > -1)
m_checkedItems.swap(index, index2);
endMoveRows();
}
bool CheckModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::CheckStateRole || !index.isValid())
return false;
if (value.toInt() == Qt::Checked)
m_checkedItems.append(m_availableItems.at(index.row()));
else
m_checkedItems.removeAll(m_availableItems.at(index.row()));
emit dataChanged(index, index);
return true;
}
int CheckModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_availableItems.count();
}
Qt::ItemFlags CheckModel::flags(const QModelIndex &/*index*/) const
{
return Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled;
}
///////////////////////////// AndroidPackageCreationWidget /////////////////////////////
AndroidPackageCreationWidget::AndroidPackageCreationWidget(AndroidPackageCreationStep *step)
: ProjectExplorer::BuildStepConfigWidget(),
m_step(step),
m_ui(new Ui::AndroidPackageCreationWidget),
m_fileSystemWatcher(new QFileSystemWatcher(this)),
m_currentBuildConfiguration(0)
{
m_qtLibsModel = new CheckModel(this);
m_prebundledLibs = new CheckModel(this);
m_ui->setupUi(this);
m_ui->signingDebugWarningIcon->hide();
m_ui->signingDebugWarningLabel->hide();
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QTimer::singleShot(50, this, SLOT(initGui()));
connect(m_step, SIGNAL(updateRequiredLibrariesModels()), SLOT(updateRequiredLibrariesModels()));
}
void AndroidPackageCreationWidget::initGui()
{
updateAndroidProjectInfo();
ProjectExplorer::Target *target = m_step->target();
m_fileSystemWatcher->addPath(AndroidManager::dirPath(target).toString());
m_fileSystemWatcher->addPath(AndroidManager::manifestPath(target).toString());
m_fileSystemWatcher->addPath(AndroidManager::srcPath(target).toString());
connect(m_fileSystemWatcher, SIGNAL(directoryChanged(QString)),
this, SLOT(updateAndroidProjectInfo()));
connect(m_fileSystemWatcher, SIGNAL(fileChanged(QString)), this,
SLOT(updateAndroidProjectInfo()));
connect(m_ui->targetSDKComboBox, SIGNAL(activated(QString)), SLOT(setTargetSDK(QString)));
connect(m_qtLibsModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(setQtLibs(QModelIndex,QModelIndex)));
connect(m_prebundledLibs, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(setPrebundledLibs(QModelIndex,QModelIndex)));
connect(m_ui->prebundledLibsListView, SIGNAL(activated(QModelIndex)), SLOT(prebundledLibSelected(QModelIndex)));
connect(m_ui->prebundledLibsListView, SIGNAL(clicked(QModelIndex)), SLOT(prebundledLibSelected(QModelIndex)));
connect(m_ui->upPushButton, SIGNAL(clicked()), SLOT(prebundledLibMoveUp()));
connect(m_ui->downPushButton, SIGNAL(clicked()), SLOT(prebundledLibMoveDown()));
connect(m_ui->readInfoPushButton, SIGNAL(clicked()), SLOT(readElfInfo()));
m_ui->qtLibsListView->setModel(m_qtLibsModel);
m_ui->prebundledLibsListView->setModel(m_prebundledLibs);
m_ui->KeystoreLocationLineEdit->setText(m_step->keystorePath().toUserOutput());
// Make the buildconfiguration emit a evironmentChanged() signal
// TODO find a better way
QmakeBuildConfiguration *bc = qobject_cast<QmakeBuildConfiguration *>(m_step->target()->activeBuildConfiguration());
if (!bc)
return;
bool use = bc->useSystemEnvironment();
bc->setUseSystemEnvironment(!use);
bc->setUseSystemEnvironment(use);
activeBuildConfigurationChanged();
connect(m_step->target(), SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
this, SLOT(activeBuildConfigurationChanged()));
}
void AndroidPackageCreationWidget::updateSigningWarning()
{
QmakeBuildConfiguration *bc = qobject_cast<QmakeBuildConfiguration *>(m_step->target()->activeBuildConfiguration());
bool debug = bc && (bc->qmakeBuildConfiguration() & QtSupport::BaseQtVersion::DebugBuild);
if (m_step->signPackage() && debug) {
m_ui->signingDebugWarningIcon->setVisible(true);
m_ui->signingDebugWarningLabel->setVisible(true);
} else {
m_ui->signingDebugWarningIcon->setVisible(false);
m_ui->signingDebugWarningLabel->setVisible(false);
}
}
void AndroidPackageCreationWidget::activeBuildConfigurationChanged()
{
if (m_currentBuildConfiguration)
disconnect(m_currentBuildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
this, SLOT(updateSigningWarning()));
updateSigningWarning();
QmakeBuildConfiguration *bc = qobject_cast<QmakeBuildConfiguration *>(m_step->target()->activeBuildConfiguration());
m_currentBuildConfiguration = bc;
if (bc)
connect(bc, SIGNAL(qmakeBuildConfigurationChanged()), this, SLOT(updateSigningWarning()));
m_currentBuildConfiguration = bc;
}
void AndroidPackageCreationWidget::updateAndroidProjectInfo()
{
ProjectExplorer::Target *target = m_step->target();
m_ui->targetSDKComboBox->clear();
int minApiLevel = 4;
if (QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(target->kit()))
if (qt->qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0))
minApiLevel = 9;
QStringList targets = AndroidConfigurations::currentConfig().sdkTargets(minApiLevel);
m_ui->targetSDKComboBox->addItems(targets);
m_ui->targetSDKComboBox->setCurrentIndex(targets.indexOf(AndroidManager::buildTargetSDK(target)));
m_qtLibsModel->setAvailableItems(AndroidManager::availableQtLibs(target));
m_qtLibsModel->setCheckedItems(AndroidManager::qtLibs(target));
m_prebundledLibs->setAvailableItems(AndroidManager::availablePrebundledLibs(target));
m_prebundledLibs->setCheckedItems(AndroidManager::prebundledLibs(target));
}
void AndroidPackageCreationWidget::setTargetSDK(const QString &sdk)
{
AndroidManager::setBuildTargetSDK(m_step->target(), sdk);
QmakeBuildConfiguration *bc = qobject_cast<QmakeBuildConfiguration *>(m_step->target()->activeBuildConfiguration());
if (!bc)
return;
QMakeStep *qs = bc->qmakeStep();
if (!qs)
return;
qs->setForced(true);
BuildManager::buildList(bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_CLEAN),
ProjectExplorerPlugin::displayNameForStepId(ProjectExplorer::Constants::BUILDSTEPS_CLEAN));
BuildManager::appendStep(qs, ProjectExplorerPlugin::displayNameForStepId(ProjectExplorer::Constants::BUILDSTEPS_CLEAN));
bc->setSubNodeBuild(0);
// Make the buildconfiguration emit a evironmentChanged() signal
// TODO find a better way
bool use = bc->useSystemEnvironment();
bc->setUseSystemEnvironment(!use);
bc->setUseSystemEnvironment(use);
}
void AndroidPackageCreationWidget::setQtLibs(QModelIndex, QModelIndex)
{
AndroidManager::setQtLibs(m_step->target(), m_qtLibsModel->checkedItems());
AndroidDeployStep * const deployStep = AndroidGlobal::buildStep<AndroidDeployStep>(m_step->target()->activeDeployConfiguration());
if (deployStep->deployAction() == AndroidDeployStep::DeployLocal
|| deployStep->deployAction() == AndroidDeployStep::BundleLibraries)
AndroidManager::updateDeploymentSettings(m_step->target());
}
void AndroidPackageCreationWidget::setPrebundledLibs(QModelIndex, QModelIndex)
{
AndroidManager::setPrebundledLibs(m_step->target(), m_prebundledLibs->checkedItems());
AndroidDeployStep * const deployStep = AndroidGlobal::buildStep<AndroidDeployStep>(m_step->target()->activeDeployConfiguration());
if (deployStep->deployAction() == AndroidDeployStep::DeployLocal
|| deployStep->deployAction() == AndroidDeployStep::BundleLibraries)
AndroidManager::updateDeploymentSettings(m_step->target());
}
void AndroidPackageCreationWidget::prebundledLibSelected(const QModelIndex &index)
{
m_ui->upPushButton->setEnabled(false);
m_ui->downPushButton->setEnabled(false);
if (!index.isValid())
return;
if (index.row() > 0)
m_ui->upPushButton->setEnabled(true);
if (index.row() < m_prebundledLibs->rowCount(QModelIndex()) - 1)
m_ui->downPushButton->setEnabled(true);
}
void AndroidPackageCreationWidget::prebundledLibMoveUp()
{
const QModelIndex &index = m_ui->prebundledLibsListView->currentIndex();
if (index.isValid())
m_prebundledLibs->moveUp(index.row());
}
void AndroidPackageCreationWidget::prebundledLibMoveDown()
{
const QModelIndex &index = m_ui->prebundledLibsListView->currentIndex();
if (index.isValid())
m_prebundledLibs->moveUp(index.row() + 1);
}
void AndroidPackageCreationWidget::updateRequiredLibrariesModels()
{
m_qtLibsModel->setCheckedItems(AndroidManager::qtLibs(m_step->target()));
m_prebundledLibs->setCheckedItems(AndroidManager::prebundledLibs(m_step->target()));
}
void AndroidPackageCreationWidget::readElfInfo()
{
m_step->checkRequiredLibraries();
}
QString AndroidPackageCreationWidget::summaryText() const
{
return tr("<b>Package configurations</b>");
}
QString AndroidPackageCreationWidget::displayName() const
{
return m_step->displayName();
}
void AndroidPackageCreationWidget::setCertificates()
{
QAbstractItemModel *certificates = m_step->keystoreCertificates();
m_ui->signPackageCheckBox->setChecked(certificates);
m_ui->certificatesAliasComboBox->setModel(certificates);
}
void AndroidPackageCreationWidget::on_signPackageCheckBox_toggled(bool checked)
{
m_step->setSignPackage(checked);
updateSigningWarning();
if (!checked)
return;
if (!m_step->keystorePath().isEmpty())
setCertificates();
}
void AndroidPackageCreationWidget::on_KeystoreCreatePushButton_clicked()
{
AndroidCreateKeystoreCertificate d;
if (d.exec() != QDialog::Accepted)
return;
m_ui->KeystoreLocationLineEdit->setText(d.keystoreFilePath().toUserOutput());
m_step->setKeystorePath(d.keystoreFilePath());
m_step->setKeystorePassword(d.keystorePassword());
m_step->setCertificateAlias(d.certificateAlias());
m_step->setCertificatePassword(d.certificatePassword());
setCertificates();
}
void AndroidPackageCreationWidget::on_KeystoreLocationPushButton_clicked()
{
Utils::FileName keystorePath = m_step->keystorePath();
if (keystorePath.isEmpty())
keystorePath = Utils::FileName::fromString(QDir::homePath());
Utils::FileName file = Utils::FileName::fromString(QFileDialog::getOpenFileName(this, tr("Select keystore file"), keystorePath.toString(), tr("Keystore files (*.keystore *.jks)")));
if (file.isEmpty())
return;
m_ui->KeystoreLocationLineEdit->setText(file.toUserOutput());
m_step->setKeystorePath(file);
m_ui->signPackageCheckBox->setChecked(false);
}
void AndroidPackageCreationWidget::on_certificatesAliasComboBox_activated(const QString &alias)
{
if (alias.length())
m_step->setCertificateAlias(alias);
}
void AndroidPackageCreationWidget::on_certificatesAliasComboBox_currentIndexChanged(const QString &alias)
{
if (alias.length())
m_step->setCertificateAlias(alias);
}
void AndroidPackageCreationWidget::on_openPackageLocationCheckBox_toggled(bool checked)
{
m_step->setOpenPackageLocation(checked);
}
} // namespace Internal
} // namespace Android
<commit_msg>Use native labels for "Browse" button<commit_after>/**************************************************************************
**
** Copyright (c) 2014 BogDan Vatra <[email protected]>
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "androidpackagecreationwidget.h"
#include "androidpackagecreationstep.h"
#include "androidconfigurations.h"
#include "androidcreatekeystorecertificate.h"
#include "androidmanager.h"
#include "androiddeploystep.h"
#include "androidglobal.h"
#include "ui_androidpackagecreationwidget.h"
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <qmakeprojectmanager/qmakebuildconfiguration.h>
#include <qmakeprojectmanager/qmakestep.h>
#include <utils/pathchooser.h>
#include <QTimer>
#include <QFileDialog>
#include <QFileSystemWatcher>
#include <QMessageBox>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
namespace Android {
namespace Internal {
using namespace ProjectExplorer;
using namespace QmakeProjectManager;
///////////////////////////// CheckModel /////////////////////////////
CheckModel::CheckModel(QObject *parent)
: QAbstractListModel(parent)
{
}
void CheckModel::setAvailableItems(const QStringList &items)
{
beginResetModel();
m_availableItems = items;
endResetModel();
}
void CheckModel::setCheckedItems(const QStringList &items)
{
m_checkedItems = items;
if (rowCount())
emit dataChanged(index(0), index(rowCount()-1));
}
const QStringList &CheckModel::checkedItems()
{
return m_checkedItems;
}
QVariant CheckModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
switch (role) {
case Qt::CheckStateRole:
return m_checkedItems.contains(m_availableItems.at(index.row())) ? Qt::Checked : Qt::Unchecked;
case Qt::DisplayRole:
return m_availableItems.at(index.row());
}
return QVariant();
}
void CheckModel::moveUp(int index)
{
beginMoveRows(QModelIndex(), index, index, QModelIndex(), index - 1);
const QString &item1 = m_availableItems[index];
const QString &item2 = m_availableItems[index - 1];
m_availableItems.swap(index, index - 1);
index = m_checkedItems.indexOf(item1);
int index2 = m_checkedItems.indexOf(item2);
if (index > -1 && index2 > -1)
m_checkedItems.swap(index, index2);
endMoveRows();
}
bool CheckModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::CheckStateRole || !index.isValid())
return false;
if (value.toInt() == Qt::Checked)
m_checkedItems.append(m_availableItems.at(index.row()));
else
m_checkedItems.removeAll(m_availableItems.at(index.row()));
emit dataChanged(index, index);
return true;
}
int CheckModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_availableItems.count();
}
Qt::ItemFlags CheckModel::flags(const QModelIndex &/*index*/) const
{
return Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled;
}
///////////////////////////// AndroidPackageCreationWidget /////////////////////////////
AndroidPackageCreationWidget::AndroidPackageCreationWidget(AndroidPackageCreationStep *step)
: ProjectExplorer::BuildStepConfigWidget(),
m_step(step),
m_ui(new Ui::AndroidPackageCreationWidget),
m_fileSystemWatcher(new QFileSystemWatcher(this)),
m_currentBuildConfiguration(0)
{
m_qtLibsModel = new CheckModel(this);
m_prebundledLibs = new CheckModel(this);
m_ui->setupUi(this);
m_ui->KeystoreLocationPushButton->setText(tr(Utils::PathChooser::browseButtonLabel));
m_ui->signingDebugWarningIcon->hide();
m_ui->signingDebugWarningLabel->hide();
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QTimer::singleShot(50, this, SLOT(initGui()));
connect(m_step, SIGNAL(updateRequiredLibrariesModels()), SLOT(updateRequiredLibrariesModels()));
}
void AndroidPackageCreationWidget::initGui()
{
updateAndroidProjectInfo();
ProjectExplorer::Target *target = m_step->target();
m_fileSystemWatcher->addPath(AndroidManager::dirPath(target).toString());
m_fileSystemWatcher->addPath(AndroidManager::manifestPath(target).toString());
m_fileSystemWatcher->addPath(AndroidManager::srcPath(target).toString());
connect(m_fileSystemWatcher, SIGNAL(directoryChanged(QString)),
this, SLOT(updateAndroidProjectInfo()));
connect(m_fileSystemWatcher, SIGNAL(fileChanged(QString)), this,
SLOT(updateAndroidProjectInfo()));
connect(m_ui->targetSDKComboBox, SIGNAL(activated(QString)), SLOT(setTargetSDK(QString)));
connect(m_qtLibsModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(setQtLibs(QModelIndex,QModelIndex)));
connect(m_prebundledLibs, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(setPrebundledLibs(QModelIndex,QModelIndex)));
connect(m_ui->prebundledLibsListView, SIGNAL(activated(QModelIndex)), SLOT(prebundledLibSelected(QModelIndex)));
connect(m_ui->prebundledLibsListView, SIGNAL(clicked(QModelIndex)), SLOT(prebundledLibSelected(QModelIndex)));
connect(m_ui->upPushButton, SIGNAL(clicked()), SLOT(prebundledLibMoveUp()));
connect(m_ui->downPushButton, SIGNAL(clicked()), SLOT(prebundledLibMoveDown()));
connect(m_ui->readInfoPushButton, SIGNAL(clicked()), SLOT(readElfInfo()));
m_ui->qtLibsListView->setModel(m_qtLibsModel);
m_ui->prebundledLibsListView->setModel(m_prebundledLibs);
m_ui->KeystoreLocationLineEdit->setText(m_step->keystorePath().toUserOutput());
// Make the buildconfiguration emit a evironmentChanged() signal
// TODO find a better way
QmakeBuildConfiguration *bc = qobject_cast<QmakeBuildConfiguration *>(m_step->target()->activeBuildConfiguration());
if (!bc)
return;
bool use = bc->useSystemEnvironment();
bc->setUseSystemEnvironment(!use);
bc->setUseSystemEnvironment(use);
activeBuildConfigurationChanged();
connect(m_step->target(), SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
this, SLOT(activeBuildConfigurationChanged()));
}
void AndroidPackageCreationWidget::updateSigningWarning()
{
QmakeBuildConfiguration *bc = qobject_cast<QmakeBuildConfiguration *>(m_step->target()->activeBuildConfiguration());
bool debug = bc && (bc->qmakeBuildConfiguration() & QtSupport::BaseQtVersion::DebugBuild);
if (m_step->signPackage() && debug) {
m_ui->signingDebugWarningIcon->setVisible(true);
m_ui->signingDebugWarningLabel->setVisible(true);
} else {
m_ui->signingDebugWarningIcon->setVisible(false);
m_ui->signingDebugWarningLabel->setVisible(false);
}
}
void AndroidPackageCreationWidget::activeBuildConfigurationChanged()
{
if (m_currentBuildConfiguration)
disconnect(m_currentBuildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
this, SLOT(updateSigningWarning()));
updateSigningWarning();
QmakeBuildConfiguration *bc = qobject_cast<QmakeBuildConfiguration *>(m_step->target()->activeBuildConfiguration());
m_currentBuildConfiguration = bc;
if (bc)
connect(bc, SIGNAL(qmakeBuildConfigurationChanged()), this, SLOT(updateSigningWarning()));
m_currentBuildConfiguration = bc;
}
void AndroidPackageCreationWidget::updateAndroidProjectInfo()
{
ProjectExplorer::Target *target = m_step->target();
m_ui->targetSDKComboBox->clear();
int minApiLevel = 4;
if (QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(target->kit()))
if (qt->qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0))
minApiLevel = 9;
QStringList targets = AndroidConfigurations::currentConfig().sdkTargets(minApiLevel);
m_ui->targetSDKComboBox->addItems(targets);
m_ui->targetSDKComboBox->setCurrentIndex(targets.indexOf(AndroidManager::buildTargetSDK(target)));
m_qtLibsModel->setAvailableItems(AndroidManager::availableQtLibs(target));
m_qtLibsModel->setCheckedItems(AndroidManager::qtLibs(target));
m_prebundledLibs->setAvailableItems(AndroidManager::availablePrebundledLibs(target));
m_prebundledLibs->setCheckedItems(AndroidManager::prebundledLibs(target));
}
void AndroidPackageCreationWidget::setTargetSDK(const QString &sdk)
{
AndroidManager::setBuildTargetSDK(m_step->target(), sdk);
QmakeBuildConfiguration *bc = qobject_cast<QmakeBuildConfiguration *>(m_step->target()->activeBuildConfiguration());
if (!bc)
return;
QMakeStep *qs = bc->qmakeStep();
if (!qs)
return;
qs->setForced(true);
BuildManager::buildList(bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_CLEAN),
ProjectExplorerPlugin::displayNameForStepId(ProjectExplorer::Constants::BUILDSTEPS_CLEAN));
BuildManager::appendStep(qs, ProjectExplorerPlugin::displayNameForStepId(ProjectExplorer::Constants::BUILDSTEPS_CLEAN));
bc->setSubNodeBuild(0);
// Make the buildconfiguration emit a evironmentChanged() signal
// TODO find a better way
bool use = bc->useSystemEnvironment();
bc->setUseSystemEnvironment(!use);
bc->setUseSystemEnvironment(use);
}
void AndroidPackageCreationWidget::setQtLibs(QModelIndex, QModelIndex)
{
AndroidManager::setQtLibs(m_step->target(), m_qtLibsModel->checkedItems());
AndroidDeployStep * const deployStep = AndroidGlobal::buildStep<AndroidDeployStep>(m_step->target()->activeDeployConfiguration());
if (deployStep->deployAction() == AndroidDeployStep::DeployLocal
|| deployStep->deployAction() == AndroidDeployStep::BundleLibraries)
AndroidManager::updateDeploymentSettings(m_step->target());
}
void AndroidPackageCreationWidget::setPrebundledLibs(QModelIndex, QModelIndex)
{
AndroidManager::setPrebundledLibs(m_step->target(), m_prebundledLibs->checkedItems());
AndroidDeployStep * const deployStep = AndroidGlobal::buildStep<AndroidDeployStep>(m_step->target()->activeDeployConfiguration());
if (deployStep->deployAction() == AndroidDeployStep::DeployLocal
|| deployStep->deployAction() == AndroidDeployStep::BundleLibraries)
AndroidManager::updateDeploymentSettings(m_step->target());
}
void AndroidPackageCreationWidget::prebundledLibSelected(const QModelIndex &index)
{
m_ui->upPushButton->setEnabled(false);
m_ui->downPushButton->setEnabled(false);
if (!index.isValid())
return;
if (index.row() > 0)
m_ui->upPushButton->setEnabled(true);
if (index.row() < m_prebundledLibs->rowCount(QModelIndex()) - 1)
m_ui->downPushButton->setEnabled(true);
}
void AndroidPackageCreationWidget::prebundledLibMoveUp()
{
const QModelIndex &index = m_ui->prebundledLibsListView->currentIndex();
if (index.isValid())
m_prebundledLibs->moveUp(index.row());
}
void AndroidPackageCreationWidget::prebundledLibMoveDown()
{
const QModelIndex &index = m_ui->prebundledLibsListView->currentIndex();
if (index.isValid())
m_prebundledLibs->moveUp(index.row() + 1);
}
void AndroidPackageCreationWidget::updateRequiredLibrariesModels()
{
m_qtLibsModel->setCheckedItems(AndroidManager::qtLibs(m_step->target()));
m_prebundledLibs->setCheckedItems(AndroidManager::prebundledLibs(m_step->target()));
}
void AndroidPackageCreationWidget::readElfInfo()
{
m_step->checkRequiredLibraries();
}
QString AndroidPackageCreationWidget::summaryText() const
{
return tr("<b>Package configurations</b>");
}
QString AndroidPackageCreationWidget::displayName() const
{
return m_step->displayName();
}
void AndroidPackageCreationWidget::setCertificates()
{
QAbstractItemModel *certificates = m_step->keystoreCertificates();
m_ui->signPackageCheckBox->setChecked(certificates);
m_ui->certificatesAliasComboBox->setModel(certificates);
}
void AndroidPackageCreationWidget::on_signPackageCheckBox_toggled(bool checked)
{
m_step->setSignPackage(checked);
updateSigningWarning();
if (!checked)
return;
if (!m_step->keystorePath().isEmpty())
setCertificates();
}
void AndroidPackageCreationWidget::on_KeystoreCreatePushButton_clicked()
{
AndroidCreateKeystoreCertificate d;
if (d.exec() != QDialog::Accepted)
return;
m_ui->KeystoreLocationLineEdit->setText(d.keystoreFilePath().toUserOutput());
m_step->setKeystorePath(d.keystoreFilePath());
m_step->setKeystorePassword(d.keystorePassword());
m_step->setCertificateAlias(d.certificateAlias());
m_step->setCertificatePassword(d.certificatePassword());
setCertificates();
}
void AndroidPackageCreationWidget::on_KeystoreLocationPushButton_clicked()
{
Utils::FileName keystorePath = m_step->keystorePath();
if (keystorePath.isEmpty())
keystorePath = Utils::FileName::fromString(QDir::homePath());
Utils::FileName file = Utils::FileName::fromString(QFileDialog::getOpenFileName(this, tr("Select keystore file"), keystorePath.toString(), tr("Keystore files (*.keystore *.jks)")));
if (file.isEmpty())
return;
m_ui->KeystoreLocationLineEdit->setText(file.toUserOutput());
m_step->setKeystorePath(file);
m_ui->signPackageCheckBox->setChecked(false);
}
void AndroidPackageCreationWidget::on_certificatesAliasComboBox_activated(const QString &alias)
{
if (alias.length())
m_step->setCertificateAlias(alias);
}
void AndroidPackageCreationWidget::on_certificatesAliasComboBox_currentIndexChanged(const QString &alias)
{
if (alias.length())
m_step->setCertificateAlias(alias);
}
void AndroidPackageCreationWidget::on_openPackageLocationCheckBox_toggled(bool checked)
{
m_step->setOpenPackageLocation(checked);
}
} // namespace Internal
} // namespace Android
<|endoftext|>
|
<commit_before>//
// EigenJS.cpp
// ~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
#ifndef EIGENJS_COMPLEX_HPP
#define EIGENJS_COMPLEX_HPP
#include <node.h>
#include <v8.h>
#include <nan.h>
#include <complex>
#include <sstream>
#define EIGENJS_COMPLEX_CLASS_METHOD( NAME ) \
static NAN_METHOD( NAME ) { \
complex_type c; \
NanScope(); \
\
if ( args.Length() == 1 ) { \
if( is_complex( args[0] ) ) { \
new (&c) complex_type( \
node::ObjectWrap::Unwrap<Complex>( \
args[0]->ToObject() \
)->complex_ \
); \
} else if ( is_saclar( args[0] ) ) { \
new (&c) complex_type(args[0]->NumberValue(), 0); \
} \
\
const complex_type& NAME = std::NAME( c ); \
const element_type& real = NAME.real(); \
const element_type& imag = NAME.imag(); \
\
v8::Local<v8::Function> ctor = NanNew( constructor ); \
v8::Local<v8::Value> argv[] = { \
NanNew<v8::Number>( real ) \
, NanNew<v8::Number>( imag ) \
}; \
\
v8::Local<v8::Object> new_complex = ctor->NewInstance( \
sizeof( argv ) / sizeof( v8::Local<v8::Value> ) \
, argv \
); \
\
NanReturnValue( new_complex ); \
} \
\
NanReturnUndefined(); \
} \
/**/
namespace EigenJS {
template <typename ValueType>
class Complex : public node::ObjectWrap {
typedef ValueType element_type;
typedef std::complex<element_type> complex_type;
public:
static void Init(v8::Handle<v8::Object> exports) {
NanScope();
v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
tpl->SetClassName(NanNew("Complex"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "abs", abs);
NODE_SET_PROTOTYPE_METHOD(tpl, "arg", arg);
NODE_SET_PROTOTYPE_METHOD(tpl, "norm", norm);
NODE_SET_PROTOTYPE_METHOD(tpl, "conj", conj);
NODE_SET_PROTOTYPE_METHOD(tpl, "equals", equals);
NODE_SET_METHOD(tpl, "polar", polar);
NODE_SET_METHOD(tpl, "proj", proj);
NODE_SET_METHOD(tpl, "cos", cos);
NODE_SET_METHOD(tpl, "cosh", cosh);
NODE_SET_METHOD(tpl, "exp", exp);
NODE_SET_METHOD(tpl, "log", log);
NODE_SET_METHOD(tpl, "log10", log10);
NODE_SET_METHOD(tpl, "pow", pow);
NODE_SET_METHOD(tpl, "sin", sin);
NODE_SET_METHOD(tpl, "sinh", sinh);
NODE_SET_METHOD(tpl, "sqrt", sqrt);
NODE_SET_METHOD(tpl, "tan", tan);
NODE_SET_METHOD(tpl, "tanh", tanh);
NODE_SET_METHOD(tpl, "acos", acos);
NODE_SET_METHOD(tpl, "acosh", acosh);
NODE_SET_METHOD(tpl, "asin", asin);
NODE_SET_METHOD(tpl, "asinh", asinh);
NODE_SET_METHOD(tpl, "atan", atan);
NODE_SET_METHOD(tpl, "atanh", atanh);
NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);
v8::Local<v8::ObjectTemplate> proto = tpl->PrototypeTemplate();
proto->SetAccessor(NanNew("real"), get_real, set_real);
proto->SetAccessor(NanNew("imag"), get_imag, set_imag);
NanAssignPersistent(constructor, tpl->GetFunction());
exports->Set(NanNew("Complex"), tpl->GetFunction());
NanAssignPersistent(function_template, tpl);
}
static NAN_METHOD(abs) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanScope();
NanReturnValue(NanNew(std::abs(obj->complex_)));
}
static NAN_METHOD(arg) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanScope();
NanReturnValue(NanNew(std::arg(obj->complex_)));
}
static NAN_METHOD(norm) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanScope();
NanReturnValue(NanNew(std::norm(obj->complex_)));
}
static NAN_METHOD(conj) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
const complex_type& c = std::conj(obj->complex_);
const element_type& real = c.real();
const element_type& imag = c.imag();
NanScope();
v8::Local<v8::Function> ctor = NanNew(constructor);
v8::Local<v8::Value> argv[] = {
NanNew<v8::Number>(real)
, NanNew<v8::Number>(imag)
};
v8::Local<v8::Object> new_complex = ctor->NewInstance(
sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
);
NanReturnValue(new_complex);
}
static NAN_METHOD(polar) {
NanScope();
if (args.Length() == 2 &&
args[0]->IsNumber() &&
args[1]->IsNumber()) {
const element_type& rho = args[0]->NumberValue();
const element_type& theta = args[1]->NumberValue();
v8::Local<v8::Function> ctor = NanNew(constructor);
v8::Local<v8::Value> argv[] = {
NanNew<v8::Number>(rho)
, NanNew<v8::Number>(theta)
};
v8::Local<v8::Object> new_complex = ctor->NewInstance(
sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
);
NanReturnValue(new_complex);
}
NanReturnUndefined();
}
EIGENJS_COMPLEX_CLASS_METHOD(proj)
EIGENJS_COMPLEX_CLASS_METHOD(cos)
EIGENJS_COMPLEX_CLASS_METHOD(cosh)
EIGENJS_COMPLEX_CLASS_METHOD(exp)
EIGENJS_COMPLEX_CLASS_METHOD(log)
EIGENJS_COMPLEX_CLASS_METHOD(log10)
EIGENJS_COMPLEX_CLASS_METHOD(sin)
EIGENJS_COMPLEX_CLASS_METHOD(sinh)
EIGENJS_COMPLEX_CLASS_METHOD(sqrt)
EIGENJS_COMPLEX_CLASS_METHOD(tan)
EIGENJS_COMPLEX_CLASS_METHOD(tanh)
EIGENJS_COMPLEX_CLASS_METHOD(acos)
EIGENJS_COMPLEX_CLASS_METHOD(acosh)
EIGENJS_COMPLEX_CLASS_METHOD(asin)
EIGENJS_COMPLEX_CLASS_METHOD(asinh)
EIGENJS_COMPLEX_CLASS_METHOD(atan)
EIGENJS_COMPLEX_CLASS_METHOD(atanh)
static NAN_METHOD(pow) {
NanScope();
if (args.Length() == 2 &&
is_complex_or_saclar(args[0]) &&
is_complex_or_saclar(args[1])) {
const bool& arg0_is_complex = is_complex(args[0]);
const bool& arg1_is_complex = is_complex(args[1]);
const bool& arg0_is_scalar = is_saclar(args[0]);
const bool& arg1_is_scalar = is_saclar(args[1]);
complex_type c;
if (arg0_is_complex && arg1_is_complex) {
const Complex* obj0 =
node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());
const Complex* obj1 =
node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject());
c = std::pow(obj0->complex_, obj1->complex_);
} else if (arg0_is_complex && arg1_is_scalar) {
const Complex* obj0 =
node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());
const element_type& scalar1 = args[1]->NumberValue();
c = std::pow(obj0->complex_, scalar1);
} else if (arg0_is_scalar && arg1_is_complex) {
const element_type& scalar0 = args[0]->NumberValue();
const Complex* obj1 =
node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject());
c = std::pow(scalar0, obj1->complex_);
} else if (arg0_is_scalar && arg1_is_scalar) {
const element_type& scalar0 = args[0]->NumberValue();
const element_type& scalar1 = args[1]->NumberValue();
c = std::pow(scalar0, scalar1);
}
v8::Local<v8::Function> ctor = NanNew(constructor);
v8::Local<v8::Value> argv[] = {
NanNew<v8::Number>(c.real())
, NanNew<v8::Number>(c.imag())
};
v8::Local<v8::Object> new_complex = ctor->NewInstance(
sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
);
NanReturnValue(new_complex);
}
NanReturnUndefined();
}
static NAN_METHOD(equals) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanScope();
if (args.Length() == 1 && is_complex(args[0])) {
const Complex* rhs_obj =
node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());
NanReturnValue(NanNew<v8::Boolean>(obj->complex_ == rhs_obj->complex_));
}
NanReturnUndefined();
}
static NAN_METHOD(toString) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanScope();
std::ostringstream result;
result << obj->complex_;
NanReturnValue(NanNew(result.str().c_str()));
NanReturnUndefined();
}
static NAN_GETTER(get_real) {
NanScope();
if (!NanGetInternalFieldPointer(args.This(), 0))
NanReturnValue(args.This());
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanReturnValue(NanNew(obj->complex_.real()));
}
static NAN_SETTER(set_real) {
if (value->IsNumber()) {
Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
obj->complex_ = complex_type(
value->NumberValue()
, obj->complex_.imag()
);
}
}
static NAN_GETTER(get_imag) {
NanScope();
if (!NanGetInternalFieldPointer(args.This(), 0))
NanReturnValue(args.This());
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanReturnValue(NanNew(obj->complex_.imag()));
}
static NAN_SETTER(set_imag) {
if (value->IsNumber()) {
Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
obj->complex_ = complex_type(
obj->complex_.real()
, value->NumberValue()
);
}
}
private:
Complex(const element_type& real, const element_type& imag)
: complex_(real, imag)
{}
~Complex() {}
static NAN_METHOD(New) {
NanScope();
if (args.Length() < 2) {
NanThrowError("Tried creating complex without real and imag arguments");
NanReturnUndefined();
}
if (args.IsConstructCall()) {
const element_type& real = args[0]->NumberValue();
const element_type& imag = args[1]->NumberValue();
Complex* obj = new Complex(real, imag);
obj->Wrap(args.This());
NanReturnValue(args.This());
} else {
v8::Local<v8::Function> ctr = NanNew(constructor);
v8::Local<v8::Value> argv[] = {args[0], args[1]};
NanReturnValue(
ctr->NewInstance(
sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
)
);
}
}
static bool HasInstance(const v8::Handle<v8::Value>& value) {
NanScope();
v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template);
return tpl->HasInstance(value);
}
private:
static v8::Persistent<v8::FunctionTemplate> function_template;
static v8::Persistent<v8::Function> constructor;
private:
static bool is_complex(const v8::Handle<v8::Value>& arg) {
return HasInstance(arg) ? true : false;
}
static bool is_saclar(const v8::Handle<v8::Value>& arg) {
return arg->IsNumber() ? true : false;
}
static bool is_complex_or_saclar(const v8::Handle<v8::Value>& arg) {
return HasInstance(arg) || arg->IsNumber()
? true : false;
}
private:
complex_type complex_;
};
template<typename ValueType>
v8::Persistent<v8::FunctionTemplate> Complex<ValueType>::function_template;
template<typename ValueType>
v8::Persistent<v8::Function> Complex<ValueType>::constructor;
} // namespace EigenJS
#undef EIGENJS_COMPLEX_CLASS_METHOD
#endif // EIGENJS_COMPLEX_HPP
<commit_msg>src: added instance method 'Complex.add()'<commit_after>//
// EigenJS.cpp
// ~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
#ifndef EIGENJS_COMPLEX_HPP
#define EIGENJS_COMPLEX_HPP
#include <node.h>
#include <v8.h>
#include <nan.h>
#include <complex>
#include <sstream>
#define EIGENJS_COMPLEX_CLASS_METHOD( NAME ) \
static NAN_METHOD( NAME ) { \
complex_type c; \
NanScope(); \
\
if ( args.Length() == 1 ) { \
if( is_complex( args[0] ) ) { \
new (&c) complex_type( \
node::ObjectWrap::Unwrap<Complex>( \
args[0]->ToObject() \
)->complex_ \
); \
} else if ( is_saclar( args[0] ) ) { \
new (&c) complex_type(args[0]->NumberValue(), 0); \
} \
\
const complex_type& NAME = std::NAME( c ); \
const element_type& real = NAME.real(); \
const element_type& imag = NAME.imag(); \
\
v8::Local<v8::Function> ctor = NanNew( constructor ); \
v8::Local<v8::Value> argv[] = { \
NanNew<v8::Number>( real ) \
, NanNew<v8::Number>( imag ) \
}; \
\
v8::Local<v8::Object> new_complex = ctor->NewInstance( \
sizeof( argv ) / sizeof( v8::Local<v8::Value> ) \
, argv \
); \
\
NanReturnValue( new_complex ); \
} \
\
NanReturnUndefined(); \
} \
/**/
#define EIGENJS_COMPLEX_BINARY_OPERATOR( NAME, OP ) \
static NAN_METHOD( NAME ) { \
complex_type c; \
NanScope(); \
\
if ( args.Length() == 1 ) { \
if( is_complex( args[0] ) ) { \
new (&c) complex_type( \
node::ObjectWrap::Unwrap<Complex>( \
args[0]->ToObject() \
)->complex_ \
); \
} else if ( is_saclar( args[0] ) ) { \
new (&c) complex_type(args[0]->NumberValue(), 0); \
} \
\
const Complex* obj = node::ObjectWrap::Unwrap<Complex>( args.This() ); \
\
c = obj->complex_ OP c; \
\
v8::Local<v8::Function> ctor = NanNew( constructor ); \
v8::Local<v8::Value> argv[] = { \
NanNew<v8::Number>( c.real() ) \
, NanNew<v8::Number>( c.imag() ) \
}; \
\
v8::Local<v8::Object> new_complex = ctor->NewInstance( \
sizeof( argv ) / sizeof( v8::Local<v8::Value> ) \
, argv \
); \
\
NanReturnValue( new_complex ); \
} \
\
NanReturnUndefined(); \
} \
/**/
namespace EigenJS {
template <typename ValueType>
class Complex : public node::ObjectWrap {
typedef ValueType element_type;
typedef std::complex<element_type> complex_type;
public:
static void Init(v8::Handle<v8::Object> exports) {
NanScope();
v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
tpl->SetClassName(NanNew("Complex"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "abs", abs);
NODE_SET_PROTOTYPE_METHOD(tpl, "arg", arg);
NODE_SET_PROTOTYPE_METHOD(tpl, "norm", norm);
NODE_SET_PROTOTYPE_METHOD(tpl, "conj", conj);
NODE_SET_PROTOTYPE_METHOD(tpl, "equals", equals);
NODE_SET_PROTOTYPE_METHOD(tpl, "add", add);
NODE_SET_METHOD(tpl, "polar", polar);
NODE_SET_METHOD(tpl, "proj", proj);
NODE_SET_METHOD(tpl, "cos", cos);
NODE_SET_METHOD(tpl, "cosh", cosh);
NODE_SET_METHOD(tpl, "exp", exp);
NODE_SET_METHOD(tpl, "log", log);
NODE_SET_METHOD(tpl, "log10", log10);
NODE_SET_METHOD(tpl, "pow", pow);
NODE_SET_METHOD(tpl, "sin", sin);
NODE_SET_METHOD(tpl, "sinh", sinh);
NODE_SET_METHOD(tpl, "sqrt", sqrt);
NODE_SET_METHOD(tpl, "tan", tan);
NODE_SET_METHOD(tpl, "tanh", tanh);
NODE_SET_METHOD(tpl, "acos", acos);
NODE_SET_METHOD(tpl, "acosh", acosh);
NODE_SET_METHOD(tpl, "asin", asin);
NODE_SET_METHOD(tpl, "asinh", asinh);
NODE_SET_METHOD(tpl, "atan", atan);
NODE_SET_METHOD(tpl, "atanh", atanh);
NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);
v8::Local<v8::ObjectTemplate> proto = tpl->PrototypeTemplate();
proto->SetAccessor(NanNew("real"), get_real, set_real);
proto->SetAccessor(NanNew("imag"), get_imag, set_imag);
NanAssignPersistent(constructor, tpl->GetFunction());
exports->Set(NanNew("Complex"), tpl->GetFunction());
NanAssignPersistent(function_template, tpl);
}
static NAN_METHOD(abs) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanScope();
NanReturnValue(NanNew(std::abs(obj->complex_)));
}
static NAN_METHOD(arg) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanScope();
NanReturnValue(NanNew(std::arg(obj->complex_)));
}
static NAN_METHOD(norm) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanScope();
NanReturnValue(NanNew(std::norm(obj->complex_)));
}
static NAN_METHOD(conj) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
const complex_type& c = std::conj(obj->complex_);
const element_type& real = c.real();
const element_type& imag = c.imag();
NanScope();
v8::Local<v8::Function> ctor = NanNew(constructor);
v8::Local<v8::Value> argv[] = {
NanNew<v8::Number>(real)
, NanNew<v8::Number>(imag)
};
v8::Local<v8::Object> new_complex = ctor->NewInstance(
sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
);
NanReturnValue(new_complex);
}
static NAN_METHOD(polar) {
NanScope();
if (args.Length() == 2 &&
args[0]->IsNumber() &&
args[1]->IsNumber()) {
const element_type& rho = args[0]->NumberValue();
const element_type& theta = args[1]->NumberValue();
v8::Local<v8::Function> ctor = NanNew(constructor);
v8::Local<v8::Value> argv[] = {
NanNew<v8::Number>(rho)
, NanNew<v8::Number>(theta)
};
v8::Local<v8::Object> new_complex = ctor->NewInstance(
sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
);
NanReturnValue(new_complex);
}
NanReturnUndefined();
}
EIGENJS_COMPLEX_BINARY_OPERATOR(add, +)
EIGENJS_COMPLEX_CLASS_METHOD(proj)
EIGENJS_COMPLEX_CLASS_METHOD(cos)
EIGENJS_COMPLEX_CLASS_METHOD(cosh)
EIGENJS_COMPLEX_CLASS_METHOD(exp)
EIGENJS_COMPLEX_CLASS_METHOD(log)
EIGENJS_COMPLEX_CLASS_METHOD(log10)
EIGENJS_COMPLEX_CLASS_METHOD(sin)
EIGENJS_COMPLEX_CLASS_METHOD(sinh)
EIGENJS_COMPLEX_CLASS_METHOD(sqrt)
EIGENJS_COMPLEX_CLASS_METHOD(tan)
EIGENJS_COMPLEX_CLASS_METHOD(tanh)
EIGENJS_COMPLEX_CLASS_METHOD(acos)
EIGENJS_COMPLEX_CLASS_METHOD(acosh)
EIGENJS_COMPLEX_CLASS_METHOD(asin)
EIGENJS_COMPLEX_CLASS_METHOD(asinh)
EIGENJS_COMPLEX_CLASS_METHOD(atan)
EIGENJS_COMPLEX_CLASS_METHOD(atanh)
static NAN_METHOD(pow) {
NanScope();
if (args.Length() == 2 &&
is_complex_or_saclar(args[0]) &&
is_complex_or_saclar(args[1])) {
const bool& arg0_is_complex = is_complex(args[0]);
const bool& arg1_is_complex = is_complex(args[1]);
const bool& arg0_is_scalar = is_saclar(args[0]);
const bool& arg1_is_scalar = is_saclar(args[1]);
complex_type c;
if (arg0_is_complex && arg1_is_complex) {
const Complex* obj0 =
node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());
const Complex* obj1 =
node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject());
c = std::pow(obj0->complex_, obj1->complex_);
} else if (arg0_is_complex && arg1_is_scalar) {
const Complex* obj0 =
node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());
const element_type& scalar1 = args[1]->NumberValue();
c = std::pow(obj0->complex_, scalar1);
} else if (arg0_is_scalar && arg1_is_complex) {
const element_type& scalar0 = args[0]->NumberValue();
const Complex* obj1 =
node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject());
c = std::pow(scalar0, obj1->complex_);
} else if (arg0_is_scalar && arg1_is_scalar) {
const element_type& scalar0 = args[0]->NumberValue();
const element_type& scalar1 = args[1]->NumberValue();
c = std::pow(scalar0, scalar1);
}
v8::Local<v8::Function> ctor = NanNew(constructor);
v8::Local<v8::Value> argv[] = {
NanNew<v8::Number>(c.real())
, NanNew<v8::Number>(c.imag())
};
v8::Local<v8::Object> new_complex = ctor->NewInstance(
sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
);
NanReturnValue(new_complex);
}
NanReturnUndefined();
}
static NAN_METHOD(equals) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanScope();
if (args.Length() == 1 && is_complex(args[0])) {
const Complex* rhs_obj =
node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());
NanReturnValue(NanNew<v8::Boolean>(obj->complex_ == rhs_obj->complex_));
}
NanReturnUndefined();
}
static NAN_METHOD(toString) {
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanScope();
std::ostringstream result;
result << obj->complex_;
NanReturnValue(NanNew(result.str().c_str()));
NanReturnUndefined();
}
static NAN_GETTER(get_real) {
NanScope();
if (!NanGetInternalFieldPointer(args.This(), 0))
NanReturnValue(args.This());
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanReturnValue(NanNew(obj->complex_.real()));
}
static NAN_SETTER(set_real) {
if (value->IsNumber()) {
Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
obj->complex_ = complex_type(
value->NumberValue()
, obj->complex_.imag()
);
}
}
static NAN_GETTER(get_imag) {
NanScope();
if (!NanGetInternalFieldPointer(args.This(), 0))
NanReturnValue(args.This());
const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
NanReturnValue(NanNew(obj->complex_.imag()));
}
static NAN_SETTER(set_imag) {
if (value->IsNumber()) {
Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());
obj->complex_ = complex_type(
obj->complex_.real()
, value->NumberValue()
);
}
}
private:
Complex(const element_type& real, const element_type& imag)
: complex_(real, imag)
{}
~Complex() {}
static NAN_METHOD(New) {
NanScope();
if (args.Length() < 2) {
NanThrowError("Tried creating complex without real and imag arguments");
NanReturnUndefined();
}
if (args.IsConstructCall()) {
const element_type& real = args[0]->NumberValue();
const element_type& imag = args[1]->NumberValue();
Complex* obj = new Complex(real, imag);
obj->Wrap(args.This());
NanReturnValue(args.This());
} else {
v8::Local<v8::Function> ctr = NanNew(constructor);
v8::Local<v8::Value> argv[] = {args[0], args[1]};
NanReturnValue(
ctr->NewInstance(
sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
)
);
}
}
static bool HasInstance(const v8::Handle<v8::Value>& value) {
NanScope();
v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template);
return tpl->HasInstance(value);
}
private:
static v8::Persistent<v8::FunctionTemplate> function_template;
static v8::Persistent<v8::Function> constructor;
private:
static bool is_complex(const v8::Handle<v8::Value>& arg) {
return HasInstance(arg) ? true : false;
}
static bool is_saclar(const v8::Handle<v8::Value>& arg) {
return arg->IsNumber() ? true : false;
}
static bool is_complex_or_saclar(const v8::Handle<v8::Value>& arg) {
return HasInstance(arg) || arg->IsNumber()
? true : false;
}
private:
complex_type complex_;
};
template<typename ValueType>
v8::Persistent<v8::FunctionTemplate> Complex<ValueType>::function_template;
template<typename ValueType>
v8::Persistent<v8::Function> Complex<ValueType>::constructor;
} // namespace EigenJS
#undef EIGENJS_COMPLEX_CLASS_METHOD
#endif // EIGENJS_COMPLEX_HPP
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2007-2009 by Lothar May *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <net/socket_helper.h>
#include <net/senderthread.h>
#include <net/sendercallback.h>
#include <net/socket_msg.h>
#include <core/loghelper.h>
#include <cstring>
#include <cassert>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace std;
using boost::asio::ip::tcp;
#define SEND_ERROR_TIMEOUT_MSEC 20000
#define SEND_TIMEOUT_MSEC 10
#define SEND_QUEUE_SIZE 10000000
#define SEND_LOG_INTERVAL_SEC 60
typedef std::list<boost::shared_ptr<NetPacket> > SendDataList;
class SendDataManager : public boost::enable_shared_from_this<SendDataManager>
{
public:
SendDataManager(boost::shared_ptr<boost::asio::ip::tcp::socket> s)
: socket(s), writeInProgress(false)
{
}
void HandleWrite(const boost::system::error_code& error);
void AsyncSendNextPacket(bool handlerMode = false);
boost::shared_ptr<boost::asio::ip::tcp::socket> socket;
mutable boost::mutex dataMutex;
SendDataList list;
bool writeInProgress;
};
void
SendDataManager::HandleWrite(const boost::system::error_code& error)
{
// TODO error handling
AsyncSendNextPacket(true);
}
void
SendDataManager::AsyncSendNextPacket(bool handlerMode)
{
boost::mutex::scoped_lock lock(dataMutex);
if (!writeInProgress || handlerMode)
{
if (handlerMode)
list.pop_front();
if (!list.empty())
{
boost::shared_ptr<NetPacket> nextPacket = list.front();
boost::asio::async_write(
*socket,
boost::asio::buffer(nextPacket->GetRawData(),
nextPacket->GetLen()),
boost::bind(&SendDataManager::HandleWrite, shared_from_this(),
boost::asio::placeholders::error));
writeInProgress = true;
}
else
writeInProgress = false;
}
}
SenderThread::SenderThread(SenderCallback &cb, boost::shared_ptr<boost::asio::io_service> ioService)
: m_callback(cb), m_ioService(ioService)
{
}
SenderThread::~SenderThread()
{
}
void
SenderThread::Start()
{
Run();
}
void
SenderThread::SignalStop()
{
SignalTermination();
}
void
SenderThread::WaitStop()
{
Join(SENDER_THREAD_TERMINATE_TIMEOUT);
}
void
SenderThread::Send(boost::shared_ptr<SessionData> session, boost::shared_ptr<NetPacket> packet)
{
if (packet.get() && session.get())
{
boost::shared_ptr<SendDataManager> tmpManager;
{
// First: lock map of all queues. Locate/insert queue.
boost::mutex::scoped_lock lock(m_sendQueueMapMutex);
SendQueueMap::iterator pos = m_sendQueueMap.find(session->GetId());
if (pos == m_sendQueueMap.end())
pos = m_sendQueueMap.insert(SendQueueMap::value_type(session->GetId(), boost::shared_ptr<SendDataManager>(new SendDataManager(session->GetAsioSocket())))).first;
tmpManager = pos->second;
}
{
// Second: Add packet to specific queue.
boost::mutex::scoped_lock lock(tmpManager->dataMutex);
if (tmpManager->list.size() < SEND_QUEUE_SIZE)
tmpManager->list.push_back(packet);
}
{
// Third: Update notification list.
boost::mutex::scoped_lock lock(m_changedSessionsMutex);
m_changedSessions.push_back(session->GetId());
}
}
}
void
SenderThread::Send(boost::shared_ptr<SessionData> session, const NetPacketList &packetList)
{
if (!packetList.empty() && session.get())
{
boost::shared_ptr<SendDataManager> tmpManager;
{
// First: lock map of all queues. Locate/insert queue.
boost::mutex::scoped_lock lock(m_sendQueueMapMutex);
SendQueueMap::iterator pos = m_sendQueueMap.find(session->GetId());
if (pos == m_sendQueueMap.end())
pos = m_sendQueueMap.insert(SendQueueMap::value_type(session->GetId(), boost::shared_ptr<SendDataManager>(new SendDataManager(session->GetAsioSocket())))).first;
tmpManager = pos->second;
}
{
// Second: Add packet to specific queue.
boost::mutex::scoped_lock lock(tmpManager->dataMutex);
if (tmpManager->list.size() + packetList.size() <= SEND_QUEUE_SIZE)
{
NetPacketList::const_iterator i = packetList.begin();
NetPacketList::const_iterator end = packetList.end();
while (i != end)
{
tmpManager->list.push_back(*i);
++i;
}
}
}
{
// Third: Update notification list.
boost::mutex::scoped_lock lock(m_changedSessionsMutex);
m_changedSessions.push_back(session->GetId());
}
}
}
void
SenderThread::SignalSessionTerminated(unsigned sessionId)
{
boost::mutex::scoped_lock lock(m_removedSessionsMutex);
m_removedSessions.push_back(sessionId);
}
void
SenderThread::Main()
{
boost::asio::io_service::work ioWork(*m_ioService);
while (!ShouldTerminate())
{
// Close sessions if they were destructed.
{
boost::mutex::scoped_lock lock(m_removedSessionsMutex);
if (!m_removedSessions.empty())
{
SessionIdList newRemovedSessions;
SessionIdList::iterator i = m_removedSessions.begin();
SessionIdList::iterator end = m_removedSessions.end();
boost::mutex::scoped_lock lock(m_sendQueueMapMutex);
while (i != end)
{
SendQueueMap::iterator pos = m_sendQueueMap.find(*i);
if (pos != m_sendQueueMap.end())
{
// Remove session if no write is in progress, else wait.
if (!pos->second->writeInProgress)
m_sendQueueMap.erase(pos);
else
newRemovedSessions.push_back(*i);
}
++i;
}
m_removedSessions = newRemovedSessions;
}
}
// Iterate through all changed sessions, and send data if needed.
bool sessionValid;
do
{
sessionValid = false;
unsigned sessionId;
{
boost::mutex::scoped_lock lock(m_changedSessionsMutex);
if (!m_changedSessions.empty())
{
sessionId = m_changedSessions.front();
m_changedSessions.pop_front();
sessionValid = true;
}
}
boost::shared_ptr<SendDataManager> tmpManager;
if (sessionValid)
{
boost::mutex::scoped_lock lock(m_sendQueueMapMutex);
SendQueueMap::iterator pos = m_sendQueueMap.find(sessionId);
if (pos != m_sendQueueMap.end())
tmpManager = pos->second;
}
if (tmpManager)
tmpManager->AsyncSendNextPacket();
} while (sessionValid);
m_ioService->poll();
Msleep(SEND_TIMEOUT_MSEC);
}
}
<commit_msg>Fixed sending error messages before closing session.<commit_after>/***************************************************************************
* Copyright (C) 2007-2009 by Lothar May *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <net/socket_helper.h>
#include <net/senderthread.h>
#include <net/sendercallback.h>
#include <net/socket_msg.h>
#include <core/loghelper.h>
#include <cstring>
#include <cassert>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace std;
using boost::asio::ip::tcp;
#define SEND_ERROR_TIMEOUT_MSEC 20000
#define SEND_TIMEOUT_MSEC 10
#define SEND_QUEUE_SIZE 10000000
#define SEND_LOG_INTERVAL_SEC 60
typedef std::list<boost::shared_ptr<NetPacket> > SendDataList;
class SendDataManager : public boost::enable_shared_from_this<SendDataManager>
{
public:
SendDataManager(boost::shared_ptr<boost::asio::ip::tcp::socket> s)
: socket(s), writeInProgress(false)
{
}
void HandleWrite(const boost::system::error_code& error);
void AsyncSendNextPacket(bool handlerMode = false);
boost::shared_ptr<boost::asio::ip::tcp::socket> socket;
mutable boost::mutex dataMutex;
SendDataList list;
bool writeInProgress;
};
void
SendDataManager::HandleWrite(const boost::system::error_code& error)
{
// TODO error handling
AsyncSendNextPacket(true);
}
void
SendDataManager::AsyncSendNextPacket(bool handlerMode)
{
boost::mutex::scoped_lock lock(dataMutex);
if (!writeInProgress || handlerMode)
{
if (handlerMode)
list.pop_front();
if (!list.empty())
{
boost::shared_ptr<NetPacket> nextPacket = list.front();
boost::asio::async_write(
*socket,
boost::asio::buffer(nextPacket->GetRawData(),
nextPacket->GetLen()),
boost::bind(&SendDataManager::HandleWrite, shared_from_this(),
boost::asio::placeholders::error));
writeInProgress = true;
}
else
writeInProgress = false;
}
}
SenderThread::SenderThread(SenderCallback &cb, boost::shared_ptr<boost::asio::io_service> ioService)
: m_callback(cb), m_ioService(ioService)
{
}
SenderThread::~SenderThread()
{
}
void
SenderThread::Start()
{
Run();
}
void
SenderThread::SignalStop()
{
SignalTermination();
}
void
SenderThread::WaitStop()
{
Join(SENDER_THREAD_TERMINATE_TIMEOUT);
}
void
SenderThread::Send(boost::shared_ptr<SessionData> session, boost::shared_ptr<NetPacket> packet)
{
if (packet.get() && session.get())
{
boost::shared_ptr<SendDataManager> tmpManager;
{
// First: lock map of all queues. Locate/insert queue.
boost::mutex::scoped_lock lock(m_sendQueueMapMutex);
SendQueueMap::iterator pos = m_sendQueueMap.find(session->GetId());
if (pos == m_sendQueueMap.end())
pos = m_sendQueueMap.insert(SendQueueMap::value_type(session->GetId(), boost::shared_ptr<SendDataManager>(new SendDataManager(session->GetAsioSocket())))).first;
tmpManager = pos->second;
}
{
// Second: Add packet to specific queue.
boost::mutex::scoped_lock lock(tmpManager->dataMutex);
if (tmpManager->list.size() < SEND_QUEUE_SIZE)
tmpManager->list.push_back(packet);
}
{
// Third: Update notification list.
boost::mutex::scoped_lock lock(m_changedSessionsMutex);
m_changedSessions.push_back(session->GetId());
}
}
}
void
SenderThread::Send(boost::shared_ptr<SessionData> session, const NetPacketList &packetList)
{
if (!packetList.empty() && session.get())
{
boost::shared_ptr<SendDataManager> tmpManager;
{
// First: lock map of all queues. Locate/insert queue.
boost::mutex::scoped_lock lock(m_sendQueueMapMutex);
SendQueueMap::iterator pos = m_sendQueueMap.find(session->GetId());
if (pos == m_sendQueueMap.end())
pos = m_sendQueueMap.insert(SendQueueMap::value_type(session->GetId(), boost::shared_ptr<SendDataManager>(new SendDataManager(session->GetAsioSocket())))).first;
tmpManager = pos->second;
}
{
// Second: Add packet to specific queue.
boost::mutex::scoped_lock lock(tmpManager->dataMutex);
if (tmpManager->list.size() + packetList.size() <= SEND_QUEUE_SIZE)
{
NetPacketList::const_iterator i = packetList.begin();
NetPacketList::const_iterator end = packetList.end();
while (i != end)
{
tmpManager->list.push_back(*i);
++i;
}
}
}
{
// Third: Update notification list.
boost::mutex::scoped_lock lock(m_changedSessionsMutex);
m_changedSessions.push_back(session->GetId());
}
}
}
void
SenderThread::SignalSessionTerminated(unsigned sessionId)
{
boost::mutex::scoped_lock lock(m_removedSessionsMutex);
m_removedSessions.push_back(sessionId);
}
void
SenderThread::Main()
{
boost::asio::io_service::work ioWork(*m_ioService);
while (!ShouldTerminate())
{
// Close sessions if they were destructed.
{
boost::mutex::scoped_lock lock(m_removedSessionsMutex);
if (!m_removedSessions.empty())
{
SessionIdList newRemovedSessions;
SessionIdList::iterator i = m_removedSessions.begin();
SessionIdList::iterator end = m_removedSessions.end();
boost::mutex::scoped_lock lock(m_sendQueueMapMutex);
while (i != end)
{
SendQueueMap::iterator pos = m_sendQueueMap.find(*i);
if (pos != m_sendQueueMap.end())
{
// Remove session if no write is in progress, else wait.
bool shouldDelete;
{
boost::mutex::scoped_lock lock(pos->second->dataMutex);
shouldDelete = (!pos->second->writeInProgress && pos->second->list.empty());
}
if (shouldDelete)
m_sendQueueMap.erase(pos);
else
newRemovedSessions.push_back(*i);
}
++i;
}
m_removedSessions = newRemovedSessions;
}
}
// Iterate through all changed sessions, and send data if needed.
bool sessionValid;
do
{
sessionValid = false;
unsigned sessionId;
{
boost::mutex::scoped_lock lock(m_changedSessionsMutex);
if (!m_changedSessions.empty())
{
sessionId = m_changedSessions.front();
m_changedSessions.pop_front();
sessionValid = true;
}
}
boost::shared_ptr<SendDataManager> tmpManager;
if (sessionValid)
{
boost::mutex::scoped_lock lock(m_sendQueueMapMutex);
SendQueueMap::iterator pos = m_sendQueueMap.find(sessionId);
if (pos != m_sendQueueMap.end())
tmpManager = pos->second;
}
if (tmpManager)
tmpManager->AsyncSendNextPacket();
} while (sessionValid);
m_ioService->poll();
Msleep(SEND_TIMEOUT_MSEC);
}
}
<|endoftext|>
|
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen, Daniel Melanz
// =============================================================================
//
// Front and Rear HMMWV suspension subsystems (double A-arm).
//
// These concrete suspension subsystems are defined with respect to right-handed
// frames with X pointing towards the front, Y to the left, and Z up (as imposed
// by the base class ChDoubleWishbone) and origins at the midpoint between the
// lower control arms' connection points to the chassis.
//
// All point locations are provided for the left half of the supspension.
//
// =============================================================================
#include "HMMWV_DoubleWishbone.h"
using namespace chrono;
namespace hmmwv {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
static const double in2m = 0.0254;
static const double lb2kg = 0.453592;
static const double lbf2N = 4.44822162;
static const double lbfpin2Npm = 175.12677;
const double HMMWV_DoubleWishboneFront::m_UCAMass = 5.813;
const double HMMWV_DoubleWishboneFront::m_LCAMass = 23.965;
const double HMMWV_DoubleWishboneFront::m_uprightMass = 19.450;
const double HMMWV_DoubleWishboneFront::m_spindleMass = 14.705;
const double HMMWV_DoubleWishboneFront::m_spindleRadius = 0.10;
const double HMMWV_DoubleWishboneFront::m_spindleWidth = 0.06;
const double HMMWV_DoubleWishboneFront::m_LCARadius = 0.03;
const double HMMWV_DoubleWishboneFront::m_UCARadius = 0.02;
const double HMMWV_DoubleWishboneFront::m_uprightRadius = 0.04;
const ChVector<> HMMWV_DoubleWishboneFront::m_spindleInertia(0.04117, 0.07352, 0.04117); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_UCAInertia(0.03, 0.03, 0.06276); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_LCAInertia(0.4, 0.4, 0.8938); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_uprightInertia(0.1656, 0.1934, 0.04367); // TODO: This is not the correct value
const double HMMWV_DoubleWishboneFront::m_axleInertia = 0.4;
const double HMMWV_DoubleWishboneFront::m_springCoefficient = 167062.000;
const double HMMWV_DoubleWishboneFront::m_springRestLength = 0.339;
// -----------------------------------------------------------------------------
const double HMMWV_DoubleWishboneRear::m_UCAMass = 5.813;
const double HMMWV_DoubleWishboneRear::m_LCAMass = 23.965;
const double HMMWV_DoubleWishboneRear::m_uprightMass = 19.450;
const double HMMWV_DoubleWishboneRear::m_spindleMass = 14.705;
const double HMMWV_DoubleWishboneRear::m_spindleRadius = 0.10;
const double HMMWV_DoubleWishboneRear::m_spindleWidth = 0.06;
const double HMMWV_DoubleWishboneRear::m_LCARadius = 0.03;
const double HMMWV_DoubleWishboneRear::m_UCARadius = 0.02;
const double HMMWV_DoubleWishboneRear::m_uprightRadius = 0.04;
const ChVector<> HMMWV_DoubleWishboneRear::m_spindleInertia(0.04117, 0.07352, 0.04117); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_UCAInertia(0.03, 0.03, 0.06276); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_LCAInertia(0.4, 0.4, 0.8938); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_uprightInertia(0.1656, 0.1934, 0.04367); // TODO: This is not the correct value
const double HMMWV_DoubleWishboneRear::m_axleInertia = 0.4;
const double HMMWV_DoubleWishboneRear::m_springCoefficient = 369149.000;
const double HMMWV_DoubleWishboneRear::m_springRestLength = 0.382;
// -----------------------------------------------------------------------------
// HMMWV shock functor class - implements a nonlinear damper
// -----------------------------------------------------------------------------
class HMMWV_ShockForce : public ChSpringForceCallback
{
public:
HMMWV_ShockForce(double midstroke_compression_slope,
double midstroke_rebound_slope,
double bumpstop_compression_slope,
double bumpstop_rebound_slope,
double min_bumpstop_compression_force,
double midstroke_lower_bound,
double midstroke_upper_bound);
virtual double operator()(double time,
double rest_length,
double length,
double vel);
private:
double m_ms_compr;
double m_ms_rebound;
double m_bs_compr;
double m_bs_rebound;
double m_F0;
double m_min_length;
double m_max_length;
};
HMMWV_ShockForce::HMMWV_ShockForce(double midstroke_compression_slope,
double midstroke_rebound_slope,
double bumpstop_compression_slope,
double bumpstop_rebound_slope,
double min_bumpstop_compression_force,
double midstroke_lower_bound,
double midstroke_upper_bound)
: m_ms_compr(midstroke_compression_slope),
m_ms_rebound(midstroke_rebound_slope),
m_bs_compr(bumpstop_compression_slope),
m_bs_rebound(bumpstop_rebound_slope),
m_F0(min_bumpstop_compression_force),
m_min_length(midstroke_lower_bound),
m_max_length(midstroke_upper_bound)
{
}
double HMMWV_ShockForce::operator()(double time,
double rest_length,
double length,
double vel)
{
/*
// On midstroke curve
if (length >= m_min_length && length <= m_max_length)
return (vel >= 0) ? -m_ms_rebound * vel : -m_ms_compr * vel;
// Hydraulic bump engaged
return (vel >= 0) ? -m_bs_rebound * vel : -m_bs_compr * vel + m_F0;
*/
return -m_bs_rebound * vel;
}
// -----------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------
HMMWV_DoubleWishboneFront::HMMWV_DoubleWishboneFront(const std::string& name)
: ChDoubleWishbone(name)
{
m_shockForceCB = new HMMWV_ShockForce(
lbfpin2Npm * 71.50, // midstroke_compression_slope
lbfpin2Npm * 128.25, // midstroke_rebound_slope
lbfpin2Npm * 33.67, // bumpstop_compression_slope
lbfpin2Npm * 343.00, // bumpstop_rebound_slope
lbf2N * 3350, // min_bumpstop_compression_force
in2m * 13.76, // midstroke_lower_bound
in2m * 15.85 // midstroke_upper_bound
);
}
HMMWV_DoubleWishboneRear::HMMWV_DoubleWishboneRear(const std::string& name)
: ChDoubleWishbone(name)
{
m_shockForceCB = new HMMWV_ShockForce(
lbfpin2Npm * 83.00, // midstroke_compression_slope
lbfpin2Npm * 200.00, // midstroke_rebound_slope
lbfpin2Npm * 48.75, // bumpstop_compression_slope
lbfpin2Npm * 365.00, // bumpstop_rebound_slope
lbf2N * 3350, // min_bumpstop_compression_force
in2m * 13.76, // midstroke_lower_bound
in2m * 15.85 // midstroke_upper_bound
);
}
// -----------------------------------------------------------------------------
// Destructors
// -----------------------------------------------------------------------------
HMMWV_DoubleWishboneFront::~HMMWV_DoubleWishboneFront()
{
delete m_shockForceCB;
}
HMMWV_DoubleWishboneRear::~HMMWV_DoubleWishboneRear()
{
delete m_shockForceCB;
}
// -----------------------------------------------------------------------------
// Implementations of the getLocation() virtual methods.
// -----------------------------------------------------------------------------
const ChVector<> HMMWV_DoubleWishboneFront::getLocation(PointId which)
{
switch (which) {
case SPINDLE: return in2m * ChVector<>(-1.59, 35.815, -1.035);
case UPRIGHT: return in2m * ChVector<>(-1.59, 29.5675, -1.0350);
case UCA_F: return in2m * ChVector<>(-1.8864, 17.5575, 9.6308);
case UCA_B: return in2m * ChVector<>(-10.5596, 18.8085, 7.6992);
case UCA_U: return in2m * ChVector<>(-2.088, 28.17, 8.484);
case UCA_CM: return in2m * ChVector<>(-4.155, 23.176, 8.575);
case LCA_F: return in2m * ChVector<>(8.7900, 12.09, 0);
case LCA_B: return in2m * ChVector<>(-8.7900, 12.09, 0);
case LCA_U: return in2m * ChVector<>(-1.40, 30.965, -4.65);
case LCA_CM: return in2m * ChVector<>(0, 21.528, -2.325);
case SHOCK_C: return in2m * ChVector<>(4.095, 19.598, 12.722);
case SHOCK_A: return in2m * ChVector<>(3.827, 21.385, -1.835);
case SPRING_C: return in2m * ChVector<>(4.095, 20.07, 7.775);
case SPRING_A: return in2m * ChVector<>(3.827, 21.385, -1.835);
case TIEROD_C: return in2m * ChVector<>(-9.855, 17.655, 2.135);
case TIEROD_U: return in2m * ChVector<>(-6.922, 32.327, -0.643);
default: return ChVector<>(0, 0, 0);
}
}
const ChVector<> HMMWV_DoubleWishboneRear::getLocation(PointId which)
{
switch (which) {
case SPINDLE: return in2m * ChVector<>(1.40, 35.815, -1.035);
case UPRIGHT: return in2m * ChVector<>(1.40, 29.5675, -1.035);
case UCA_F: return in2m * ChVector<>(13.7445, 18.1991, 8.9604);
case UCA_B: return in2m * ChVector<>(3.0355, 18.1909, 8.8096);
case UCA_U: return in2m * ChVector<>(1.40, 28.17, 8.5);
case UCA_CM: return in2m * ChVector<>(4.895, 23.183, 8.692);
case LCA_F: return in2m * ChVector<>(8.7900, 12.09, 0);
case LCA_B: return in2m * ChVector<>(-8.7900, 12.09, 0);
case LCA_U: return in2m * ChVector<>(1.40, 30.965, -4.650);
case LCA_CM: return in2m * ChVector<>(0, 21.527, -2.325);
case SHOCK_C: return in2m * ChVector<>(-4.095, 19.598, 12.722);
case SHOCK_A: return in2m * ChVector<>(-3.827, 21.415, -1.511);
case SPRING_C: return in2m * ChVector<>(-4.095, 19.747, 10.098);
case SPRING_A: return in2m * ChVector<>(-3.827, 21.385, -1.835);
case TIEROD_C: return in2m * ChVector<>(8.790, 16.38, 2.310);
case TIEROD_U: return in2m * ChVector<>(6.704, 32.327, -0.365);
default: return ChVector<>(0, 0, 0);
}
}
} // end namespace hmmwv
<commit_msg>Updated HMMWV Double Wishbone shock model to include hard contact<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen, Daniel Melanz
// =============================================================================
//
// Front and Rear HMMWV suspension subsystems (double A-arm).
//
// These concrete suspension subsystems are defined with respect to right-handed
// frames with X pointing towards the front, Y to the left, and Z up (as imposed
// by the base class ChDoubleWishbone) and origins at the midpoint between the
// lower control arms' connection points to the chassis.
//
// All point locations are provided for the left half of the supspension.
//
// =============================================================================
#include "HMMWV_DoubleWishbone.h"
using namespace chrono;
namespace hmmwv {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
static const double in2m = 0.0254;
static const double lb2kg = 0.453592;
static const double lbf2N = 4.44822162;
static const double lbfpin2Npm = 175.12677;
const double HMMWV_DoubleWishboneFront::m_UCAMass = 5.813;
const double HMMWV_DoubleWishboneFront::m_LCAMass = 23.965;
const double HMMWV_DoubleWishboneFront::m_uprightMass = 19.450;
const double HMMWV_DoubleWishboneFront::m_spindleMass = 14.705;
const double HMMWV_DoubleWishboneFront::m_spindleRadius = 0.10;
const double HMMWV_DoubleWishboneFront::m_spindleWidth = 0.06;
const double HMMWV_DoubleWishboneFront::m_LCARadius = 0.03;
const double HMMWV_DoubleWishboneFront::m_UCARadius = 0.02;
const double HMMWV_DoubleWishboneFront::m_uprightRadius = 0.04;
const ChVector<> HMMWV_DoubleWishboneFront::m_spindleInertia(0.04117, 0.07352, 0.04117); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_UCAInertia(0.03, 0.03, 0.06276); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_LCAInertia(0.4, 0.4, 0.8938); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_uprightInertia(0.1656, 0.1934, 0.04367); // TODO: This is not the correct value
const double HMMWV_DoubleWishboneFront::m_axleInertia = 0.4;
const double HMMWV_DoubleWishboneFront::m_springCoefficient = 167062.000;
const double HMMWV_DoubleWishboneFront::m_springRestLength = 0.339;
// -----------------------------------------------------------------------------
const double HMMWV_DoubleWishboneRear::m_UCAMass = 5.813;
const double HMMWV_DoubleWishboneRear::m_LCAMass = 23.965;
const double HMMWV_DoubleWishboneRear::m_uprightMass = 19.450;
const double HMMWV_DoubleWishboneRear::m_spindleMass = 14.705;
const double HMMWV_DoubleWishboneRear::m_spindleRadius = 0.10;
const double HMMWV_DoubleWishboneRear::m_spindleWidth = 0.06;
const double HMMWV_DoubleWishboneRear::m_LCARadius = 0.03;
const double HMMWV_DoubleWishboneRear::m_UCARadius = 0.02;
const double HMMWV_DoubleWishboneRear::m_uprightRadius = 0.04;
const ChVector<> HMMWV_DoubleWishboneRear::m_spindleInertia(0.04117, 0.07352, 0.04117); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_UCAInertia(0.03, 0.03, 0.06276); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_LCAInertia(0.4, 0.4, 0.8938); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_uprightInertia(0.1656, 0.1934, 0.04367); // TODO: This is not the correct value
const double HMMWV_DoubleWishboneRear::m_axleInertia = 0.4;
const double HMMWV_DoubleWishboneRear::m_springCoefficient = 369149.000;
const double HMMWV_DoubleWishboneRear::m_springRestLength = 0.382;
// -----------------------------------------------------------------------------
// HMMWV shock functor class - implements a nonlinear damper
// -----------------------------------------------------------------------------
class HMMWV_ShockForce : public ChSpringForceCallback
{
public:
HMMWV_ShockForce(double midstroke_compression_slope,
double midstroke_rebound_slope,
double bumpstop_compression_slope,
double bumpstop_rebound_slope,
double metalmetal_slope,
double min_bumpstop_compression_force,
double midstroke_lower_bound,
double midstroke_upper_bound,
double metalmetal_lower_bound,
double metalmetal_upper_bound);
virtual double operator()(double time,
double rest_length,
double length,
double vel);
private:
double m_ms_compr;
double m_ms_rebound;
double m_bs_compr;
double m_bs_rebound;
double m_metal_K;
double m_F0;
double m_ms_min_length;
double m_ms_max_length;
double m_min_length;
double m_max_length;
};
HMMWV_ShockForce::HMMWV_ShockForce(double midstroke_compression_slope,
double midstroke_rebound_slope,
double bumpstop_compression_slope,
double bumpstop_rebound_slope,
double metalmetal_slope,
double min_bumpstop_compression_force,
double midstroke_lower_bound,
double midstroke_upper_bound,
double metalmetal_lower_bound,
double metalmetal_upper_bound)
: m_ms_compr(midstroke_compression_slope),
m_ms_rebound(midstroke_rebound_slope),
m_bs_compr(bumpstop_compression_slope),
m_bs_rebound(bumpstop_rebound_slope),
m_metal_K(metalmetal_slope),
m_F0(min_bumpstop_compression_force),
m_ms_min_length(midstroke_lower_bound),
m_ms_max_length(midstroke_upper_bound),
m_min_length(metalmetal_lower_bound),
m_max_length(metalmetal_upper_bound)
{
}
double HMMWV_ShockForce::operator()(double time,
double rest_length,
double length,
double vel)
{
/*
// On midstroke curve
if (length >= m_min_length && length <= m_max_length)
return (vel >= 0) ? -m_ms_rebound * vel : -m_ms_compr * vel;
// Hydraulic bump engaged
return (vel >= 0) ? -m_bs_rebound * vel : -m_bs_compr * vel + m_F0;
*/
double force = 0;
//Calculate Damping Force
if(vel >= 0)
{
force = (length >= m_ms_max_length) ? -m_bs_rebound * vel : -m_ms_rebound * vel;
}
else
{
force = (length <= m_ms_min_length) ? -m_bs_compr * vel : -m_ms_compr * vel;
}
//Add in Shock metal to metal contact force
if(length <= m_min_length)
{
force = m_metal_K*(m_min_length-length);
}
else if(length >= m_max_length)
{
force = -m_metal_K*(length-m_max_length);
}
return force;
}
// -----------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------
HMMWV_DoubleWishboneFront::HMMWV_DoubleWishboneFront(const std::string& name)
: ChDoubleWishbone(name)
{
m_shockForceCB = new HMMWV_ShockForce(
lbfpin2Npm * 71.50, // midstroke_compression_slope
lbfpin2Npm * 128.25, // midstroke_rebound_slope
lbfpin2Npm * 33.67, // bumpstop_compression_slope
lbfpin2Npm * 343.00, // bumpstop_rebound_slope
lbfpin2Npm * 150000, // metalmetal_slope
lbf2N * 3350, // min_bumpstop_compression_force
in2m * 13.76, // midstroke_lower_bound
in2m * 15.85, // midstroke_upper_bound
in2m * 12.76, // metalmetal_lower_bound
in2m * 16.48 // metalmetal_upper_boun
);
}
HMMWV_DoubleWishboneRear::HMMWV_DoubleWishboneRear(const std::string& name)
: ChDoubleWishbone(name)
{
m_shockForceCB = new HMMWV_ShockForce(
lbfpin2Npm * 83.00, // midstroke_compression_slope
lbfpin2Npm * 200.00, // midstroke_rebound_slope
lbfpin2Npm * 48.75, // bumpstop_compression_slope
lbfpin2Npm * 365.00, // bumpstop_rebound_slope
lbfpin2Npm * 150000, // metalmetal_slope
lbf2N * 3350, // min_bumpstop_compression_force
in2m * 13.76, // midstroke_lower_bound
in2m * 15.85, // midstroke_upper_bound
in2m * 12.76, // metalmetal_lower_bound
in2m * 16.48 // metalmetal_upper_bound
);
}
// -----------------------------------------------------------------------------
// Destructors
// -----------------------------------------------------------------------------
HMMWV_DoubleWishboneFront::~HMMWV_DoubleWishboneFront()
{
delete m_shockForceCB;
}
HMMWV_DoubleWishboneRear::~HMMWV_DoubleWishboneRear()
{
delete m_shockForceCB;
}
// -----------------------------------------------------------------------------
// Implementations of the getLocation() virtual methods.
// -----------------------------------------------------------------------------
const ChVector<> HMMWV_DoubleWishboneFront::getLocation(PointId which)
{
switch (which) {
case SPINDLE: return in2m * ChVector<>(-1.59, 35.815, -1.035);
case UPRIGHT: return in2m * ChVector<>(-1.59, 29.5675, -1.0350);
case UCA_F: return in2m * ChVector<>(-1.8864, 17.5575, 9.6308);
case UCA_B: return in2m * ChVector<>(-10.5596, 18.8085, 7.6992);
case UCA_U: return in2m * ChVector<>(-2.088, 28.17, 8.484);
case UCA_CM: return in2m * ChVector<>(-4.155, 23.176, 8.575);
case LCA_F: return in2m * ChVector<>(8.7900, 12.09, 0);
case LCA_B: return in2m * ChVector<>(-8.7900, 12.09, 0);
case LCA_U: return in2m * ChVector<>(-1.40, 30.965, -4.65);
case LCA_CM: return in2m * ChVector<>(0, 21.528, -2.325);
case SHOCK_C: return in2m * ChVector<>(4.095, 19.598, 12.722);
case SHOCK_A: return in2m * ChVector<>(3.827, 21.385, -1.835);
case SPRING_C: return in2m * ChVector<>(4.095, 20.07, 7.775);
case SPRING_A: return in2m * ChVector<>(3.827, 21.385, -1.835);
case TIEROD_C: return in2m * ChVector<>(-9.855, 17.655, 2.135);
case TIEROD_U: return in2m * ChVector<>(-6.922, 32.327, -0.643);
default: return ChVector<>(0, 0, 0);
}
}
const ChVector<> HMMWV_DoubleWishboneRear::getLocation(PointId which)
{
switch (which) {
case SPINDLE: return in2m * ChVector<>(1.40, 35.815, -1.035);
case UPRIGHT: return in2m * ChVector<>(1.40, 29.5675, -1.035);
case UCA_F: return in2m * ChVector<>(13.7445, 18.1991, 8.9604);
case UCA_B: return in2m * ChVector<>(3.0355, 18.1909, 8.8096);
case UCA_U: return in2m * ChVector<>(1.40, 28.17, 8.5);
case UCA_CM: return in2m * ChVector<>(4.895, 23.183, 8.692);
case LCA_F: return in2m * ChVector<>(8.7900, 12.09, 0);
case LCA_B: return in2m * ChVector<>(-8.7900, 12.09, 0);
case LCA_U: return in2m * ChVector<>(1.40, 30.965, -4.650);
case LCA_CM: return in2m * ChVector<>(0, 21.527, -2.325);
case SHOCK_C: return in2m * ChVector<>(-4.095, 19.598, 12.722);
case SHOCK_A: return in2m * ChVector<>(-3.827, 21.415, -1.511);
case SPRING_C: return in2m * ChVector<>(-4.095, 19.747, 10.098);
case SPRING_A: return in2m * ChVector<>(-3.827, 21.385, -1.835);
case TIEROD_C: return in2m * ChVector<>(8.790, 16.38, 2.310);
case TIEROD_U: return in2m * ChVector<>(6.704, 32.327, -0.365);
default: return ChVector<>(0, 0, 0);
}
}
} // end namespace hmmwv
<|endoftext|>
|
<commit_before>#pragma once
#include <sched.h>
namespace mimosa
{
inline void yield()
{
::sched_yield();
}
}
<commit_msg>More noexcept<commit_after>#pragma once
#include <sched.h>
namespace mimosa
{
inline void yield() noexcept
{
::sched_yield();
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scripttypedetector.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2006-06-20 04:44:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <com/sun/star/i18n/CTLScriptType.hpp>
#include <com/sun/star/i18n/ScriptDirection.hpp>
#include <com/sun/star/i18n/UnicodeScript.hpp>
#include <scripttypedetector.hxx>
#include <i18nutil/unicode.hxx>
// ----------------------------------------------------
// class ScriptTypeDetector
// ----------------------------------------------------;
using namespace com::sun::star::i18n;
ScriptTypeDetector::ScriptTypeDetector()
{
}
ScriptTypeDetector::~ScriptTypeDetector()
{
}
static sal_Int16 scriptDirection[] = {
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT = 0,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT = 1,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER = 2,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER_SEPARATOR = 3,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER_TERMINATOR = 4,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_ARABIC_NUMBER = 5,
ScriptDirection::NEUTRAL, // DirectionProperty_COMMON_NUMBER_SEPARATOR = 6,
ScriptDirection::NEUTRAL, // DirectionProperty_BLOCK_SEPARATOR = 7,
ScriptDirection::NEUTRAL, // DirectionProperty_SEGMENT_SEPARATOR = 8,
ScriptDirection::NEUTRAL, // DirectionProperty_WHITE_SPACE_NEUTRAL = 9,
ScriptDirection::NEUTRAL, // DirectionProperty_OTHER_NEUTRAL = 10,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT_EMBEDDING = 11,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT_OVERRIDE = 12,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_ARABIC = 13,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_EMBEDDING = 14,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_OVERRIDE = 15,
ScriptDirection::NEUTRAL, // DirectionProperty_POP_DIRECTIONAL_FORMAT = 16,
ScriptDirection::NEUTRAL, // DirectionProperty_DIR_NON_SPACING_MARK = 17,
ScriptDirection::NEUTRAL, // DirectionProperty_BOUNDARY_NEUTRAL = 18,
};
sal_Int16 SAL_CALL
ScriptTypeDetector::getScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 defaultScriptDirection ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int16 dir = scriptDirection[unicode::getUnicodeDirection(Text[nPos])];
return (dir == ScriptDirection::NEUTRAL) ? defaultScriptDirection : dir;
}
// return value '-1' means either the direction on nPos is not same as scriptDirection or nPos is out of range.
sal_Int32 SAL_CALL
ScriptTypeDetector::beginOfScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 direction ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int32 cPos = nPos;
if (cPos < Text.getLength()) {
for (; cPos >= 0; cPos--) {
if (direction != getScriptDirection(Text, cPos, direction))
break;
}
}
return cPos == nPos ? -1 : cPos + 1;
}
sal_Int32 SAL_CALL
ScriptTypeDetector::endOfScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 direction ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int32 cPos = nPos;
sal_Int32 len = Text.getLength();
if (cPos >=0) {
for (; cPos < len; cPos++) {
if (direction != getScriptDirection(Text, cPos, direction))
break;
}
}
return cPos == nPos ? -1 : cPos;
}
sal_Int16 SAL_CALL
ScriptTypeDetector::getCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
static ScriptTypeList typeList[] = {
{ UnicodeScript_kHebrew, UnicodeScript_kHebrew, CTLScriptType::CTL_HEBREW }, // 10
{ UnicodeScript_kArabic, UnicodeScript_kArabic, CTLScriptType::CTL_ARABIC }, // 11
{ UnicodeScript_kDevanagari, UnicodeScript_kDevanagari, CTLScriptType::CTL_INDIC }, // 14
{ UnicodeScript_kThai, UnicodeScript_kThai, CTLScriptType::CTL_THAI }, // 24
{ UnicodeScript_kScriptCount, UnicodeScript_kScriptCount, CTLScriptType::CTL_UNKNOWN } // 88
};
return unicode::getUnicodeScriptType(Text[nPos], typeList, CTLScriptType::CTL_UNKNOWN);
}
// Begin of Script Type is inclusive.
sal_Int32 SAL_CALL
ScriptTypeDetector::beginOfCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
if (nPos < 0)
return 0;
else if (nPos >= Text.getLength())
return Text.getLength();
else {
sal_Int16 cType = getCTLScriptType(Text, nPos);
for (nPos--; nPos >= 0; nPos--) {
if (cType != getCTLScriptType(Text, nPos))
break;
}
return nPos + 1;
}
}
// End of the Script Type is exclusive, the return value pointing to the begin of next script type
sal_Int32 SAL_CALL
ScriptTypeDetector::endOfCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
if (nPos < 0)
return 0;
else if (nPos >= Text.getLength())
return Text.getLength();
else {
sal_Int16 cType = getCTLScriptType(Text, nPos);
sal_Int32 len = Text.getLength();
for (nPos++; nPos < len; nPos++) {
if (cType != getCTLScriptType(Text, nPos))
break;
}
return nPos;
}
}
const sal_Char sDetector[] = "draft.com.sun.star.i18n.ScriptTypeDetector";
rtl::OUString SAL_CALL
ScriptTypeDetector::getImplementationName() throw( ::com::sun::star::uno::RuntimeException )
{
return ::rtl::OUString::createFromAscii(sDetector);
}
sal_Bool SAL_CALL
ScriptTypeDetector::supportsService(const rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException )
{
return !ServiceName.compareToAscii(sDetector);
}
::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
ScriptTypeDetector::getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException )
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aRet(1);
aRet[0] = ::rtl::OUString::createFromAscii(sDetector);
return aRet;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.8.16); FILE MERGED 2006/09/01 17:30:41 kaib 1.8.16.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scripttypedetector.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-17 09:16:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"
#include <com/sun/star/i18n/CTLScriptType.hpp>
#include <com/sun/star/i18n/ScriptDirection.hpp>
#include <com/sun/star/i18n/UnicodeScript.hpp>
#include <scripttypedetector.hxx>
#include <i18nutil/unicode.hxx>
// ----------------------------------------------------
// class ScriptTypeDetector
// ----------------------------------------------------;
using namespace com::sun::star::i18n;
ScriptTypeDetector::ScriptTypeDetector()
{
}
ScriptTypeDetector::~ScriptTypeDetector()
{
}
static sal_Int16 scriptDirection[] = {
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT = 0,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT = 1,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER = 2,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER_SEPARATOR = 3,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER_TERMINATOR = 4,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_ARABIC_NUMBER = 5,
ScriptDirection::NEUTRAL, // DirectionProperty_COMMON_NUMBER_SEPARATOR = 6,
ScriptDirection::NEUTRAL, // DirectionProperty_BLOCK_SEPARATOR = 7,
ScriptDirection::NEUTRAL, // DirectionProperty_SEGMENT_SEPARATOR = 8,
ScriptDirection::NEUTRAL, // DirectionProperty_WHITE_SPACE_NEUTRAL = 9,
ScriptDirection::NEUTRAL, // DirectionProperty_OTHER_NEUTRAL = 10,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT_EMBEDDING = 11,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT_OVERRIDE = 12,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_ARABIC = 13,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_EMBEDDING = 14,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_OVERRIDE = 15,
ScriptDirection::NEUTRAL, // DirectionProperty_POP_DIRECTIONAL_FORMAT = 16,
ScriptDirection::NEUTRAL, // DirectionProperty_DIR_NON_SPACING_MARK = 17,
ScriptDirection::NEUTRAL, // DirectionProperty_BOUNDARY_NEUTRAL = 18,
};
sal_Int16 SAL_CALL
ScriptTypeDetector::getScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 defaultScriptDirection ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int16 dir = scriptDirection[unicode::getUnicodeDirection(Text[nPos])];
return (dir == ScriptDirection::NEUTRAL) ? defaultScriptDirection : dir;
}
// return value '-1' means either the direction on nPos is not same as scriptDirection or nPos is out of range.
sal_Int32 SAL_CALL
ScriptTypeDetector::beginOfScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 direction ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int32 cPos = nPos;
if (cPos < Text.getLength()) {
for (; cPos >= 0; cPos--) {
if (direction != getScriptDirection(Text, cPos, direction))
break;
}
}
return cPos == nPos ? -1 : cPos + 1;
}
sal_Int32 SAL_CALL
ScriptTypeDetector::endOfScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 direction ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int32 cPos = nPos;
sal_Int32 len = Text.getLength();
if (cPos >=0) {
for (; cPos < len; cPos++) {
if (direction != getScriptDirection(Text, cPos, direction))
break;
}
}
return cPos == nPos ? -1 : cPos;
}
sal_Int16 SAL_CALL
ScriptTypeDetector::getCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
static ScriptTypeList typeList[] = {
{ UnicodeScript_kHebrew, UnicodeScript_kHebrew, CTLScriptType::CTL_HEBREW }, // 10
{ UnicodeScript_kArabic, UnicodeScript_kArabic, CTLScriptType::CTL_ARABIC }, // 11
{ UnicodeScript_kDevanagari, UnicodeScript_kDevanagari, CTLScriptType::CTL_INDIC }, // 14
{ UnicodeScript_kThai, UnicodeScript_kThai, CTLScriptType::CTL_THAI }, // 24
{ UnicodeScript_kScriptCount, UnicodeScript_kScriptCount, CTLScriptType::CTL_UNKNOWN } // 88
};
return unicode::getUnicodeScriptType(Text[nPos], typeList, CTLScriptType::CTL_UNKNOWN);
}
// Begin of Script Type is inclusive.
sal_Int32 SAL_CALL
ScriptTypeDetector::beginOfCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
if (nPos < 0)
return 0;
else if (nPos >= Text.getLength())
return Text.getLength();
else {
sal_Int16 cType = getCTLScriptType(Text, nPos);
for (nPos--; nPos >= 0; nPos--) {
if (cType != getCTLScriptType(Text, nPos))
break;
}
return nPos + 1;
}
}
// End of the Script Type is exclusive, the return value pointing to the begin of next script type
sal_Int32 SAL_CALL
ScriptTypeDetector::endOfCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
if (nPos < 0)
return 0;
else if (nPos >= Text.getLength())
return Text.getLength();
else {
sal_Int16 cType = getCTLScriptType(Text, nPos);
sal_Int32 len = Text.getLength();
for (nPos++; nPos < len; nPos++) {
if (cType != getCTLScriptType(Text, nPos))
break;
}
return nPos;
}
}
const sal_Char sDetector[] = "draft.com.sun.star.i18n.ScriptTypeDetector";
rtl::OUString SAL_CALL
ScriptTypeDetector::getImplementationName() throw( ::com::sun::star::uno::RuntimeException )
{
return ::rtl::OUString::createFromAscii(sDetector);
}
sal_Bool SAL_CALL
ScriptTypeDetector::supportsService(const rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException )
{
return !ServiceName.compareToAscii(sDetector);
}
::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
ScriptTypeDetector::getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException )
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aRet(1);
aRet[0] = ::rtl::OUString::createFromAscii(sDetector);
return aRet;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2019, 2021 by Robert Bosch GmbH, Apex.AI Inc. 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 "iceoryx_posh/internal/log/posh_logging.hpp"
#include "iceoryx_posh/roudi/iceoryx_roudi_app.hpp"
#include "iceoryx_posh/roudi/roudi_cmd_line_parser_config_file_option.hpp"
#include "iceoryx_posh/roudi/roudi_config_toml_file_provider.hpp"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace ::testing;
using ::testing::Return;
using iox::roudi::IceOryxRouDiApp;
using namespace iox::config;
namespace iox
{
namespace test
{
class IceoryxRoudiApp_Child : public IceOryxRouDiApp
{
public:
IceoryxRoudiApp_Child(const config::CmdLineArgs_t& cmdLineArgs, const RouDiConfig_t& roudiConfig)
: IceOryxRouDiApp(cmdLineArgs, roudiConfig)
{
}
bool getVariableMRun()
{
return m_run;
}
void setVariableMRun(bool condition)
{
m_run = condition;
}
uint8_t callRun() noexcept
{
return run();
}
};
/// @brief Test goal: This file tests class roudi app
class IceoryxRoudiApp_test : public Test
{
public:
CmdLineParserConfigFileOption cmdLineParser;
void TearDown()
{
// Reset optind to be able to parse again
optind = 0;
};
};
TEST_F(IceoryxRoudiApp_test, CheckConstructorIsSuccessfull)
{
constexpr uint8_t numberOfArgs{1U};
char* args[numberOfArgs];
char appName[] = "./foo";
args[0] = &appName[0];
auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);
IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
EXPECT_TRUE(roudi.getVariableMRun());
}
TEST_F(IceoryxRoudiApp_test, CreateTwoRoudiAppIsSuccessfull)
{
constexpr uint8_t numberOfArgs{1U};
char* args[numberOfArgs];
char appName[] = "./foo";
args[0] = &appName[0];
auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);
IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
EXPECT_TRUE(roudiTest.getVariableMRun());
}
TEST_F(IceoryxRoudiApp_test, CheckRunMethodWithMRunFalseReturnExitSuccess)
{
constexpr uint8_t numberOfArgs{1U};
char* args[numberOfArgs];
char appName[] = "./foo";
args[0] = &appName[0];
auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);
IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
roudi.setVariableMRun(false);
uint8_t result = roudi.callRun();
EXPECT_EQ(result, EXIT_SUCCESS);
}
TEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgUniqueIdSetRunVariableToFalse)
{
constexpr uint8_t numberOfArgs{3U};
char* args[numberOfArgs];
char appName[] = "./foo";
char option[] = "--unique-roudi-id";
char value[] = "4242";
args[0] = &appName[0];
args[1] = &option[0];
args[2] = &value[0];
auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);
iox::cxx::optional<iox::Error> detectedError;
auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler(
[&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
detectedError.emplace(error);
EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::MODERATE));
});
IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
ASSERT_THAT(detectedError.has_value(), Eq(true));
EXPECT_THAT(detectedError.value(), Eq(iox::Error::kPOPO__TYPED_UNIQUE_ID_ROUDI_HAS_ALREADY_DEFINED_UNIQUE_ID));
}
TEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgVersionSetRunVariableToFalse)
{
constexpr uint8_t numberOfArgs{2U};
char* args[numberOfArgs];
char appName[] = "./foo";
char option[] = "-v";
args[0] = &appName[0];
args[1] = &option[0];
auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);
IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
EXPECT_FALSE(roudi.getVariableMRun());
}
} // namespace test
} // namespace iox<commit_msg>iox-#454 change test name<commit_after>// Copyright (c) 2019, 2021 by Robert Bosch GmbH, Apex.AI Inc. 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 "iceoryx_posh/internal/log/posh_logging.hpp"
#include "iceoryx_posh/roudi/iceoryx_roudi_app.hpp"
#include "iceoryx_posh/roudi/roudi_cmd_line_parser_config_file_option.hpp"
#include "iceoryx_posh/roudi/roudi_config_toml_file_provider.hpp"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace ::testing;
using ::testing::Return;
using iox::roudi::IceOryxRouDiApp;
using namespace iox::config;
namespace iox
{
namespace test
{
class IceoryxRoudiApp_Child : public IceOryxRouDiApp
{
public:
IceoryxRoudiApp_Child(const config::CmdLineArgs_t& cmdLineArgs, const RouDiConfig_t& roudiConfig)
: IceOryxRouDiApp(cmdLineArgs, roudiConfig)
{
}
bool getVariableMRun()
{
return m_run;
}
void setVariableMRun(bool condition)
{
m_run = condition;
}
uint8_t callRun() noexcept
{
return run();
}
};
/// @brief Test goal: This file tests class roudi app
class IceoryxRoudiApp_test : public Test
{
public:
CmdLineParserConfigFileOption cmdLineParser;
void TearDown()
{
// Reset optind to be able to parse again
optind = 0;
};
};
TEST_F(IceoryxRoudiApp_test, CheckConstructorIsSuccessfull)
{
constexpr uint8_t numberOfArgs{1U};
char* args[numberOfArgs];
char appName[] = "./foo";
args[0] = &appName[0];
auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);
IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
EXPECT_TRUE(roudi.getVariableMRun());
}
TEST_F(IceoryxRoudiApp_test, CreateTwoRoudiAppIsSuccessfull)
{
constexpr uint8_t numberOfArgs{1U};
char* args[numberOfArgs];
char appName[] = "./foo";
args[0] = &appName[0];
auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);
IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
EXPECT_TRUE(roudiTest.getVariableMRun());
}
TEST_F(IceoryxRoudiApp_test, CheckRunMethodWithMRunFalseReturnExitSuccess)
{
constexpr uint8_t numberOfArgs{1U};
char* args[numberOfArgs];
char appName[] = "./foo";
args[0] = &appName[0];
auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);
IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
roudi.setVariableMRun(false);
uint8_t result = roudi.callRun();
EXPECT_EQ(result, EXIT_SUCCESS);
}
TEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgUniqueIdTwoTimesReturnError)
{
constexpr uint8_t numberOfArgs{3U};
char* args[numberOfArgs];
char appName[] = "./foo";
char option[] = "--unique-roudi-id";
char value[] = "4242";
args[0] = &appName[0];
args[1] = &option[0];
args[2] = &value[0];
auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);
iox::cxx::optional<iox::Error> detectedError;
auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler(
[&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
detectedError.emplace(error);
EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::MODERATE));
});
IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
ASSERT_THAT(detectedError.has_value(), Eq(true));
EXPECT_THAT(detectedError.value(), Eq(iox::Error::kPOPO__TYPED_UNIQUE_ID_ROUDI_HAS_ALREADY_DEFINED_UNIQUE_ID));
}
TEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgVersionSetRunVariableToFalse)
{
constexpr uint8_t numberOfArgs{2U};
char* args[numberOfArgs];
char appName[] = "./foo";
char option[] = "-v";
args[0] = &appName[0];
args[1] = &option[0];
auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);
IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());
EXPECT_FALSE(roudi.getVariableMRun());
}
} // namespace test
} // namespace iox<|endoftext|>
|
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file process_model_interface.hpp
* \date October 2014
* \author Jan Issac ([email protected])
*/
#ifndef FL__MODEL__PROCESS__PROCESS_MODEL_INTERFACE_HPP
#define FL__MODEL__PROCESS__PROCESS_MODEL_INTERFACE_HPP
#include <fl/util/traits.hpp>
namespace fl
{
template <
typename State_,
typename Noise_,
typename Input_,
int Id = 0
>
class StateTransitionFunction
{
public:
typedef State_ State;
typedef Noise_ Noise;
typedef Input_ Input;
public:
/**
* \brief Overridable default destructor
*/
virtual ~StateTransitionFunction() { }
virtual State state(const State& prev_state,
const Noise& noise,
const Input& input) const = 0;
/**
* \return Dimension of the state variable $\f$x\f$
*/
virtual int state_dimension() const = 0;
/**
* \return Dimension of the noise term \f$w\f$
*/
virtual int noise_dimension() const = 0;
/**
* \return Dimension of the input \f$u_t\f$
*/
virtual int input_dimension() const = 0;
/**
* \return Model id number
*
* In case of multiple sensors of the same kind, this function returns the
* id of the individual model.
*/
virtual int id() const { return Id; }
/**
* Sets the model id
*
* \param new_id Model's new ID
*/
virtual void id(int) { /* const ID */ }
};
/**
* \interface ProcessModelInterface
* \ingroup process_models
*
* \brief This reprersents the common process model interface of the form
* \f$p(x\mid x_t, u_t, v_t)\f$
*
* \tparam State Type of the state variable \f$x_t\f$
* \tparam Noise Type of the noise term \f$v_t\f$
* \tparam Input Type of the control input \f$u_t\f$
*/
template <
typename State,
typename Noise,
typename Input
>
class ProcessModelInterface
: public internal::ProcessModelType
{
public:
typedef internal::ProcessModelType ModelType;
public:
/**
* Sets the conditional arguments \f$x_t, u_t\f$ of \f$p(x\mid x_t, u_t)\f$
*
* \param delta_time Prediction duration \f$\Delta t\f$
* \param state Previous state \f$x_{t}\f$
* \param input Control input \f$u_t\f$
*
* Once the conditional have been set, may either sample from this model
* since it also represents a conditional distribution or you may map
* a SNV noise term \f$v_t\f$ onto the distribution using
* \c map_standard_variate(\f$v_t\f$) if implemented.
*/
virtual void condition(const double& delta_time,
const State& state,
const Input& input = Input()) { }
/**
* Predicts the state conditioned on the previous state and input.
*
* \param delta_time Prediction duration \f$\Delta t\f$
* \param state Previous state \f$x_{t}\f$
* \param noise Additive or non-Additive noise \f$v_t\f$
* \param input Control input \f$u_t\f$
*
* \return State \f$x_{t+1}\sim p(x\mid x_t, u_t)\f$
*/
/// \todo have a default argument for the input, a default function which
/// has to be implemented by the derived classes
virtual State predict_state(double delta_time,
const State& state,
const Noise& noise,
const Input& input) = 0;
/**
* \return \f$\dim(x_t)\f$, dimension of the state
*/
virtual constexpr int state_dimension() const = 0;
/**
* \return \f$\dim(v_t)\f$, dimension of the noise
*/
virtual constexpr int noise_dimension() const = 0;
/**
* \return \f$\dim(u_t)\f$, dimension of the control input
*/
virtual constexpr int input_dimension() const = 0;
};
}
#endif
<commit_msg>StateTransitionFunction is of type NonAdditiveModelType<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file process_model_interface.hpp
* \date October 2014
* \author Jan Issac ([email protected])
*/
#ifndef FL__MODEL__PROCESS__PROCESS_MODEL_INTERFACE_HPP
#define FL__MODEL__PROCESS__PROCESS_MODEL_INTERFACE_HPP
#include <fl/util/traits.hpp>
namespace fl
{
template <
typename State_,
typename Noise_,
typename Input_,
int Id = 0
>
class StateTransitionFunction
: internal::NonAdditiveModelType
{
public:
typedef internal::NonAdditiveModelType Type;
typedef State_ State;
typedef Noise_ Noise;
typedef Input_ Input;
public:
/**
* \brief Overridable default destructor
*/
virtual ~StateTransitionFunction() { }
virtual State state(const State& prev_state,
const Noise& noise,
const Input& input) const = 0;
/**
* \return Dimension of the state variable $\f$x\f$
*/
virtual int state_dimension() const = 0;
/**
* \return Dimension of the noise term \f$w\f$
*/
virtual int noise_dimension() const = 0;
/**
* \return Dimension of the input \f$u_t\f$
*/
virtual int input_dimension() const = 0;
/**
* \return Model id number
*
* In case of multiple sensors of the same kind, this function returns the
* id of the individual model.
*/
virtual int id() const { return Id; }
/**
* Sets the model id
*
* \param new_id Model's new ID
*/
virtual void id(int) { /* const ID */ }
};
/**
* \interface ProcessModelInterface
* \ingroup process_models
*
* \brief This reprersents the common process model interface of the form
* \f$p(x\mid x_t, u_t, v_t)\f$
*
* \tparam State Type of the state variable \f$x_t\f$
* \tparam Noise Type of the noise term \f$v_t\f$
* \tparam Input Type of the control input \f$u_t\f$
*/
template <
typename State,
typename Noise,
typename Input
>
class ProcessModelInterface
: public internal::ProcessModelType
{
public:
typedef internal::ProcessModelType ModelType;
public:
/**
* Sets the conditional arguments \f$x_t, u_t\f$ of \f$p(x\mid x_t, u_t)\f$
*
* \param delta_time Prediction duration \f$\Delta t\f$
* \param state Previous state \f$x_{t}\f$
* \param input Control input \f$u_t\f$
*
* Once the conditional have been set, may either sample from this model
* since it also represents a conditional distribution or you may map
* a SNV noise term \f$v_t\f$ onto the distribution using
* \c map_standard_variate(\f$v_t\f$) if implemented.
*/
virtual void condition(const double& delta_time,
const State& state,
const Input& input = Input()) { }
/**
* Predicts the state conditioned on the previous state and input.
*
* \param delta_time Prediction duration \f$\Delta t\f$
* \param state Previous state \f$x_{t}\f$
* \param noise Additive or non-Additive noise \f$v_t\f$
* \param input Control input \f$u_t\f$
*
* \return State \f$x_{t+1}\sim p(x\mid x_t, u_t)\f$
*/
/// \todo have a default argument for the input, a default function which
/// has to be implemented by the derived classes
virtual State predict_state(double delta_time,
const State& state,
const Noise& noise,
const Input& input) = 0;
/**
* \return \f$\dim(x_t)\f$, dimension of the state
*/
virtual constexpr int state_dimension() const = 0;
/**
* \return \f$\dim(v_t)\f$, dimension of the noise
*/
virtual constexpr int noise_dimension() const = 0;
/**
* \return \f$\dim(u_t)\f$, dimension of the control input
*/
virtual constexpr int input_dimension() const = 0;
};
}
#endif
<|endoftext|>
|
<commit_before>/*
Copyright 2014 Néstor Morales Hernández <[email protected]>
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 "rsgm_ros.h"
#include <ros/ros.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_listener.h>
#include <pcl-1.7/pcl/point_cloud.h>
#include <pcl-1.7/pcl/impl/point_types.hpp>
#include <tiff.h>
#include "rSGM/src/MyImage.hpp"
#include "rSGM/src/rSGMCmd.cpp"
const static string DISPARITY_NAMES_SGM_5x5 = "sgm_5x5";
const static string DISPARITY_NAMES_HCWS_CENSUS_9x7 = "hwcs_census_9x7";
const static string SAMPLING_NAMES_STANDARD_SGM = "standard_sgm";
const static string SAMPLING_NAMES_STRIPED_SGM = "striped_sgm";
const static string SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_2 = "striped_sgm_subsample_2";
const static string SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_4 = "striped_sgm_subsample_4";
namespace rsgm_ros {
RSGM_ROS::RSGM_ROS(const std::string& transport)
{
ros::NodeHandle nh;
int queue_size;
string dispMethod, samplingMethod;
int paths, threads, strips, dispCount;
ros::NodeHandle local_nh("~");
local_nh.param("queue_size", queue_size, 10);
local_nh.param("paths", paths, 8);
local_nh.param("threads", threads, 4);
local_nh.param("strips", strips, 4);
local_nh.param("disp_count", dispCount, 64);
m_paths = paths;
m_threads = threads;
m_strips = strips;
m_dispCount = dispCount;
local_nh.param("disparity_method", dispMethod, DISPARITY_NAMES_HCWS_CENSUS_9x7);
local_nh.param("sampling_method", samplingMethod, SAMPLING_NAMES_STRIPED_SGM);
if (dispMethod == DISPARITY_NAMES_SGM_5x5) {
m_disparityMethod = METHOD_SGM;
} else if (dispMethod == DISPARITY_NAMES_HCWS_CENSUS_9x7) {
m_disparityMethod = METHOD_HCWS_CENSUS;
} else {
ROS_ERROR("disparity_method %s not valid!. Try: [%s, %s]",
dispMethod.c_str(), DISPARITY_NAMES_SGM_5x5.c_str(), DISPARITY_NAMES_HCWS_CENSUS_9x7.c_str());
ROS_INFO("Aborting...");
exit(0);
}
if (samplingMethod == SAMPLING_NAMES_STANDARD_SGM) {
m_samplingMethod = STANDARD_SGM;
} else if (samplingMethod == SAMPLING_NAMES_STRIPED_SGM) {
m_samplingMethod = STRIPED_SGM;
} else if (samplingMethod == SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_2) {
m_samplingMethod = STRIPED_SGM_SUBSAMPLE_2;
} else if (samplingMethod == SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_4) {
m_samplingMethod = STRIPED_SGM_SUBSAMPLE_4;
} else {
ROS_ERROR("sampling_method %s not valid!. Try: [%s, %s, %s. %s]",
samplingMethod.c_str(), SAMPLING_NAMES_STANDARD_SGM.c_str(), SAMPLING_NAMES_STRIPED_SGM.c_str(),
SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_2.c_str(), SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_4.c_str());
ROS_INFO("Aborting...");
exit(0);
}
ROS_INFO("PARAMS INFO");
ROS_INFO("===========");
ROS_INFO("paths: %d", m_paths);
ROS_INFO("threads: %d", m_threads);
ROS_INFO("strips: %d", m_strips);
ROS_INFO("disp_count: %d", m_dispCount);
ROS_INFO("disparity_method: %s", dispMethod.c_str());
ROS_INFO("sampling_method: %s", samplingMethod.c_str());
// Topics
std::string stereo_ns = nh.resolveName("stereo");
std::string left_topic = ros::names::clean(stereo_ns + "/left/" + nh.resolveName("image"));
std::string right_topic = ros::names::clean(stereo_ns + "/right/" + nh.resolveName("image"));
std::string left_info_topic = stereo_ns + "/left/camera_info";
std::string right_info_topic = stereo_ns + "/right/camera_info";
image_transport::ImageTransport it(nh);
m_left_sub.subscribe(it, left_topic, 1, transport);
m_right_sub.subscribe(it, right_topic, 1, transport);
m_left_info_sub.subscribe(nh, left_info_topic, 1);
m_right_info_sub.subscribe(nh, right_info_topic, 1);
// Synchronize input topics. Optionally do approximate synchronization.
bool approx;
local_nh.param("approximate_sync", approx, false);
if (approx)
{
m_approximate_sync.reset(new ApproximateSync(ApproximatePolicy(queue_size),
m_left_sub, m_right_sub, m_left_info_sub, m_right_info_sub) );
m_approximate_sync->registerCallback(boost::bind(&RSGM_ROS::process, this, _1, _2, _3, _4));
}
else
{
m_exact_sync.reset(new ExactSync(ExactPolicy(queue_size),
m_left_sub, m_right_sub, m_left_info_sub, m_right_info_sub) );
m_exact_sync->registerCallback(boost::bind(&RSGM_ROS::process, this, _1, _2, _3, _4));
}
}
void RSGM_ROS::process(const sensor_msgs::ImageConstPtr& l_image_msg,
const sensor_msgs::ImageConstPtr& r_image_msg,
const sensor_msgs::CameraInfoConstPtr& l_info_msg,
const sensor_msgs::CameraInfoConstPtr& r_info_msg)
{
INIT_CLOCK(startCompute)
cv_bridge::CvImageConstPtr leftImgPtr, rightImgPtr;
leftImgPtr = cv_bridge::toCvShare(l_image_msg, sensor_msgs::image_encodings::MONO8);
rightImgPtr = cv_bridge::toCvShare(r_image_msg, sensor_msgs::image_encodings::MONO8);
m_model.fromCameraInfo(*l_info_msg, *r_info_msg);
MyImage_t myImgLeft = fromCVtoMyImage(leftImgPtr->image);
MyImage_t myImgRight = fromCVtoMyImage(rightImgPtr->image);
MyImage<uint8> disp(myImgLeft.getWidth(), myImgLeft.getHeight());
// start processing
float32* dispImgLeft = (float32*)_mm_malloc(myImgLeft.getWidth()*myImgLeft.getHeight()*sizeof(float32), 16);
float32* dispImgRight = (float32*)_mm_malloc(myImgLeft.getWidth()*myImgLeft.getHeight()*sizeof(float32), 16);
uint8* leftImg = myImgLeft.getData();
uint8* rightImg = myImgRight.getData();
// enum Disparity_Method_t { METHOD_SGM = 0, METHOD_HCWS_CENSUS = 1 };
switch (m_disparityMethod) {
case METHOD_SGM: {
processCensus5x5SGM(leftImg, rightImg, dispImgLeft, dispImgRight,
myImgLeft.getWidth(), myImgLeft.getHeight(),
m_disparityMethod, m_paths, m_threads, m_strips, m_dispCount);
break;
}
case METHOD_HCWS_CENSUS: {
processCensus9x7SGM(leftImg, rightImg, dispImgLeft, dispImgRight,
myImgLeft.getWidth(), myImgLeft.getHeight(),
m_disparityMethod, m_paths, m_threads, m_strips, m_dispCount);
break;
}
default: {
ROS_ERROR("[At %s:%d] This message should never be shown. Aborting...", __FILE__, __LINE__);
}
}
// write output
uint8* dispOut = disp.getData();
for (uint32 i = 0; i < myImgLeft.getWidth()*myImgLeft.getHeight(); i++) {
if (dispImgLeft[i]>0) {
dispOut[i] = (uint8)dispImgLeft[i];
}
else {
dispOut[i] = 0;
}
}
END_CLOCK(totalCompute, startCompute)
ROS_INFO("[%s] Total time: %f seconds", __FILE__, totalCompute);
cv::Mat dispMap = fromMyImagetoOpenCV(disp);
double min = 0;
double max = m_dispCount;
// cv::minMaxIdx(dispMap, &min, &max);
cv::Mat adjMap;
// expand your range to 0..255. Similar to histEq();
dispMap.convertTo(adjMap,CV_8UC1, 255 / (max-min), -min);
cout << "min " << min << endl;
cout << "max " << max << endl;
// this is great. It converts your grayscale image into a tone-mapped one,
// much more pleasing for the eye
// function is found in contrib module, so include contrib.hpp
// and link accordingly
cv::Mat falseColorsMap;
applyColorMap(adjMap, falseColorsMap, cv::COLORMAP_RAINBOW);
cv::imshow("Out", falseColorsMap);
// writePGM(disp, "/tmp/disp.pgm", true);
// cv::imshow("left", leftImg2);
uint8_t keycode;
keycode = cv::waitKey(200);
if (keycode == 27) {
exit(0);
}
ros::spinOnce();
}
RSGM_ROS::MyImage_t RSGM_ROS::fromCVtoMyImage(const cv::Mat& img)
{
MyImage_t myImg;
const uint32 & width = img.cols;
const uint32 & height = img.rows;
// copy values
MyImage_Data_t* data = (MyImage_Data_t*)_mm_malloc(width * height * sizeof(MyImage_Data_t), 16);
memcpy(data, img.data, width*height*sizeof(MyImage_Data_t));
myImg.setAttributes(width, height, data);
return myImg;
}
cv::Mat RSGM_ROS::fromMyImagetoOpenCV(RSGM_ROS::MyImage_t& myImg)
{
const uint32 width = myImg.getWidth();
const uint32 height = myImg.getHeight();
MyImage_Data_t* data = myImg.getData();
cv::Mat img(height, width, CV_8UC1);
memcpy(img.data, data, width * height * sizeof(MyImage_Data_t));
return img;
}
}<commit_msg>Original code has been modified, so now it accepts up to 8 processors as input. However, times doesn not seem to improve. The patch needs to be updated.<commit_after>/*
Copyright 2014 Néstor Morales Hernández <[email protected]>
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 "rsgm_ros.h"
#include <ros/ros.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_listener.h>
#include <pcl-1.7/pcl/point_cloud.h>
#include <pcl-1.7/pcl/impl/point_types.hpp>
#include <tiff.h>
#include "rSGM/src/MyImage.hpp"
#include "rSGM/src/rSGMCmd.cpp"
const static string DISPARITY_NAMES_SGM_5x5 = "sgm_5x5";
const static string DISPARITY_NAMES_HCWS_CENSUS_9x7 = "hwcs_census_9x7";
const static string SAMPLING_NAMES_STANDARD_SGM = "standard_sgm";
const static string SAMPLING_NAMES_STRIPED_SGM = "striped_sgm";
const static string SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_2 = "striped_sgm_subsample_2";
const static string SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_4 = "striped_sgm_subsample_4";
namespace rsgm_ros {
RSGM_ROS::RSGM_ROS(const std::string& transport)
{
ros::NodeHandle nh;
int queue_size;
string dispMethod, samplingMethod;
int paths, threads, strips, dispCount;
ros::NodeHandle local_nh("~");
local_nh.param("queue_size", queue_size, 10);
local_nh.param("paths", paths, 8);
local_nh.param("threads", threads, 8);
local_nh.param("strips", strips, 8);
local_nh.param("disp_count", dispCount, 64);
m_paths = paths;
m_threads = threads;
m_strips = strips;
m_dispCount = dispCount;
local_nh.param("disparity_method", dispMethod, DISPARITY_NAMES_HCWS_CENSUS_9x7);
local_nh.param("sampling_method", samplingMethod, SAMPLING_NAMES_STRIPED_SGM);
if (dispMethod == DISPARITY_NAMES_SGM_5x5) {
m_disparityMethod = METHOD_SGM;
} else if (dispMethod == DISPARITY_NAMES_HCWS_CENSUS_9x7) {
m_disparityMethod = METHOD_HCWS_CENSUS;
} else {
ROS_ERROR("disparity_method %s not valid!. Try: [%s, %s]",
dispMethod.c_str(), DISPARITY_NAMES_SGM_5x5.c_str(), DISPARITY_NAMES_HCWS_CENSUS_9x7.c_str());
ROS_INFO("Aborting...");
exit(0);
}
if (samplingMethod == SAMPLING_NAMES_STANDARD_SGM) {
m_samplingMethod = STANDARD_SGM;
} else if (samplingMethod == SAMPLING_NAMES_STRIPED_SGM) {
m_samplingMethod = STRIPED_SGM;
} else if (samplingMethod == SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_2) {
m_samplingMethod = STRIPED_SGM_SUBSAMPLE_2;
} else if (samplingMethod == SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_4) {
m_samplingMethod = STRIPED_SGM_SUBSAMPLE_4;
} else {
ROS_ERROR("sampling_method %s not valid!. Try: [%s, %s, %s. %s]",
samplingMethod.c_str(), SAMPLING_NAMES_STANDARD_SGM.c_str(), SAMPLING_NAMES_STRIPED_SGM.c_str(),
SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_2.c_str(), SAMPLING_NAMES_STRIPED_SGM_SUBSAMPLE_4.c_str());
ROS_INFO("Aborting...");
exit(0);
}
if (m_threads != 2 && m_threads != 4 && m_threads != 8) {
ROS_ERROR("The number of threads is %d", m_threads);
ROS_ERROR("It should be 2, 4 or 8!!!");
ROS_INFO("Aborting...");
exit(0);
}
if ((m_strips / m_threads == 0) || (m_strips % m_threads != 0)) {
ROS_ERROR("The number of strips can not be smaller than the number of threads!!!");
ROS_ERROR("Division between the number of strips and threads should be exact!!!");
ROS_ERROR("Number of threads: %d", m_threads);
ROS_ERROR("Number of strips: %d", m_strips);
ROS_INFO("Aborting...");
exit(0);
}
ROS_INFO("PARAMS INFO");
ROS_INFO("===========");
ROS_INFO("paths: %d", m_paths);
ROS_INFO("threads: %d", m_threads);
ROS_INFO("strips: %d", m_strips);
ROS_INFO("disp_count: %d", m_dispCount);
ROS_INFO("disparity_method: %s", dispMethod.c_str());
ROS_INFO("sampling_method: %s", samplingMethod.c_str());
// Topics
std::string stereo_ns = nh.resolveName("stereo");
std::string left_topic = ros::names::clean(stereo_ns + "/left/" + nh.resolveName("image"));
std::string right_topic = ros::names::clean(stereo_ns + "/right/" + nh.resolveName("image"));
std::string left_info_topic = stereo_ns + "/left/camera_info";
std::string right_info_topic = stereo_ns + "/right/camera_info";
image_transport::ImageTransport it(nh);
m_left_sub.subscribe(it, left_topic, 1, transport);
m_right_sub.subscribe(it, right_topic, 1, transport);
m_left_info_sub.subscribe(nh, left_info_topic, 1);
m_right_info_sub.subscribe(nh, right_info_topic, 1);
// Synchronize input topics. Optionally do approximate synchronization.
bool approx;
local_nh.param("approximate_sync", approx, false);
if (approx)
{
m_approximate_sync.reset(new ApproximateSync(ApproximatePolicy(queue_size),
m_left_sub, m_right_sub, m_left_info_sub, m_right_info_sub) );
m_approximate_sync->registerCallback(boost::bind(&RSGM_ROS::process, this, _1, _2, _3, _4));
}
else
{
m_exact_sync.reset(new ExactSync(ExactPolicy(queue_size),
m_left_sub, m_right_sub, m_left_info_sub, m_right_info_sub) );
m_exact_sync->registerCallback(boost::bind(&RSGM_ROS::process, this, _1, _2, _3, _4));
}
}
void RSGM_ROS::process(const sensor_msgs::ImageConstPtr& l_image_msg,
const sensor_msgs::ImageConstPtr& r_image_msg,
const sensor_msgs::CameraInfoConstPtr& l_info_msg,
const sensor_msgs::CameraInfoConstPtr& r_info_msg)
{
INIT_CLOCK(startCompute)
cv_bridge::CvImageConstPtr leftImgPtr, rightImgPtr;
leftImgPtr = cv_bridge::toCvShare(l_image_msg, sensor_msgs::image_encodings::MONO8);
rightImgPtr = cv_bridge::toCvShare(r_image_msg, sensor_msgs::image_encodings::MONO8);
m_model.fromCameraInfo(*l_info_msg, *r_info_msg);
MyImage_t myImgLeft = fromCVtoMyImage(leftImgPtr->image);
MyImage_t myImgRight = fromCVtoMyImage(rightImgPtr->image);
MyImage<uint8> disp(myImgLeft.getWidth(), myImgLeft.getHeight());
// start processing
float32* dispImgLeft = (float32*)_mm_malloc(myImgLeft.getWidth()*myImgLeft.getHeight()*sizeof(float32), 16);
float32* dispImgRight = (float32*)_mm_malloc(myImgLeft.getWidth()*myImgLeft.getHeight()*sizeof(float32), 16);
uint8* leftImg = myImgLeft.getData();
uint8* rightImg = myImgRight.getData();
// enum Disparity_Method_t { METHOD_SGM = 0, METHOD_HCWS_CENSUS = 1 };
switch (m_disparityMethod) {
case METHOD_SGM: {
processCensus5x5SGM(leftImg, rightImg, dispImgLeft, dispImgRight,
myImgLeft.getWidth(), myImgLeft.getHeight(),
m_disparityMethod, m_paths, m_threads, m_strips, m_dispCount);
break;
}
case METHOD_HCWS_CENSUS: {
processCensus9x7SGM(leftImg, rightImg, dispImgLeft, dispImgRight,
myImgLeft.getWidth(), myImgLeft.getHeight(),
m_disparityMethod, m_paths, m_threads, m_strips, m_dispCount);
break;
}
default: {
ROS_ERROR("[At %s:%d] This message should never be shown. Aborting...", __FILE__, __LINE__);
}
}
// write output
uint8* dispOut = disp.getData();
for (uint32 i = 0; i < myImgLeft.getWidth()*myImgLeft.getHeight(); i++) {
if (dispImgLeft[i]>0) {
dispOut[i] = (uint8)dispImgLeft[i];
}
else {
dispOut[i] = 0;
}
}
END_CLOCK(totalCompute, startCompute)
ROS_INFO("[%s] Total time: %f seconds", __FILE__, totalCompute);
cv::Mat dispMap = fromMyImagetoOpenCV(disp);
double min = 0;
double max = m_dispCount;
// cv::minMaxIdx(dispMap, &min, &max);
cv::Mat adjMap;
// expand your range to 0..255. Similar to histEq();
dispMap.convertTo(adjMap,CV_8UC1, 255 / (max-min), -min);
cout << "min " << min << endl;
cout << "max " << max << endl;
// this is great. It converts your grayscale image into a tone-mapped one,
// much more pleasing for the eye
// function is found in contrib module, so include contrib.hpp
// and link accordingly
cv::Mat falseColorsMap;
applyColorMap(adjMap, falseColorsMap, cv::COLORMAP_RAINBOW);
cv::imshow("Out", falseColorsMap);
// writePGM(disp, "/tmp/disp.pgm", true);
// cv::imshow("left", leftImg2);
uint8_t keycode;
keycode = cv::waitKey(200);
if (keycode == 27) {
exit(0);
}
ros::spinOnce();
}
RSGM_ROS::MyImage_t RSGM_ROS::fromCVtoMyImage(const cv::Mat& img)
{
MyImage_t myImg;
const uint32 & width = img.cols;
const uint32 & height = img.rows;
// copy values
MyImage_Data_t* data = (MyImage_Data_t*)_mm_malloc(width * height * sizeof(MyImage_Data_t), 16);
memcpy(data, img.data, width*height*sizeof(MyImage_Data_t));
myImg.setAttributes(width, height, data);
return myImg;
}
cv::Mat RSGM_ROS::fromMyImagetoOpenCV(RSGM_ROS::MyImage_t& myImg)
{
const uint32 width = myImg.getWidth();
const uint32 height = myImg.getHeight();
MyImage_Data_t* data = myImg.getData();
cv::Mat img(height, width, CV_8UC1);
memcpy(img.data, data, width * height * sizeof(MyImage_Data_t));
return img;
}
}<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008-2014 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "textinput.h"
#include <QStyleOptionFrame>
#include <IrcCommandParser>
#include <IrcBufferModel>
#include <IrcConnection>
#include <IrcCompleter>
#include <IrcBuffer>
#include <QKeyEvent>
#include <QPainter>
TextInput::TextInput(QWidget* parent) : QLineEdit(parent)
{
setAttribute(Qt::WA_MacShowFocusRect, false);
d.hint = "...";
d.index = 0;
d.buffer = 0;
d.parser = 0;
d.completer = new IrcCompleter(this);
connect(this, SIGNAL(bufferChanged(IrcBuffer*)), d.completer, SLOT(setBuffer(IrcBuffer*)));
connect(this, SIGNAL(parserChanged(IrcCommandParser*)), d.completer, SLOT(setParser(IrcCommandParser*)));
connect(d.completer, SIGNAL(completed(QString,int)), this, SLOT(doComplete(QString,int)));
connect(this, SIGNAL(textEdited(QString)), d.completer, SLOT(reset()));
connect(this, SIGNAL(returnPressed()), this, SLOT(sendInput()));
connect(this, SIGNAL(textChanged(QString)), this, SLOT(updateHint(QString)));
}
IrcBuffer* TextInput::buffer() const
{
return d.buffer;
}
IrcCommandParser* TextInput::parser() const
{
return d.parser;
}
static void bind(IrcBuffer* buffer, IrcCommandParser* parser)
{
if (buffer && parser) {
IrcBufferModel* model = buffer->model();
QObject::connect(model, SIGNAL(channelsChanged(QStringList)), parser, SLOT(setChannels(QStringList)));
QObject::connect(buffer, SIGNAL(titleChanged(QString)), parser, SLOT(setTarget(QString)));
parser->setTarget(buffer->title());
parser->setChannels(buffer->model()->channels());
} else if (parser) {
parser->reset();
}
}
static void unbind(IrcBuffer* buffer, IrcCommandParser* parser)
{
if (buffer && parser) {
IrcBufferModel* model = buffer->model();
QObject::disconnect(model, SIGNAL(channelsChanged(QStringList)), parser, SLOT(setChannels(QStringList)));
QObject::disconnect(buffer, SIGNAL(titleChanged(QString)), parser, SLOT(setTarget(QString)));
}
}
void TextInput::setBuffer(IrcBuffer* buffer)
{
if (d.buffer != buffer) {
unbind(d.buffer, d.parser);
bind(buffer, d.parser);
if (d.buffer)
d.states.insert(d.buffer, saveState());
d.buffer = buffer;
if (buffer)
restoreState(d.states.value(buffer));
emit bufferChanged(buffer);
}
}
void TextInput::setParser(IrcCommandParser* parser)
{
if (d.parser != parser) {
unbind(d.buffer, d.parser);
bind(d.buffer, parser);
d.parser = parser;
emit parserChanged(parser);
}
}
bool TextInput::event(QEvent* event)
{
if (event->type() == QEvent::KeyPress) {
switch (static_cast<QKeyEvent*>(event)->key()) {
case Qt::Key_Tab:
tryComplete();
return true;
case Qt::Key_Up:
goBackward();
return true;
case Qt::Key_Down:
goForward();
return true;
default:
break;
}
}
return QLineEdit::event(event);
}
// copied from qlineedit.cpp:
#define vMargin 1
#define hMargin 2
void TextInput::paintEvent(QPaintEvent* event)
{
QLineEdit::paintEvent(event);
if (!d.hint.isEmpty()) {
QStyleOptionFrameV2 option;
initStyleOption(&option);
QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &option, this);
int left, top, right, bottom;
getTextMargins(&left, &top, &right, &bottom);
left += qMax(0, -fontMetrics().minLeftBearing());
r.adjust(left, top, -right, -bottom);
r.adjust(hMargin, vMargin, -hMargin, -vMargin);
QString txt = text();
if (!txt.isEmpty()) {
if (!txt.endsWith(" "))
txt += " ";
r.adjust(fontMetrics().width(txt), 0, 0, 0);
}
QPainter painter(this);
QColor color = palette().text().color();
color.setAlpha(128);
painter.setPen(color);
QString hint = fontMetrics().elidedText(d.hint, Qt::ElideRight, r.width());
painter.drawText(r, alignment(), hint);
}
}
void TextInput::updateHint(const QString& text)
{
QString match;
QStringList params;
QStringList suggestions;
if (d.parser) {
if (text.startsWith('/')) {
QStringList words = text.mid(1).split(" ");
QString command = words.value(0);
params = words.mid(1);
foreach (const QString& available, d.parser->commands()) {
if (!command.compare(available, Qt::CaseInsensitive)) {
match = available;
break;
} else if (params.isEmpty() && available.startsWith(command, Qt::CaseInsensitive)) {
suggestions += available;
}
}
}
}
if (!match.isEmpty()) {
QStringList syntax = d.parser->syntax(match).split(" ", QString::SkipEmptyParts).mid(1);
if (!params.isEmpty())
d.hint = QStringList(syntax.mid(params.count() - 1)).join(" ");
else
d.hint = syntax.join(" ");
} else if (suggestions.isEmpty()) {
d.hint = text.isEmpty() ? "..." : "";
} else if (suggestions.count() == 1) {
d.hint = d.parser->syntax(suggestions.first());
} else {
d.hint = suggestions.join(" ");
}
}
void TextInput::goBackward()
{
if (!text().isEmpty() && !d.history.contains(text()))
d.current = text();
if (d.index > 0)
setText(d.history.value(--d.index));
}
void TextInput::goForward()
{
if (d.index < d.history.count())
setText(d.history.value(++d.index));
if (text().isEmpty())
setText(d.current);
}
void TextInput::sendInput()
{
IrcBuffer* b = buffer();
IrcCommandParser* p = parser();
IrcConnection* c = b ? b->connection() : 0;
if (!c || !p)
return;
if (!text().isEmpty()) {
d.current.clear();
d.history.append(text());
d.index = d.history.count();
}
bool error = false;
const QStringList lines = text().split(QRegExp("[\\r\\n]"), QString::SkipEmptyParts);
foreach (const QString& line, lines) {
if (!line.trimmed().isEmpty()) {
IrcCommand* cmd = p->parse(line);
if (cmd) {
cmd->setProperty("TextInput", true);
b->sendCommand(cmd);
if (cmd->type() == IrcCommand::Message || cmd->type() == IrcCommand::Notice || cmd->type() == IrcCommand::CtcpAction)
b->receiveMessage(cmd->toMessage(c->nickName(), c));
} else {
error = true;
}
}
}
if (!error)
clear();
}
void TextInput::tryComplete()
{
d.completer->complete(text(), cursorPosition());
}
void TextInput::doComplete(const QString& text, int cursor)
{
setText(text);
setCursorPosition(cursor);
}
QByteArray TextInput::saveState() const
{
QByteArray data;
QDataStream out(&data, QIODevice::WriteOnly);
out << d.index << d.current << d.history;
out << text() << cursorPosition() << selectionStart() << selectedText().length();
return data;
}
void TextInput::restoreState(const QByteArray& state)
{
QDataStream in(state);
in >> d.index >> d.current >> d.history;
QString txt;
int pos, start, len;
in >> txt >> pos >> start >> len;
setText(txt);
setCursorPosition(pos);
if (start != -1)
setSelection(start, len);
}
<commit_msg>Nag about pasting several lines (#82)<commit_after>/*
* Copyright (C) 2008-2014 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "textinput.h"
#include <QStyleOptionFrame>
#include <IrcCommandParser>
#include <IrcBufferModel>
#include <IrcConnection>
#include <IrcCompleter>
#include <QMessageBox>
#include <QSettings>
#include <QCheckBox>
#include <IrcBuffer>
#include <QKeyEvent>
#include <QPainter>
TextInput::TextInput(QWidget* parent) : QLineEdit(parent)
{
setAttribute(Qt::WA_MacShowFocusRect, false);
d.hint = "...";
d.index = 0;
d.buffer = 0;
d.parser = 0;
d.completer = new IrcCompleter(this);
connect(this, SIGNAL(bufferChanged(IrcBuffer*)), d.completer, SLOT(setBuffer(IrcBuffer*)));
connect(this, SIGNAL(parserChanged(IrcCommandParser*)), d.completer, SLOT(setParser(IrcCommandParser*)));
connect(d.completer, SIGNAL(completed(QString,int)), this, SLOT(doComplete(QString,int)));
connect(this, SIGNAL(textEdited(QString)), d.completer, SLOT(reset()));
connect(this, SIGNAL(returnPressed()), this, SLOT(sendInput()));
connect(this, SIGNAL(textChanged(QString)), this, SLOT(updateHint(QString)));
}
IrcBuffer* TextInput::buffer() const
{
return d.buffer;
}
IrcCommandParser* TextInput::parser() const
{
return d.parser;
}
static void bind(IrcBuffer* buffer, IrcCommandParser* parser)
{
if (buffer && parser) {
IrcBufferModel* model = buffer->model();
QObject::connect(model, SIGNAL(channelsChanged(QStringList)), parser, SLOT(setChannels(QStringList)));
QObject::connect(buffer, SIGNAL(titleChanged(QString)), parser, SLOT(setTarget(QString)));
parser->setTarget(buffer->title());
parser->setChannels(buffer->model()->channels());
} else if (parser) {
parser->reset();
}
}
static void unbind(IrcBuffer* buffer, IrcCommandParser* parser)
{
if (buffer && parser) {
IrcBufferModel* model = buffer->model();
QObject::disconnect(model, SIGNAL(channelsChanged(QStringList)), parser, SLOT(setChannels(QStringList)));
QObject::disconnect(buffer, SIGNAL(titleChanged(QString)), parser, SLOT(setTarget(QString)));
}
}
void TextInput::setBuffer(IrcBuffer* buffer)
{
if (d.buffer != buffer) {
unbind(d.buffer, d.parser);
bind(buffer, d.parser);
if (d.buffer)
d.states.insert(d.buffer, saveState());
d.buffer = buffer;
if (buffer)
restoreState(d.states.value(buffer));
emit bufferChanged(buffer);
}
}
void TextInput::setParser(IrcCommandParser* parser)
{
if (d.parser != parser) {
unbind(d.buffer, d.parser);
bind(d.buffer, parser);
d.parser = parser;
emit parserChanged(parser);
}
}
bool TextInput::event(QEvent* event)
{
if (event->type() == QEvent::KeyPress) {
switch (static_cast<QKeyEvent*>(event)->key()) {
case Qt::Key_Tab:
tryComplete();
return true;
case Qt::Key_Up:
goBackward();
return true;
case Qt::Key_Down:
goForward();
return true;
default:
break;
}
}
return QLineEdit::event(event);
}
// copied from qlineedit.cpp:
#define vMargin 1
#define hMargin 2
void TextInput::paintEvent(QPaintEvent* event)
{
QLineEdit::paintEvent(event);
if (!d.hint.isEmpty()) {
QStyleOptionFrameV2 option;
initStyleOption(&option);
QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &option, this);
int left, top, right, bottom;
getTextMargins(&left, &top, &right, &bottom);
left += qMax(0, -fontMetrics().minLeftBearing());
r.adjust(left, top, -right, -bottom);
r.adjust(hMargin, vMargin, -hMargin, -vMargin);
QString txt = text();
if (!txt.isEmpty()) {
if (!txt.endsWith(" "))
txt += " ";
r.adjust(fontMetrics().width(txt), 0, 0, 0);
}
QPainter painter(this);
QColor color = palette().text().color();
color.setAlpha(128);
painter.setPen(color);
QString hint = fontMetrics().elidedText(d.hint, Qt::ElideRight, r.width());
painter.drawText(r, alignment(), hint);
}
}
void TextInput::updateHint(const QString& text)
{
QString match;
QStringList params;
QStringList suggestions;
if (d.parser) {
if (text.startsWith('/')) {
QStringList words = text.mid(1).split(" ");
QString command = words.value(0);
params = words.mid(1);
foreach (const QString& available, d.parser->commands()) {
if (!command.compare(available, Qt::CaseInsensitive)) {
match = available;
break;
} else if (params.isEmpty() && available.startsWith(command, Qt::CaseInsensitive)) {
suggestions += available;
}
}
}
}
if (!match.isEmpty()) {
QStringList syntax = d.parser->syntax(match).split(" ", QString::SkipEmptyParts).mid(1);
if (!params.isEmpty())
d.hint = QStringList(syntax.mid(params.count() - 1)).join(" ");
else
d.hint = syntax.join(" ");
} else if (suggestions.isEmpty()) {
d.hint = text.isEmpty() ? "..." : "";
} else if (suggestions.count() == 1) {
d.hint = d.parser->syntax(suggestions.first());
} else {
d.hint = suggestions.join(" ");
}
}
void TextInput::goBackward()
{
if (!text().isEmpty() && !d.history.contains(text()))
d.current = text();
if (d.index > 0)
setText(d.history.value(--d.index));
}
void TextInput::goForward()
{
if (d.index < d.history.count())
setText(d.history.value(++d.index));
if (text().isEmpty())
setText(d.current);
}
void TextInput::sendInput()
{
IrcBuffer* b = buffer();
IrcCommandParser* p = parser();
IrcConnection* c = b ? b->connection() : 0;
if (!c || !p)
return;
const QStringList lines = text().split(QRegExp("[\\r\\n]"), QString::SkipEmptyParts);
#if QT_VERSION >= 0x050200
if (lines.count() > 2) {
QSettings settings;
bool warn = settings.value("warn", true).toBool();
if (warn) {
QMessageBox msgBox;
msgBox.setText(tr("The input contains more than two lines."));
msgBox.setInformativeText(tr("IRC is not a suitable medium for pasting multiple lines of text. Consider using a pastebin site instead.\n\n"
"Do you still want to proceed and send %1 lines of text?\n").arg(lines.count()));
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
QCheckBox* checkBox = new QCheckBox(tr("Do not show again"), &msgBox);
msgBox.setCheckBox(checkBox);
int res = msgBox.exec();
settings.setValue("warn", !checkBox->isChecked());
if (res != QMessageBox::Yes)
return;
}
}
#endif
if (!text().isEmpty()) {
d.current.clear();
d.history.append(text());
d.index = d.history.count();
}
bool error = false;
foreach (const QString& line, lines) {
if (!line.trimmed().isEmpty()) {
IrcCommand* cmd = p->parse(line);
if (cmd) {
cmd->setProperty("TextInput", true);
b->sendCommand(cmd);
if (cmd->type() == IrcCommand::Message || cmd->type() == IrcCommand::Notice || cmd->type() == IrcCommand::CtcpAction)
b->receiveMessage(cmd->toMessage(c->nickName(), c));
} else {
error = true;
}
}
}
if (!error)
clear();
}
void TextInput::tryComplete()
{
d.completer->complete(text(), cursorPosition());
}
void TextInput::doComplete(const QString& text, int cursor)
{
setText(text);
setCursorPosition(cursor);
}
QByteArray TextInput::saveState() const
{
QByteArray data;
QDataStream out(&data, QIODevice::WriteOnly);
out << d.index << d.current << d.history;
out << text() << cursorPosition() << selectionStart() << selectedText().length();
return data;
}
void TextInput::restoreState(const QByteArray& state)
{
QDataStream in(state);
in >> d.index >> d.current >> d.history;
QString txt;
int pos, start, len;
in >> txt >> pos >> start >> len;
setText(txt);
setCursorPosition(pos);
if (start != -1)
setSelection(start, len);
}
<|endoftext|>
|
<commit_before>#include "derivations.hh"
#include "store-api.hh"
#include "globals.hh"
#include "util.hh"
namespace nix {
Path writeDerivation(const Derivation & drv, const string & name)
{
PathSet references;
references.insert(drv.inputSrcs.begin(), drv.inputSrcs.end());
foreach (DerivationInputs::const_iterator, i, drv.inputDrvs)
references.insert(i->first);
/* Note that the outputs of a derivation are *not* references
(that can be missing (of course) and should not necessarily be
held during a garbage collection). */
string suffix = name + drvExtension;
string contents = unparseDerivation(drv);
return readOnlyMode
? computeStorePathForText(suffix, contents, references)
: store->addTextToStore(suffix, contents, references);
}
static Path parsePath(std::istream & str)
{
string s = parseString(str);
if (s.size() == 0 || s[0] != '/')
throw Error(format("bad path `%1%' in derivation") % s);
return s;
}
static StringSet parseStrings(std::istream & str, bool arePaths)
{
StringSet res;
while (!endOfList(str))
res.insert(arePaths ? parsePath(str) : parseString(str));
return res;
}
Derivation parseDerivation(const string & s)
{
Derivation drv;
std::istringstream str(s);
expect(str, "Derive([");
/* Parse the list of outputs. */
while (!endOfList(str)) {
DerivationOutput out;
expect(str, "("); string id = parseString(str);
expect(str, ","); out.path = parsePath(str);
expect(str, ","); out.hashAlgo = parseString(str);
expect(str, ","); out.hash = parseString(str);
expect(str, ")");
drv.outputs[id] = out;
}
/* Parse the list of input derivations. */
expect(str, ",[");
while (!endOfList(str)) {
expect(str, "(");
Path drvPath = parsePath(str);
expect(str, ",[");
drv.inputDrvs[drvPath] = parseStrings(str, false);
expect(str, ")");
}
expect(str, ",["); drv.inputSrcs = parseStrings(str, true);
expect(str, ","); drv.platform = parseString(str);
expect(str, ","); drv.builder = parseString(str);
/* Parse the builder arguments. */
expect(str, ",[");
while (!endOfList(str))
drv.args.push_back(parseString(str));
/* Parse the environment variables. */
expect(str, ",[");
while (!endOfList(str)) {
expect(str, "("); string name = parseString(str);
expect(str, ","); string value = parseString(str);
expect(str, ")");
drv.env[name] = value;
}
expect(str, ")");
return drv;
}
void printString(std::ostream & str, const string & s)
{
str << "\"";
for (const char * i = s.c_str(); *i; i++)
if (*i == '\"' || *i == '\\') str << "\\" << *i;
else if (*i == '\n') str << "\\n";
else if (*i == '\r') str << "\\r";
else if (*i == '\t') str << "\\t";
else str << *i;
str << "\"";
}
template<class ForwardIterator>
void printStrings(std::ostream & str, ForwardIterator i, ForwardIterator j)
{
str << "[";
bool first = true;
for ( ; i != j; ++i) {
if (first) first = false; else str << ",";
printString(str, *i);
}
str << "]";
}
string unparseDerivation(const Derivation & drv)
{
std::ostringstream str;
str << "Derive([";
bool first = true;
foreach (DerivationOutputs::const_iterator, i, drv.outputs) {
if (first) first = false; else str << ",";
str << "("; printString(str, i->first);
str << ","; printString(str, i->second.path);
str << ","; printString(str, i->second.hashAlgo);
str << ","; printString(str, i->second.hash);
str << ")";
}
str << "],[";
first = true;
foreach (DerivationInputs::const_iterator, i, drv.inputDrvs) {
if (first) first = false; else str << ",";
str << "("; printString(str, i->first);
str << ","; printStrings(str, i->second.begin(), i->second.end());
str << ")";
}
str << "],";
printStrings(str, drv.inputSrcs.begin(), drv.inputSrcs.end());
str << ","; printString(str, drv.platform);
str << ","; printString(str, drv.builder);
str << ","; printStrings(str, drv.args.begin(), drv.args.end());
str << ",[";
first = true;
foreach (StringPairs::const_iterator, i, drv.env) {
if (first) first = false; else str << ",";
str << "("; printString(str, i->first);
str << ","; printString(str, i->second);
str << ")";
}
str << "])";
return str.str();
}
bool isDerivation(const string & fileName)
{
return hasSuffix(fileName, drvExtension);
}
}
<commit_msg>* Don't use an ostringstream in unparseDerivation(), because it's slow. A `nix-env -qa --drv-path \*' on Nixpkgs was spending 40% of its time in unparseDerivation() because of this (now 11%).<commit_after>#include "derivations.hh"
#include "store-api.hh"
#include "globals.hh"
#include "util.hh"
namespace nix {
Path writeDerivation(const Derivation & drv, const string & name)
{
PathSet references;
references.insert(drv.inputSrcs.begin(), drv.inputSrcs.end());
foreach (DerivationInputs::const_iterator, i, drv.inputDrvs)
references.insert(i->first);
/* Note that the outputs of a derivation are *not* references
(that can be missing (of course) and should not necessarily be
held during a garbage collection). */
string suffix = name + drvExtension;
string contents = unparseDerivation(drv);
return readOnlyMode
? computeStorePathForText(suffix, contents, references)
: store->addTextToStore(suffix, contents, references);
}
static Path parsePath(std::istream & str)
{
string s = parseString(str);
if (s.size() == 0 || s[0] != '/')
throw Error(format("bad path `%1%' in derivation") % s);
return s;
}
static StringSet parseStrings(std::istream & str, bool arePaths)
{
StringSet res;
while (!endOfList(str))
res.insert(arePaths ? parsePath(str) : parseString(str));
return res;
}
Derivation parseDerivation(const string & s)
{
Derivation drv;
std::istringstream str(s);
expect(str, "Derive([");
/* Parse the list of outputs. */
while (!endOfList(str)) {
DerivationOutput out;
expect(str, "("); string id = parseString(str);
expect(str, ","); out.path = parsePath(str);
expect(str, ","); out.hashAlgo = parseString(str);
expect(str, ","); out.hash = parseString(str);
expect(str, ")");
drv.outputs[id] = out;
}
/* Parse the list of input derivations. */
expect(str, ",[");
while (!endOfList(str)) {
expect(str, "(");
Path drvPath = parsePath(str);
expect(str, ",[");
drv.inputDrvs[drvPath] = parseStrings(str, false);
expect(str, ")");
}
expect(str, ",["); drv.inputSrcs = parseStrings(str, true);
expect(str, ","); drv.platform = parseString(str);
expect(str, ","); drv.builder = parseString(str);
/* Parse the builder arguments. */
expect(str, ",[");
while (!endOfList(str))
drv.args.push_back(parseString(str));
/* Parse the environment variables. */
expect(str, ",[");
while (!endOfList(str)) {
expect(str, "("); string name = parseString(str);
expect(str, ","); string value = parseString(str);
expect(str, ")");
drv.env[name] = value;
}
expect(str, ")");
return drv;
}
static void printString(string & res, const string & s)
{
res += '"';
for (const char * i = s.c_str(); *i; i++)
if (*i == '\"' || *i == '\\') { res += "\\"; res += *i; }
else if (*i == '\n') res += "\\n";
else if (*i == '\r') res += "\\r";
else if (*i == '\t') res += "\\t";
else res += *i;
res += '"';
}
template<class ForwardIterator>
static void printStrings(string & res, ForwardIterator i, ForwardIterator j)
{
res += '[';
bool first = true;
for ( ; i != j; ++i) {
if (first) first = false; else res += ',';
printString(res, *i);
}
res += ']';
}
string unparseDerivation(const Derivation & drv)
{
string s;
s.reserve(65536);
s += "Derive([";
bool first = true;
foreach (DerivationOutputs::const_iterator, i, drv.outputs) {
if (first) first = false; else s += ',';
s += '('; printString(s, i->first);
s += ','; printString(s, i->second.path);
s += ','; printString(s, i->second.hashAlgo);
s += ','; printString(s, i->second.hash);
s += ')';
}
s += "],[";
first = true;
foreach (DerivationInputs::const_iterator, i, drv.inputDrvs) {
if (first) first = false; else s += ',';
s += '('; printString(s, i->first);
s += ','; printStrings(s, i->second.begin(), i->second.end());
s += ')';
}
s += "],";
printStrings(s, drv.inputSrcs.begin(), drv.inputSrcs.end());
s += ','; printString(s, drv.platform);
s += ','; printString(s, drv.builder);
s += ','; printStrings(s, drv.args.begin(), drv.args.end());
s += ",[";
first = true;
foreach (StringPairs::const_iterator, i, drv.env) {
if (first) first = false; else s += ',';
s += '('; printString(s, i->first);
s += ','; printString(s, i->second);
s += ')';
}
s += "])";
return s;
}
bool isDerivation(const string & fileName)
{
return hasSuffix(fileName, drvExtension);
}
}
<|endoftext|>
|
<commit_before>#include "dsa_common.h"
#include "module_loader.h"
#include "../module/broker_security_manager.h"
#include "broker_config.h"
#include "module/default/console_logger.h"
#include <boost/dll/import.hpp>
#include <boost/function.hpp>
#include <iostream>
#include <boost/bind.hpp>
namespace bf=boost::filesystem;
namespace dsa {
boost::function<api_creators_func::security_manager_type> ModuleLoader::security_manager_creator = 0;
boost::function<api_creators_func::logger_type> ModuleLoader::logger_creator = 0;
ModuleLoader::ModuleLoader(ref_<BrokerConfig> config) {
if(security_manager_creator.empty())
{
security_manager_creator = get_create_function<api_creators_func::security_manager_type>(
"security_manager_", "create_security_manager",
[](App& app, ref_<LinkStrand> strand){return make_ref_<BrokerSecurityManager>(strand);});
}
if(logger_creator.empty())
{
logger_creator = get_create_function<api_creators_func::logger_type>(
"logger_", "create_logger",
[](App& app, ref_<LinkStrand> strand){return std::unique_ptr<Logger>(new ConsoleLogger());});
}
}
std::unique_ptr<Logger> ModuleLoader::new_logger(App &app, ref_<LinkStrand> strand) {
return logger_creator(app, strand);
}
ref_<SecurityManager> ModuleLoader::new_security_manager(App &app, ref_<LinkStrand> strand) {
return security_manager_creator(app, strand);
}
template<typename T>
boost::function<T> ModuleLoader::get_create_function(string_ module_name, string_ function_name,
boost::function<T> default_function)
{
bf::path lib_path("./module");
auto module_suffix = boost::dll::shared_library::suffix();
// There is no module directory returning default function
if(!bf::is_directory(lib_path)) return default_function;
// Iterate directory files
std::vector<bf::path> module_paths;
bf::directory_iterator end_itr;
for (bf::directory_iterator itr(lib_path); itr != end_itr; ++itr)
{
if (bf::is_regular_file(itr->path())) {
auto file_name = itr->path().filename().string();
auto file_suffix = itr->path().extension();
if(file_name.compare(0, module_name.length(), module_name) == 0 &&
file_suffix == module_suffix)
{
module_paths.push_back(itr->path());
}
}
}
// analyze results
bf::path shared_library_path;
if(module_paths.size() == 1)
shared_library_path = module_paths[0];
if(module_paths.size() > 1)
std::cout<< "There is more than one module for "<< module_name << "so we can't decide which one will be used"<< std::endl;
if(shared_library_path.empty()) return default_function;
// we found our shared lib, get create function from it
try{
return boost::dll::import_alias<T>(shared_library_path, function_name);
}
catch (int e) {
std::cout<<"Exception while loading " << module_name <<std::endl;
}
// error occurred so returning default again
return default_function;
}
}<commit_msg>System exits with error if two of same shared file in the directory<commit_after>#include "dsa_common.h"
#include "module_loader.h"
#include "../module/broker_security_manager.h"
#include "broker_config.h"
#include "module/default/console_logger.h"
#include <boost/dll/import.hpp>
#include <boost/function.hpp>
#include <iostream>
#include <boost/bind.hpp>
namespace bf=boost::filesystem;
namespace dsa {
boost::function<api_creators_func::security_manager_type> ModuleLoader::security_manager_creator = 0;
boost::function<api_creators_func::logger_type> ModuleLoader::logger_creator = 0;
ModuleLoader::ModuleLoader(ref_<BrokerConfig> config) {
if(security_manager_creator.empty())
{
security_manager_creator = get_create_function<api_creators_func::security_manager_type>(
"security_manager_", "create_security_manager",
[](App& app, ref_<LinkStrand> strand){return make_ref_<BrokerSecurityManager>(strand);});
}
if(logger_creator.empty())
{
logger_creator = get_create_function<api_creators_func::logger_type>(
"logger_", "create_logger",
[](App& app, ref_<LinkStrand> strand){return std::unique_ptr<Logger>(new ConsoleLogger());});
}
}
std::unique_ptr<Logger> ModuleLoader::new_logger(App &app, ref_<LinkStrand> strand) {
return logger_creator(app, strand);
}
ref_<SecurityManager> ModuleLoader::new_security_manager(App &app, ref_<LinkStrand> strand) {
return security_manager_creator(app, strand);
}
template<typename T>
boost::function<T> ModuleLoader::get_create_function(string_ module_name, string_ function_name,
boost::function<T> default_function)
{
bf::path lib_path("./module");
auto module_suffix = boost::dll::shared_library::suffix();
// There is no module directory returning default function
if(!bf::is_directory(lib_path)) return default_function;
// Iterate directory files
std::vector<bf::path> module_paths;
bf::directory_iterator end_itr;
for (bf::directory_iterator itr(lib_path); itr != end_itr; ++itr)
{
if (bf::is_regular_file(itr->path())) {
auto file_name = itr->path().filename().string();
auto file_suffix = itr->path().extension();
if(file_name.compare(0, module_name.length(), module_name) == 0 &&
file_suffix == module_suffix)
{
module_paths.push_back(itr->path());
}
}
}
// analyze results
bf::path shared_library_path;
if(module_paths.size() == 1)
shared_library_path = module_paths[0];
if(module_paths.size() > 1)
{
std::cout<< "There is more than one module for "<< module_name << "so we can't decide which one will be used"<< std::endl;
exit(1);
}
if(shared_library_path.empty()) return default_function;
// we found our shared lib, get create function from it
try{
return boost::dll::import_alias<T>(shared_library_path, function_name);
}
catch (int e) {
std::cout<<"Exception while loading " << module_name <<std::endl;
}
// error occurred so returning default again
return default_function;
}
}<|endoftext|>
|
<commit_before>#include <Element.h>
#include <FWApplication.h>
#include <ElementNotInitializedException.h>
#include <PlatformThread.h>
#include <TextLabel.h>
#include <cassert>
#include <iostream>
#include <typeinfo>
using namespace std;
std::unordered_map<int, Element *> Element::registered_elements;
Mutex Element::mutex;
Element::~Element() {
if (unregisterElement(this)) {
if (auto ptr = thread.lock()) {
Command c(Command::DELETE_ELEMENT, getInternalId());
ptr->sendCommand(c);
}
}
}
void
Element::initialize(std::shared_ptr<PlatformThread> _thread) {
assert(_thread.get());
if (_thread.get()) {
thread = _thread;
registerElement(this);
prepare();
if (isVisible()) {
initializeContent();
} else {
cerr << "skipping initialization of " << typeid(*this).name() << endl;
}
}
}
void
Element::initializeContent() {
cerr << "initializing content of " << typeid(*this).name() << endl;
if (auto t = thread.lock()) {
is_content_initialized = true;
create();
if (!pendingCommands.empty()) {
if (t->isInTransaction()) {
for (auto & c : pendingCommands) {
t->sendCommand(c);
}
} else {
t->sendCommands(pendingCommands);
}
pendingCommands.clear();
}
for (auto & c : getChildren()) {
c->initialize(t);
}
load();
}
}
void
Element::setError(bool t) {
if ((t && !has_error) || (!t && has_error)) {
has_error = t;
Command c(Command::SET_ERROR, getInternalId());
c.setValue(t ? 1 : 0);
if (t) c.setTextValue("Arvo ei kelpaa!");
sendCommand(c);
}
}
void
Element::show() {
is_visible = true;
if (!is_content_initialized) {
initializeContent();
}
Command c(Command::SET_VISIBILITY, getInternalId());
c.setValue(1);
sendCommand(c);
}
void
Element::hide() {
is_visible = false;
Command c(Command::SET_VISIBILITY, getInternalId());
c.setValue(0);
sendCommand(c);
}
void
Element::stop() {
sendCommand(Command(Command::STOP, getInternalId()));
}
Element &
Element::style(Selector s, const std::string & key, const std::string & value) {
Command c(Command::SET_STYLE, getInternalId());
c.setValue(int(s));
c.setTextValue(key);
c.setTextValue2(value);
sendCommand(c);
return *this;
}
void
Element::begin() {
if (auto ptr = thread.lock()) {
ptr->beginBatch();
}
}
void
Element::commit() {
if (auto ptr = thread.lock()) {
ptr->commitBatch();
}
}
void
Element::sendCommand(const Command & command) {
if (auto ptr = thread.lock()) {
ptr->sendCommand(command);
} else {
pendingCommands.push_back(command);
}
}
void
Element::onEvent(Event & ev) {
if (!ev.isHandled() && ev.getTTL()) {
ev.decTTL();
if (ev.isBroadcast()) {
for (auto & c : getChildren()){
ev.dispatch(*c);
}
} else if (parent) {
ev.dispatch(*parent);
}
ev.incTTL();
}
}
void
Element::showToast(const std::string & message, int duration) {
Command c(Command::CREATE_TOAST, getParentInternalId(), getInternalId());
c.setTextValue(message);
c.setValue(duration);
sendCommand(c);
}
void
Element::launchBrowser(const std::string & input_url) {
sendCommand(Command(Command::LAUNCH_BROWSER, getInternalId(), input_url));
}
Element &
Element::addChild(const std::shared_ptr<Element> & element) {
assert(element);
element->setParent(this);
children.push_back(element);
if (auto ptr = thread.lock()) {
element->initialize(ptr);
}
return *element;
}
Element &
Element::addChild(const std::string & text) {
return addChild(std::make_shared<TextLabel>(text));
}
FWApplication &
Element::getApplication() {
if (auto ptr = thread.lock()) {
return ptr->getApplication();
} else {
throw ElementNotInitializedException();
}
}
const FWApplication &
Element::getApplication() const {
if (auto ptr = thread.lock()) {
return ptr->getApplication();
} else {
throw ElementNotInitializedException();
}
}
void
Element::removeChildren() {
for (auto & child : children) {
sendCommand(Command(Command::REMOVE_CHILD, getInternalId(), child->getInternalId()));
}
children.clear();
}
void
Element::removeChild(Element * child) {
if (child) {
child->setParent(0);
for (auto it = children.begin(); it != children.end(); it++) {
if (it->get() == child) {
sendCommand(Command(Command::REMOVE_CHILD, getInternalId(), child->getInternalId()));
children.erase(it);
return;
}
}
}
}
int
Element::createTimer(int timeout_ms) {
int timer_id = getNextInternalId();
Command c(Command::CREATE_TIMER, getInternalId(), timer_id);
c.setValue(timeout_ms);
sendCommand(c);
return timer_id;
}
int
Element::showModal(const std::shared_ptr<Element> & dialog) {
addChild(dialog);
if (auto ptr = thread.lock()) {
return ptr->startModal();
} else {
return 0;
}
}
<commit_msg>refactor, always create content<commit_after>#include <Element.h>
#include <FWApplication.h>
#include <ElementNotInitializedException.h>
#include <PlatformThread.h>
#include <TextLabel.h>
#include <cassert>
#include <iostream>
#include <typeinfo>
using namespace std;
std::unordered_map<int, Element *> Element::registered_elements;
Mutex Element::mutex;
Element::~Element() {
if (unregisterElement(this)) {
if (auto ptr = thread.lock()) {
Command c(Command::DELETE_ELEMENT, getInternalId());
ptr->sendCommand(c);
}
}
}
void
Element::initialize(std::shared_ptr<PlatformThread> _thread) {
assert(_thread.get());
if (_thread.get()) {
thread = _thread;
registerElement(this);
prepare();
if (1 || isVisible()) {
initializeContent();
} else {
cerr << "skipping initialization of " << typeid(*this).name() << endl;
}
}
}
void
Element::initializeContent() {
cerr << "initializing content of " << typeid(*this).name() << endl;
if (auto t = thread.lock()) {
is_content_initialized = true;
create();
if (!pendingCommands.empty()) {
if (t->isInTransaction()) {
for (auto & c : pendingCommands) {
t->sendCommand(c);
}
} else {
t->sendCommands(pendingCommands);
}
pendingCommands.clear();
}
for (auto & c : getChildren()) {
c->initialize(t);
}
load();
}
}
void
Element::setError(bool t) {
if ((t && !has_error) || (!t && has_error)) {
has_error = t;
Command c(Command::SET_ERROR, getInternalId());
c.setValue(t ? 1 : 0);
if (t) c.setTextValue("Arvo ei kelpaa!");
sendCommand(c);
}
}
void
Element::show() {
is_visible = true;
if (!is_content_initialized) {
initializeContent();
}
Command c(Command::SET_VISIBILITY, getInternalId());
c.setValue(1);
sendCommand(c);
}
void
Element::hide() {
is_visible = false;
Command c(Command::SET_VISIBILITY, getInternalId());
c.setValue(0);
sendCommand(c);
}
void
Element::stop() {
sendCommand(Command(Command::STOP, getInternalId()));
}
Element &
Element::style(Selector s, const std::string & key, const std::string & value) {
Command c(Command::SET_STYLE, getInternalId());
c.setValue(int(s));
c.setTextValue(key);
c.setTextValue2(value);
sendCommand(c);
return *this;
}
void
Element::begin() {
if (auto ptr = thread.lock()) {
ptr->beginBatch();
}
}
void
Element::commit() {
if (auto ptr = thread.lock()) {
ptr->commitBatch();
}
}
void
Element::sendCommand(const Command & command) {
if (is_content_initialized) {
if (auto ptr = thread.lock()) {
ptr->sendCommand(command);
return;
}
}
pendingCommands.push_back(command);
}
void
Element::onEvent(Event & ev) {
if (!ev.isHandled() && ev.getTTL()) {
ev.decTTL();
if (ev.isBroadcast()) {
for (auto & c : getChildren()){
ev.dispatch(*c);
}
} else if (parent) {
ev.dispatch(*parent);
}
ev.incTTL();
}
}
void
Element::showToast(const std::string & message, int duration) {
Command c(Command::CREATE_TOAST, getParentInternalId(), getInternalId());
c.setTextValue(message);
c.setValue(duration);
sendCommand(c);
}
void
Element::launchBrowser(const std::string & input_url) {
sendCommand(Command(Command::LAUNCH_BROWSER, getInternalId(), input_url));
}
Element &
Element::addChild(const std::shared_ptr<Element> & element) {
assert(element);
element->setParent(this);
children.push_back(element);
if (auto ptr = thread.lock()) {
element->initialize(ptr);
}
return *element;
}
Element &
Element::addChild(const std::string & text) {
return addChild(std::make_shared<TextLabel>(text));
}
FWApplication &
Element::getApplication() {
if (auto ptr = thread.lock()) {
return ptr->getApplication();
} else {
throw ElementNotInitializedException();
}
}
const FWApplication &
Element::getApplication() const {
if (auto ptr = thread.lock()) {
return ptr->getApplication();
} else {
throw ElementNotInitializedException();
}
}
void
Element::removeChildren() {
for (auto & child : children) {
sendCommand(Command(Command::REMOVE_CHILD, getInternalId(), child->getInternalId()));
}
children.clear();
}
void
Element::removeChild(Element * child) {
if (child) {
child->setParent(0);
for (auto it = children.begin(); it != children.end(); it++) {
if (it->get() == child) {
sendCommand(Command(Command::REMOVE_CHILD, getInternalId(), child->getInternalId()));
children.erase(it);
return;
}
}
}
}
int
Element::createTimer(int timeout_ms) {
int timer_id = getNextInternalId();
Command c(Command::CREATE_TIMER, getInternalId(), timer_id);
c.setValue(timeout_ms);
sendCommand(c);
return timer_id;
}
int
Element::showModal(const std::shared_ptr<Element> & dialog) {
addChild(dialog);
if (auto ptr = thread.lock()) {
return ptr->startModal();
} else {
return 0;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/fscapi.h"
//#include "crtdbg.h"
#include "base/messages.h"
#include "base/Log.h"
#include "base/util/ArrayList.h"
#include "base/util/StringBuffer.h"
#include "spds/spdsutils.h"
#include "spds/constants.h"
#include "client/SyncClient.h"
#include "client/DMTClientConfig.h"
#include "examples/TestSyncSource.h"
#include "examples/TestSyncSource2.h"
#include "filter/AllClause.h"
#include "filter/ClauseUtil.h"
#include "filter/LogicalClause.h"
#include "filter/FieldClause.h"
#include "filter/SourceFilter.h"
#include "filter/WhereClause.h"
#include "syncml/core/core.h"
#include "syncml/formatter/Formatter.h"
#include "spds/DefaultConfigFactory.h"
#include "examples/listeners/TestSyncListener.h"
#include "examples/listeners/TestSyncSourceListener.h"
#include "examples/listeners/TestSyncStatusListener.h"
#include "examples/listeners/TestSyncItemListener.h"
#include "examples/listeners/TestTransportListener.h"
#include "event/SetListener.h"
// Define the test configuration
#include "examples/config.h"
void testFilter();
void testClause();
void testConfigFilter();
void testEncryption();
void createConfig(DMTClientConfig& config);
static void testXMLProcessor();
void printReport(SyncReport* sr, char* sourceName);
#define APPLICATION_URI "Funambol/SyncclientPIM"
#define LOG_TITLE "Funambol Win32 Example Log"
#define LOG_PATH "."
#define LOG_LEVEL LOG_LEVEL_DEBUG
#define SOURCE_NAME "briefcase"
#define WSOURCE_NAME TEXT("briefcase")
#define DEVICE_ID "Funambol Win32 Example"
// Define DEBUG_SETTINGS in your project to create a default configuration
// tree for the test client. WARNING: it will override any previous setting!
//
#ifdef DEBUG_SETTINGS
int settings(const char *root);
#endif
#ifdef _WIN32_WCE
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd ) {
#else
int main(int argc, char** argv) {
#endif
// Init LOG
Log(0, LOG_PATH, LOG_NAME);
LOG.reset(LOG_TITLE);
LOG.setLevel(LOG_LEVEL);
#if 0
_CrtSetDbgFlag (ON);
// Get current flag
int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
// Turn on leak-checking bit
tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
// Turn on automatic checks
tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
// Set flag to the new value
_CrtSetDbgFlag( tmpFlag );
#endif
#ifdef DEBUG_SETTINGS
if ( settings(APPLICATION_URI) ){
sprintf(logmsg, "Error %d setting config paramaters.", lastErrorCode);
LOG.error(logmsg);
return lastErrorCode;
}
#endif
#ifdef TEST_ENCODE
WCHAR *content = loadAndConvert(TEXT("message.xml"), TEXT("base64"));
if(!content) {
fprintf(stderr, "Error in uudecode.");
exit(1);
}
convertAndSave(TEXT("message_out.xml"), content, TEXT("base64"));
#endif
#ifdef TEST_EVENT_HANDLING
//
// Set listeners:
//
TestSyncListener* listener1 = new TestSyncListener();
TestSyncSourceListener* listener2 = new TestSyncSourceListener();
TestSyncStatusListener* listener3 = new TestSyncStatusListener();
TestSyncItemListener* listener4 = new TestSyncItemListener();
TestTransportListener* listener5 = new TestTransportListener();
setSyncListener (listener1);
setSyncSourceListener(listener2);
setSyncStatusListener(listener3);
setSyncItemListener (listener4);
setTransportListener (listener5);
#ifndef TEST_SYNCSOURCE
#define TEST_SYNCSOURCE 1
#endif
#endif
// ------------- Main sample client ------------------------
#ifdef TEST_SYNCSOURCE
//
// Create the configuration.
//
DMTClientConfig config(APPLICATION_URI);
// Read config from registry.
if (!config.read() ||
strcmp(config.getDeviceConfig().getDevID(), DEVICE_ID)) {
// Config not found -> generate a default config
createConfig(config);
}
//
// Create the SyncSource passing its name and its config.
//
TestSyncSource source(WSOURCE_NAME, config.getSyncSourceConfig(SOURCE_NAME));
SyncSource* ssArray[2];
ssArray[0] = &source;
ssArray[1] = NULL;
//
// Create the SyncClient passing the config.
//
SyncClient sampleClient;
// SYNC!
if( sampleClient.sync(config, ssArray) ) {
LOG.error("Error in sync.");
}
// Print sync results.
printReport(sampleClient.getSyncReport(), SOURCE_NAME);
// Save config to registry.
config.save();
#endif
// ----------------------------------------------------------
#ifdef TEST_EVENT_HANDLING
//
// Unset Listeners
//
unsetSyncListener ();
unsetSyncSourceListener();
unsetSyncStatusListener();
unsetSyncItemListener ();
unsetTransportListener ();
#endif
#ifdef TEST_SYNC_ENCRYPTION
Sync4jClient& s4j = Sync4jClient::getInstance();
s4j.setDMConfig(APPLICATION_URI);
TestSyncSource source = TestSyncSource(TEXT("briefcase"));
SyncSource** ssArray = new SyncSource*[2];
ssArray[0] = &source;
ssArray[1] = NULL;
s4j.sync(ssArray);
#endif
#ifdef TEST_ENCRYPTION
testEncryption();
#endif
#ifdef TEST_FILTER
testFilter();
#endif
#ifdef TEST_CLAUSE
testClause();
#endif
#ifdef TEST_CONFIG_FILTER
testConfigFilter();
#endif
#ifdef TEST_XMLPROCESSOR
testXMLProcessor();
#endif
return 0;
}
static void testXMLProcessor(void)
{
const char xml1[] =
"<document>\n\
<LocURI>./devinf11</LocURI>\n\
<plaintag>\n\
<attrtag attr=\"val\">content</attrtag>\n\
</plaintag>\n\
<emptytag/>\n\
</document>" ;
unsigned int pos = 0, start = 0, end = 0;
const char *p = 0;
// Get 'document' tag
char *doc = XMLProcessor::copyElementContent(xml1, "document", &pos);
LOG.debug("Document: '%s'", doc);
LOG.debug("xml[pos]= '%s'", xml1 + pos);
char buf[256];
// Get 'plaintag' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "plaintag", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Plaintag: '%s'", buf);
// Get 'LocURI' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "LocURI", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("LocURI: '%s'", buf);
// Get 'attrtag' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "attrtag", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Attrtag: '%s'", buf);
// Get 'attrtag' attr list, using start/end pos
if(!XMLProcessor::getElementAttributes(doc, "attrtag", &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Attrlist: '%s'", buf);
// Get 'emptytag' content, that should be empty
const char*empty = XMLProcessor::copyElementContent(doc, "emptytag");
if(!empty){
LOG.error("TEST FAILED.");
return;
}
LOG.debug("Emptytag: '%s'", empty);
if(doc)
delete [] doc;
if (empty)
delete [] empty;
}
//
// Function to create a default config.
//
void createConfig(DMTClientConfig& config) {
AccessConfig* ac = DefaultConfigFactory::getAccessConfig();
config.setAccessConfig(*ac);
delete ac;
DeviceConfig* dc = DefaultConfigFactory::getDeviceConfig();
dc->setDevID(DEVICE_ID); // So next time won't be generated, we always save config at the end.
dc->setMan ("Funambol");
config.setDeviceConfig(*dc);
delete dc;
SyncSourceConfig* sc = DefaultConfigFactory::getSyncSourceConfig(SOURCE_NAME);
sc->setEncoding("plain/text");
sc->setType ("text");
sc->setURI ("briefcase");
config.setSyncSourceConfig(*sc);
delete sc;
}
#include "base/util/StringBuffer.h"
//
// Prints a formatted report for the synchronization process.
//
void printReport(SyncReport* sr, const char*sourceName) {
StringBuffer res;
char tmp[512];
res = "===========================================================\n";
res.append("================ SYNCHRONIZATION REPORT ===============\n");
res.append("===========================================================\n");
sprintf(tmp, "Last error code = %d\n", sr->getLastErrorCode());
res.append(tmp);
sprintf(tmp, "Last error msg = %s\n\n", sr->getLastErrorMsg());
res.append(tmp);
res.append("----------|--------CLIENT---------|--------SERVER---------|\n");
res.append(" Source | NEW | MOD | DEL | NEW | MOD | DEL |\n");
res.append("----------|-----------------------------------------------|\n");
int sourceNumber = 1;
for (unsigned int i=0; i<sourceNumber; i++) {
SyncSourceReport* ssr = sr->getSyncSourceReport(sourceName);
sprintf(tmp, "%10s|", ssr->getSourceName());
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_ADD), ssr->getItemReportCount(CLIENT, COMMAND_ADD));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_REPLACE), ssr->getItemReportCount(CLIENT, COMMAND_REPLACE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_DELETE), ssr->getItemReportCount(CLIENT, COMMAND_DELETE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_ADD), ssr->getItemReportCount(SERVER, COMMAND_ADD));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_REPLACE), ssr->getItemReportCount(SERVER, COMMAND_REPLACE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|\n", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_DELETE), ssr->getItemReportCount(SERVER, COMMAND_DELETE));
res.append(tmp);
res.append("----------|-----------------------------------------------|\n\n");
sprintf(tmp, "%s:\n----------", ssr->getSourceName());
res.append(tmp);
sprintf(tmp, "\nSource State = %d\n", ssr->getState());
res.append(tmp);
sprintf(tmp, "Last error code = %d\n", ssr->getLastErrorCode());
res.append(tmp);
sprintf(tmp, "Last error msg = %s\n\n", ssr->getLastErrorMsg());
res.append(tmp);
}
printf("\n%s", res.c_str());
}
<commit_msg>fix printReport declaration<commit_after>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/fscapi.h"
//#include "crtdbg.h"
#include "base/messages.h"
#include "base/Log.h"
#include "base/util/ArrayList.h"
#include "base/util/StringBuffer.h"
#include "spds/spdsutils.h"
#include "spds/constants.h"
#include "client/SyncClient.h"
#include "client/DMTClientConfig.h"
#include "examples/TestSyncSource.h"
#include "examples/TestSyncSource2.h"
#include "filter/AllClause.h"
#include "filter/ClauseUtil.h"
#include "filter/LogicalClause.h"
#include "filter/FieldClause.h"
#include "filter/SourceFilter.h"
#include "filter/WhereClause.h"
#include "syncml/core/core.h"
#include "syncml/formatter/Formatter.h"
#include "spds/DefaultConfigFactory.h"
#include "examples/listeners/TestSyncListener.h"
#include "examples/listeners/TestSyncSourceListener.h"
#include "examples/listeners/TestSyncStatusListener.h"
#include "examples/listeners/TestSyncItemListener.h"
#include "examples/listeners/TestTransportListener.h"
#include "event/SetListener.h"
// Define the test configuration
#include "examples/config.h"
void testFilter();
void testClause();
void testConfigFilter();
void testEncryption();
void createConfig(DMTClientConfig& config);
static void testXMLProcessor();
void printReport(SyncReport* sr, const char* sourceName);
#define APPLICATION_URI "Funambol/SyncclientPIM"
#define LOG_TITLE "Funambol Win32 Example Log"
#define LOG_PATH "."
#define LOG_LEVEL LOG_LEVEL_DEBUG
#define SOURCE_NAME "briefcase"
#define WSOURCE_NAME TEXT("briefcase")
#define DEVICE_ID "Funambol Win32 Example"
// Define DEBUG_SETTINGS in your project to create a default configuration
// tree for the test client. WARNING: it will override any previous setting!
//
#ifdef DEBUG_SETTINGS
int settings(const char *root);
#endif
#ifdef _WIN32_WCE
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd ) {
#else
int main(int argc, char** argv) {
#endif
// Init LOG
Log(0, LOG_PATH, LOG_NAME);
LOG.reset(LOG_TITLE);
LOG.setLevel(LOG_LEVEL);
#if 0
_CrtSetDbgFlag (ON);
// Get current flag
int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
// Turn on leak-checking bit
tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
// Turn on automatic checks
tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
// Set flag to the new value
_CrtSetDbgFlag( tmpFlag );
#endif
#ifdef DEBUG_SETTINGS
if ( settings(APPLICATION_URI) ){
sprintf(logmsg, "Error %d setting config paramaters.", lastErrorCode);
LOG.error(logmsg);
return lastErrorCode;
}
#endif
#ifdef TEST_ENCODE
WCHAR *content = loadAndConvert(TEXT("message.xml"), TEXT("base64"));
if(!content) {
fprintf(stderr, "Error in uudecode.");
exit(1);
}
convertAndSave(TEXT("message_out.xml"), content, TEXT("base64"));
#endif
#ifdef TEST_EVENT_HANDLING
//
// Set listeners:
//
TestSyncListener* listener1 = new TestSyncListener();
TestSyncSourceListener* listener2 = new TestSyncSourceListener();
TestSyncStatusListener* listener3 = new TestSyncStatusListener();
TestSyncItemListener* listener4 = new TestSyncItemListener();
TestTransportListener* listener5 = new TestTransportListener();
setSyncListener (listener1);
setSyncSourceListener(listener2);
setSyncStatusListener(listener3);
setSyncItemListener (listener4);
setTransportListener (listener5);
#ifndef TEST_SYNCSOURCE
#define TEST_SYNCSOURCE 1
#endif
#endif
// ------------- Main sample client ------------------------
#ifdef TEST_SYNCSOURCE
//
// Create the configuration.
//
DMTClientConfig config(APPLICATION_URI);
// Read config from registry.
if (!config.read() ||
strcmp(config.getDeviceConfig().getDevID(), DEVICE_ID)) {
// Config not found -> generate a default config
createConfig(config);
}
//
// Create the SyncSource passing its name and its config.
//
TestSyncSource source(WSOURCE_NAME, config.getSyncSourceConfig(SOURCE_NAME));
SyncSource* ssArray[2];
ssArray[0] = &source;
ssArray[1] = NULL;
//
// Create the SyncClient passing the config.
//
SyncClient sampleClient;
// SYNC!
if( sampleClient.sync(config, ssArray) ) {
LOG.error("Error in sync.");
}
// Print sync results.
printReport(sampleClient.getSyncReport(), SOURCE_NAME);
// Save config to registry.
config.save();
#endif
// ----------------------------------------------------------
#ifdef TEST_EVENT_HANDLING
//
// Unset Listeners
//
unsetSyncListener ();
unsetSyncSourceListener();
unsetSyncStatusListener();
unsetSyncItemListener ();
unsetTransportListener ();
#endif
#ifdef TEST_SYNC_ENCRYPTION
Sync4jClient& s4j = Sync4jClient::getInstance();
s4j.setDMConfig(APPLICATION_URI);
TestSyncSource source = TestSyncSource(TEXT("briefcase"));
SyncSource** ssArray = new SyncSource*[2];
ssArray[0] = &source;
ssArray[1] = NULL;
s4j.sync(ssArray);
#endif
#ifdef TEST_ENCRYPTION
testEncryption();
#endif
#ifdef TEST_FILTER
testFilter();
#endif
#ifdef TEST_CLAUSE
testClause();
#endif
#ifdef TEST_CONFIG_FILTER
testConfigFilter();
#endif
#ifdef TEST_XMLPROCESSOR
testXMLProcessor();
#endif
return 0;
}
static void testXMLProcessor(void)
{
const char xml1[] =
"<document>\n\
<LocURI>./devinf11</LocURI>\n\
<plaintag>\n\
<attrtag attr=\"val\">content</attrtag>\n\
</plaintag>\n\
<emptytag/>\n\
</document>" ;
unsigned int pos = 0, start = 0, end = 0;
const char *p = 0;
// Get 'document' tag
char *doc = XMLProcessor::copyElementContent(xml1, "document", &pos);
LOG.debug("Document: '%s'", doc);
LOG.debug("xml[pos]= '%s'", xml1 + pos);
char buf[256];
// Get 'plaintag' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "plaintag", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Plaintag: '%s'", buf);
// Get 'LocURI' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "LocURI", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("LocURI: '%s'", buf);
// Get 'attrtag' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "attrtag", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Attrtag: '%s'", buf);
// Get 'attrtag' attr list, using start/end pos
if(!XMLProcessor::getElementAttributes(doc, "attrtag", &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Attrlist: '%s'", buf);
// Get 'emptytag' content, that should be empty
const char*empty = XMLProcessor::copyElementContent(doc, "emptytag");
if(!empty){
LOG.error("TEST FAILED.");
return;
}
LOG.debug("Emptytag: '%s'", empty);
if(doc)
delete [] doc;
if (empty)
delete [] empty;
}
//
// Function to create a default config.
//
void createConfig(DMTClientConfig& config) {
AccessConfig* ac = DefaultConfigFactory::getAccessConfig();
config.setAccessConfig(*ac);
delete ac;
DeviceConfig* dc = DefaultConfigFactory::getDeviceConfig();
dc->setDevID(DEVICE_ID); // So next time won't be generated, we always save config at the end.
dc->setMan ("Funambol");
config.setDeviceConfig(*dc);
delete dc;
SyncSourceConfig* sc = DefaultConfigFactory::getSyncSourceConfig(SOURCE_NAME);
sc->setEncoding("plain/text");
sc->setType ("text");
sc->setURI ("briefcase");
config.setSyncSourceConfig(*sc);
delete sc;
}
#include "base/util/StringBuffer.h"
//
// Prints a formatted report for the synchronization process.
//
void printReport(SyncReport* sr, const char*sourceName) {
StringBuffer res;
char tmp[512];
res = "===========================================================\n";
res.append("================ SYNCHRONIZATION REPORT ===============\n");
res.append("===========================================================\n");
sprintf(tmp, "Last error code = %d\n", sr->getLastErrorCode());
res.append(tmp);
sprintf(tmp, "Last error msg = %s\n\n", sr->getLastErrorMsg());
res.append(tmp);
res.append("----------|--------CLIENT---------|--------SERVER---------|\n");
res.append(" Source | NEW | MOD | DEL | NEW | MOD | DEL |\n");
res.append("----------|-----------------------------------------------|\n");
int sourceNumber = 1;
for (unsigned int i=0; i<sourceNumber; i++) {
SyncSourceReport* ssr = sr->getSyncSourceReport(sourceName);
sprintf(tmp, "%10s|", ssr->getSourceName());
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_ADD), ssr->getItemReportCount(CLIENT, COMMAND_ADD));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_REPLACE), ssr->getItemReportCount(CLIENT, COMMAND_REPLACE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_DELETE), ssr->getItemReportCount(CLIENT, COMMAND_DELETE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_ADD), ssr->getItemReportCount(SERVER, COMMAND_ADD));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_REPLACE), ssr->getItemReportCount(SERVER, COMMAND_REPLACE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|\n", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_DELETE), ssr->getItemReportCount(SERVER, COMMAND_DELETE));
res.append(tmp);
res.append("----------|-----------------------------------------------|\n\n");
sprintf(tmp, "%s:\n----------", ssr->getSourceName());
res.append(tmp);
sprintf(tmp, "\nSource State = %d\n", ssr->getState());
res.append(tmp);
sprintf(tmp, "Last error code = %d\n", ssr->getLastErrorCode());
res.append(tmp);
sprintf(tmp, "Last error msg = %s\n\n", ssr->getLastErrorMsg());
res.append(tmp);
}
printf("\n%s", res.c_str());
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "spds/ItemReport.h"
//--------------------------------------------------- Constructor & Destructor
ItemReport::ItemReport() {
status = 0;
id = NULL;
}
ItemReport::ItemReport(const WCHAR* luid, const int statusCode) {
id = NULL;
setStatus(statusCode);
setId(luid);
}
ItemReport::ItemReport(ItemReport& ir) {
assign(ir);
}
ItemReport::~ItemReport() {
if (id) {
delete [] id;
id = NULL;
}
}
//------------------------------------------------------------- Public Methods
const WCHAR* ItemReport::getId() const {
return id;
}
void ItemReport::setId(const WCHAR* v) {
if (id) {
delete [] id;
id = NULL;
}
id = _wcsdup(v);
}
const int ItemReport::getStatus() const {
return status;
}
void ItemReport::setStatus(const int v) {
status = v;
}
ArrayElement* ItemReport::clone() {
ItemReport* it = new ItemReport(getId(), getStatus());
return it;
}
void ItemReport::assign(const ItemReport& ir) {
setId (ir.getId ());
setStatus(ir.getStatus());
}
<commit_msg>corrected: _wcsdup() -> wstrdup()<commit_after>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "spds/ItemReport.h"
//--------------------------------------------------- Constructor & Destructor
ItemReport::ItemReport() {
status = 0;
id = NULL;
}
ItemReport::ItemReport(const WCHAR* luid, const int statusCode) {
id = NULL;
setStatus(statusCode);
setId(luid);
}
ItemReport::ItemReport(ItemReport& ir) {
assign(ir);
}
ItemReport::~ItemReport() {
if (id) {
delete [] id;
id = NULL;
}
}
//------------------------------------------------------------- Public Methods
const WCHAR* ItemReport::getId() const {
return id;
}
void ItemReport::setId(const WCHAR* v) {
if (id) {
delete [] id;
id = NULL;
}
id = wstrdup(v);
}
const int ItemReport::getStatus() const {
return status;
}
void ItemReport::setStatus(const int v) {
status = v;
}
ArrayElement* ItemReport::clone() {
ItemReport* it = new ItemReport(getId(), getStatus());
return it;
}
void ItemReport::assign(const ItemReport& ir) {
setId (ir.getId ());
setStatus(ir.getStatus());
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <string>
#include "gflags/gflags.h"
#include "webrtc/base/checks.h"
#include "webrtc/common_audio/channel_buffer.h"
#include "webrtc/common_audio/wav_file.h"
#include "webrtc/modules/audio_processing/include/audio_processing.h"
#include "webrtc/modules/audio_processing/test/test_utils.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
DEFINE_string(dump, "", "The name of the debug dump file to read from.");
DEFINE_string(c, "", "The name of the capture input file to read from.");
DEFINE_string(o, "out.wav", "Name of the capture output file to write to.");
DEFINE_int32(o_channels, 0, "Number of output channels. Defaults to input.");
DEFINE_int32(o_sample_rate, 0, "Output sample rate in Hz. Defaults to input.");
DEFINE_double(mic_spacing, 0.0,
"Microphone spacing in meters. Used when beamforming is enabled");
DEFINE_bool(aec, false, "Enable echo cancellation.");
DEFINE_bool(agc, false, "Enable automatic gain control.");
DEFINE_bool(hpf, false, "Enable high-pass filtering.");
DEFINE_bool(ns, false, "Enable noise suppression.");
DEFINE_bool(ts, false, "Enable transient suppression.");
DEFINE_bool(bf, false, "Enable beamforming.");
DEFINE_bool(all, false, "Enable all components.");
DEFINE_int32(ns_level, -1, "Noise suppression level [0 - 3].");
static const int kChunksPerSecond = 100;
static const char kUsage[] =
"Command-line tool to run audio processing on WAV files. Accepts either\n"
"an input capture WAV file or protobuf debug dump and writes to an output\n"
"WAV file.\n"
"\n"
"All components are disabled by default. If any bi-directional components\n"
"are enabled, only debug dump files are permitted.";
namespace webrtc {
int main(int argc, char* argv[]) {
{
const std::string program_name = argv[0];
const std::string usage = kUsage;
google::SetUsageMessage(usage);
}
google::ParseCommandLineFlags(&argc, &argv, true);
if (!((FLAGS_c == "") ^ (FLAGS_dump == ""))) {
fprintf(stderr,
"An input file must be specified with either -c or -dump.\n");
return 1;
}
if (FLAGS_dump != "") {
fprintf(stderr, "FIXME: the -dump option is not yet implemented.\n");
return 1;
}
WavReader c_file(FLAGS_c);
// If the output format is uninitialized, use the input format.
int o_channels = FLAGS_o_channels;
if (!o_channels)
o_channels = c_file.num_channels();
int o_sample_rate = FLAGS_o_sample_rate;
if (!o_sample_rate)
o_sample_rate = c_file.sample_rate();
WavWriter o_file(FLAGS_o, o_sample_rate, o_channels);
Config config;
config.Set<ExperimentalNs>(new ExperimentalNs(FLAGS_ts || FLAGS_all));
if (FLAGS_bf || FLAGS_all) {
if (FLAGS_mic_spacing <= 0) {
fprintf(stderr,
"mic_spacing must a positive value when beamforming is enabled.\n");
return 1;
}
const size_t num_mics = c_file.num_channels();
std::vector<Point> array_geometry;
array_geometry.reserve(num_mics);
for (size_t i = 0; i < num_mics; ++i) {
array_geometry.push_back(Point(0.0, i * FLAGS_mic_spacing, 0.0));
}
config.Set<Beamforming>(new Beamforming(true, array_geometry));
}
scoped_ptr<AudioProcessing> ap(AudioProcessing::Create(config));
if (FLAGS_dump != "") {
CHECK_EQ(kNoErr, ap->echo_cancellation()->Enable(FLAGS_aec || FLAGS_all));
} else if (FLAGS_aec) {
fprintf(stderr, "-aec requires a -dump file.\n");
return -1;
}
CHECK_EQ(kNoErr, ap->gain_control()->Enable(FLAGS_agc || FLAGS_all));
CHECK_EQ(kNoErr, ap->gain_control()->set_mode(GainControl::kFixedDigital));
CHECK_EQ(kNoErr, ap->high_pass_filter()->Enable(FLAGS_hpf || FLAGS_all));
CHECK_EQ(kNoErr, ap->noise_suppression()->Enable(FLAGS_ns || FLAGS_all));
if (FLAGS_ns_level != -1)
CHECK_EQ(kNoErr, ap->noise_suppression()->set_level(
static_cast<NoiseSuppression::Level>(FLAGS_ns_level)));
printf("Input file: %s\nChannels: %d, Sample rate: %d Hz\n\n",
FLAGS_c.c_str(), c_file.num_channels(), c_file.sample_rate());
printf("Output file: %s\nChannels: %d, Sample rate: %d Hz\n\n",
FLAGS_o.c_str(), o_file.num_channels(), o_file.sample_rate());
ChannelBuffer<float> c_buf(c_file.sample_rate() / kChunksPerSecond,
c_file.num_channels());
ChannelBuffer<float> o_buf(o_file.sample_rate() / kChunksPerSecond,
o_file.num_channels());
const size_t c_length = static_cast<size_t>(c_buf.length());
scoped_ptr<float[]> c_interleaved(new float[c_length]);
scoped_ptr<float[]> o_interleaved(new float[o_buf.length()]);
while (c_file.ReadSamples(c_length, c_interleaved.get()) == c_length) {
FloatS16ToFloat(c_interleaved.get(), c_length, c_interleaved.get());
Deinterleave(c_interleaved.get(), c_buf.samples_per_channel(),
c_buf.num_channels(), c_buf.channels());
CHECK_EQ(kNoErr,
ap->ProcessStream(c_buf.channels(),
c_buf.samples_per_channel(),
c_file.sample_rate(),
LayoutFromChannels(c_buf.num_channels()),
o_file.sample_rate(),
LayoutFromChannels(o_buf.num_channels()),
o_buf.channels()));
Interleave(o_buf.channels(), o_buf.samples_per_channel(),
o_buf.num_channels(), o_interleaved.get());
FloatToFloatS16(o_interleaved.get(), o_buf.length(), o_interleaved.get());
o_file.WriteSamples(o_interleaved.get(), o_buf.length());
}
return 0;
}
} // namespace webrtc
int main(int argc, char* argv[]) {
return webrtc::main(argc, argv);
}
<commit_msg>Add arbitrary microphone geometry input to audioproc_f test utility.<commit_after>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <sstream>
#include <string>
#include "gflags/gflags.h"
#include "webrtc/base/checks.h"
#include "webrtc/common_audio/channel_buffer.h"
#include "webrtc/common_audio/wav_file.h"
#include "webrtc/modules/audio_processing/include/audio_processing.h"
#include "webrtc/modules/audio_processing/test/test_utils.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
DEFINE_string(dump, "", "The name of the debug dump file to read from.");
DEFINE_string(c, "", "The name of the capture input file to read from.");
DEFINE_string(o, "out.wav", "Name of the capture output file to write to.");
DEFINE_int32(o_channels, 0, "Number of output channels. Defaults to input.");
DEFINE_int32(o_sample_rate, 0, "Output sample rate in Hz. Defaults to input.");
DEFINE_double(mic_spacing, 0.0,
"Alternate way to specify mic_positions. "
"Assumes uniform linear array with specified spacings.");
DEFINE_string(mic_positions, "",
"Space delimited cartesian coordinates of microphones in meters. "
"The coordinates of each point are contiguous. "
"For a two element array: \"x1 y1 z1 x2 y2 z2\"");
DEFINE_bool(aec, false, "Enable echo cancellation.");
DEFINE_bool(agc, false, "Enable automatic gain control.");
DEFINE_bool(hpf, false, "Enable high-pass filtering.");
DEFINE_bool(ns, false, "Enable noise suppression.");
DEFINE_bool(ts, false, "Enable transient suppression.");
DEFINE_bool(bf, false, "Enable beamforming.");
DEFINE_bool(all, false, "Enable all components.");
DEFINE_int32(ns_level, -1, "Noise suppression level [0 - 3].");
static const int kChunksPerSecond = 100;
static const char kUsage[] =
"Command-line tool to run audio processing on WAV files. Accepts either\n"
"an input capture WAV file or protobuf debug dump and writes to an output\n"
"WAV file.\n"
"\n"
"All components are disabled by default. If any bi-directional components\n"
"are enabled, only debug dump files are permitted.";
namespace webrtc {
namespace {
// Returns a vector<T> parsed from whitespace delimited values in to_parse,
// or an empty vector if the string could not be parsed.
template<typename T>
std::vector<T> parse_list(std::string to_parse) {
std::vector<T> values;
std::istringstream str(to_parse);
std::copy(
std::istream_iterator<T>(str),
std::istream_iterator<T>(),
std::back_inserter(values));
return values;
}
// Parses the array geometry from the command line.
//
// If a vector with size != num_mics is returned, an error has occurred and an
// appropriate error message has been printed to stdout.
std::vector<Point> get_array_geometry(size_t num_mics) {
std::vector<Point> result;
result.reserve(num_mics);
if (FLAGS_mic_positions.length()) {
CHECK(FLAGS_mic_spacing == 0.0 &&
"mic_positions and mic_spacing should not both be specified");
const std::vector<float> values = parse_list<float>(FLAGS_mic_positions);
if (values.size() != 3 * num_mics) {
fprintf(stderr,
"Could not parse mic_positions or incorrect number of points.\n");
} else {
for (size_t i = 0; i < values.size(); i += 3) {
double x = values[i + 0];
double y = values[i + 1];
double z = values[i + 2];
result.push_back(Point(x, y, z));
}
}
} else {
if (FLAGS_mic_spacing <= 0) {
fprintf(stderr,
"mic_spacing must a positive value when beamforming is enabled.\n");
} else {
for (size_t i = 0; i < num_mics; ++i) {
result.push_back(Point(0.0, i * FLAGS_mic_spacing, 0.0));
}
}
}
return result;
}
} // namespace
int main(int argc, char* argv[]) {
{
const std::string program_name = argv[0];
const std::string usage = kUsage;
google::SetUsageMessage(usage);
}
google::ParseCommandLineFlags(&argc, &argv, true);
if (!((FLAGS_c == "") ^ (FLAGS_dump == ""))) {
fprintf(stderr,
"An input file must be specified with either -c or -dump.\n");
return 1;
}
if (FLAGS_dump != "") {
fprintf(stderr, "FIXME: the -dump option is not yet implemented.\n");
return 1;
}
WavReader c_file(FLAGS_c);
// If the output format is uninitialized, use the input format.
int o_channels = FLAGS_o_channels;
if (!o_channels)
o_channels = c_file.num_channels();
int o_sample_rate = FLAGS_o_sample_rate;
if (!o_sample_rate)
o_sample_rate = c_file.sample_rate();
WavWriter o_file(FLAGS_o, o_sample_rate, o_channels);
Config config;
config.Set<ExperimentalNs>(new ExperimentalNs(FLAGS_ts || FLAGS_all));
if (FLAGS_bf || FLAGS_all) {
const size_t num_mics = c_file.num_channels();
const std::vector<Point> array_geometry = get_array_geometry(num_mics);
if (array_geometry.size() != num_mics) {
return 1;
}
config.Set<Beamforming>(new Beamforming(true, array_geometry));
}
scoped_ptr<AudioProcessing> ap(AudioProcessing::Create(config));
if (FLAGS_dump != "") {
CHECK_EQ(kNoErr, ap->echo_cancellation()->Enable(FLAGS_aec || FLAGS_all));
} else if (FLAGS_aec) {
fprintf(stderr, "-aec requires a -dump file.\n");
return -1;
}
CHECK_EQ(kNoErr, ap->gain_control()->Enable(FLAGS_agc || FLAGS_all));
CHECK_EQ(kNoErr, ap->gain_control()->set_mode(GainControl::kFixedDigital));
CHECK_EQ(kNoErr, ap->high_pass_filter()->Enable(FLAGS_hpf || FLAGS_all));
CHECK_EQ(kNoErr, ap->noise_suppression()->Enable(FLAGS_ns || FLAGS_all));
if (FLAGS_ns_level != -1)
CHECK_EQ(kNoErr, ap->noise_suppression()->set_level(
static_cast<NoiseSuppression::Level>(FLAGS_ns_level)));
printf("Input file: %s\nChannels: %d, Sample rate: %d Hz\n\n",
FLAGS_c.c_str(), c_file.num_channels(), c_file.sample_rate());
printf("Output file: %s\nChannels: %d, Sample rate: %d Hz\n\n",
FLAGS_o.c_str(), o_file.num_channels(), o_file.sample_rate());
ChannelBuffer<float> c_buf(c_file.sample_rate() / kChunksPerSecond,
c_file.num_channels());
ChannelBuffer<float> o_buf(o_file.sample_rate() / kChunksPerSecond,
o_file.num_channels());
const size_t c_length = static_cast<size_t>(c_buf.length());
scoped_ptr<float[]> c_interleaved(new float[c_length]);
scoped_ptr<float[]> o_interleaved(new float[o_buf.length()]);
while (c_file.ReadSamples(c_length, c_interleaved.get()) == c_length) {
FloatS16ToFloat(c_interleaved.get(), c_length, c_interleaved.get());
Deinterleave(c_interleaved.get(), c_buf.samples_per_channel(),
c_buf.num_channels(), c_buf.channels());
CHECK_EQ(kNoErr,
ap->ProcessStream(c_buf.channels(),
c_buf.samples_per_channel(),
c_file.sample_rate(),
LayoutFromChannels(c_buf.num_channels()),
o_file.sample_rate(),
LayoutFromChannels(o_buf.num_channels()),
o_buf.channels()));
Interleave(o_buf.channels(), o_buf.samples_per_channel(),
o_buf.num_channels(), o_interleaved.get());
FloatToFloatS16(o_interleaved.get(), o_buf.length(), o_interleaved.get());
o_file.WriteSamples(o_interleaved.get(), o_buf.length());
}
return 0;
}
} // namespace webrtc
int main(int argc, char* argv[]) {
return webrtc::main(argc, argv);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2011 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.
*/
#include "jni_internal.h"
#include "oat/utils/arm/assembler_arm.h"
#include "oat/runtime/oat_support_entrypoints.h"
#include "object.h"
#include "stack_indirect_reference_table.h"
#define __ assembler->
namespace art {
namespace arm {
ByteArray* ArmCreateResolutionTrampoline(Runtime::TrampolineType type) {
UniquePtr<ArmAssembler> assembler(static_cast<ArmAssembler*>(Assembler::Create(kArm)));
// | Out args |
// | Method* | <- SP on entry
// | LR | return address into caller
// | ... | callee saves
// | R3 | possible argument
// | R2 | possible argument
// | R1 | possible argument
// | R0 | junk on call to UnresolvedDirectMethodTrampolineFromCode, holds result Method*
// | Method* | Callee save Method* set up by UnresolvedDirectMethodTrampolineFromCode
// Save callee saves and ready frame for exception delivery
RegList save = (1 << R1) | (1 << R2) | (1 << R3) | (1 << R5) | (1 << R6) | (1 << R7) | (1 << R8) |
(1 << R10) | (1 << R11) | (1 << LR);
// TODO: enable when GetCalleeSaveMethod is available at stub generation time
// DCHECK_EQ(save, Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs)->GetCoreSpillMask());
__ PushList(save);
__ LoadFromOffset(kLoadWord, R12, TR,
ENTRYPOINT_OFFSET(pUnresolvedDirectMethodTrampolineFromCode));
__ mov(R2, ShifterOperand(TR)); // Pass Thread::Current() in R2
__ LoadImmediate(R3, type);
__ IncreaseFrameSize(8); // 2 words of space for alignment
__ mov(R1, ShifterOperand(SP)); // Pass SP
// Call to unresolved direct method trampoline (method_idx, sp, Thread*, is_static)
__ blx(R12);
__ mov(R12, ShifterOperand(R0)); // Save code address returned into R12
// Restore registers which may have been modified by GC, "R0" will hold the Method*
__ DecreaseFrameSize(4);
__ PopList((1 << R0) | save);
__ bx(R12); // Leaf call to method's code
__ bkpt(0);
assembler->EmitSlowPaths();
size_t cs = assembler->CodeSize();
SirtRef<ByteArray> resolution_trampoline(ByteArray::Alloc(cs));
CHECK(resolution_trampoline.get() != NULL);
MemoryRegion code(resolution_trampoline->GetData(), resolution_trampoline->GetLength());
assembler->FinalizeInstructions(code);
return resolution_trampoline.get();
}
typedef void (*ThrowAme)(Method*, Thread*);
ByteArray* CreateAbstractMethodErrorStub() {
UniquePtr<ArmAssembler> assembler(static_cast<ArmAssembler*>(Assembler::Create(kArm)));
// Save callee saves and ready frame for exception delivery
RegList save = (1 << R4) | (1 << R5) | (1 << R6) | (1 << R7) | (1 << R8) | (1 << R9) |
(1 << R10) | (1 << R11) | (1 << LR);
// TODO: enable when GetCalleeSaveMethod is available at stub generation time
// DCHECK_EQ(save, Runtime::Current()->GetCalleeSaveMethod(Runtime::kSaveAll)->GetCoreSpillMask());
__ PushList(save); // push {r4-r11, lr} - 9 words of callee saves
// TODO: enable when GetCalleeSaveMethod is available at stub generation time
// DCHECK_EQ(Runtime::Current()->GetCalleeSaveMethod(Runtime::kSaveAll)->GetFpSpillMask(), 0xFFFFU);
__ Emit(0xed2d0a20); // vpush {s0-s31}
__ IncreaseFrameSize(12); // 3 words of space, bottom word will hold callee save Method*
// R0 is the Method* already
__ mov(R1, ShifterOperand(R9)); // Pass Thread::Current() in R1
__ mov(R2, ShifterOperand(SP)); // Pass SP in R2
// Call to throw AbstractMethodError
__ LoadFromOffset(kLoadWord, R12, TR, ENTRYPOINT_OFFSET(pThrowAbstractMethodErrorFromCode));
__ mov(PC, ShifterOperand(R12)); // Leaf call to routine that never returns
__ bkpt(0);
assembler->EmitSlowPaths();
size_t cs = assembler->CodeSize();
SirtRef<ByteArray> abstract_stub(ByteArray::Alloc(cs));
CHECK(abstract_stub.get() != NULL);
MemoryRegion code(abstract_stub->GetData(), abstract_stub->GetLength());
assembler->FinalizeInstructions(code);
return abstract_stub.get();
}
ByteArray* CreateJniDlsymLookupStub() {
UniquePtr<ArmAssembler> assembler(static_cast<ArmAssembler*>(Assembler::Create(kArm)));
// Build frame and save argument registers and LR.
RegList save = (1 << R0) | (1 << R1) | (1 << R2) | (1 << R3) | (1 << LR);
__ PushList(save);
__ AddConstant(SP, -12); // Ensure 16-byte alignment
__ mov(R0, ShifterOperand(R9)); // Pass Thread::Current() in R0
// Call FindNativeMethod
__ LoadFromOffset(kLoadWord, R12, TR, ENTRYPOINT_OFFSET(pFindNativeMethod));
__ blx(R12);
__ mov(R12, ShifterOperand(R0)); // Save result of FindNativeMethod in R12
__ AddConstant(SP, 12); // Restore registers (including outgoing arguments)
__ PopList(save);
__ cmp(R12, ShifterOperand(0));
__ bx(R12, NE); // If R12 != 0 tail call into native code
__ bx(LR); // Return to caller to handle exception
assembler->EmitSlowPaths();
size_t cs = assembler->CodeSize();
SirtRef<ByteArray> jni_stub(ByteArray::Alloc(cs));
CHECK(jni_stub.get() != NULL);
MemoryRegion code(jni_stub->GetData(), jni_stub->GetLength());
assembler->FinalizeInstructions(code);
return jni_stub.get();
}
} // namespace arm
} // namespace art
<commit_msg>am e2f0911d: Implement ARM trampoline for llvm compiler.<commit_after>/*
* Copyright (C) 2011 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.
*/
#include "jni_internal.h"
#include "oat/utils/arm/assembler_arm.h"
#include "oat/runtime/oat_support_entrypoints.h"
#include "object.h"
#include "stack_indirect_reference_table.h"
#define __ assembler->
namespace art {
namespace arm {
ByteArray* ArmCreateResolutionTrampoline(Runtime::TrampolineType type) {
UniquePtr<ArmAssembler> assembler(static_cast<ArmAssembler*>(Assembler::Create(kArm)));
#if !defined(ART_USE_LLVM_COMPILER)
// | Out args |
// | Method* | <- SP on entry
// | LR | return address into caller
// | ... | callee saves
// | R3 | possible argument
// | R2 | possible argument
// | R1 | possible argument
// | R0 | junk on call to UnresolvedDirectMethodTrampolineFromCode, holds result Method*
// | Method* | Callee save Method* set up by UnresolvedDirectMethodTrampolineFromCode
// Save callee saves and ready frame for exception delivery
RegList save = (1 << R1) | (1 << R2) | (1 << R3) | (1 << R5) | (1 << R6) | (1 << R7) | (1 << R8) |
(1 << R10) | (1 << R11) | (1 << LR);
// TODO: enable when GetCalleeSaveMethod is available at stub generation time
// DCHECK_EQ(save, Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs)->GetCoreSpillMask());
__ PushList(save);
__ LoadFromOffset(kLoadWord, R12, TR,
ENTRYPOINT_OFFSET(pUnresolvedDirectMethodTrampolineFromCode));
__ mov(R2, ShifterOperand(TR)); // Pass Thread::Current() in R2
__ LoadImmediate(R3, type);
__ IncreaseFrameSize(8); // 2 words of space for alignment
__ mov(R1, ShifterOperand(SP)); // Pass SP
// Call to unresolved direct method trampoline (method_idx, sp, Thread*, is_static)
__ blx(R12);
__ mov(R12, ShifterOperand(R0)); // Save code address returned into R12
// Restore registers which may have been modified by GC, "R0" will hold the Method*
__ DecreaseFrameSize(4);
__ PopList((1 << R0) | save);
__ bx(R12); // Leaf call to method's code
__ bkpt(0);
#else // ART_USE_LLVM_COMPILER
RegList save = (1 << R0) | (1 << R1) | (1 << R2) | (1 << R3) | (1 << LR);
__ PushList(save);
__ LoadFromOffset(kLoadWord, R12, TR,
ENTRYPOINT_OFFSET(pUnresolvedDirectMethodTrampolineFromCode));
__ mov(R2, ShifterOperand(TR)); // Pass Thread::Current() in R2
__ LoadImmediate(R3, type); // Pass is_static
__ mov(R1, ShifterOperand(SP)); // Pass sp for Method** callee_addr
__ IncreaseFrameSize(12); // 3 words of space for alignment
// Call to unresolved direct method trampoline (callee, callee_addr, Thread*, is_static)
__ blx(R12);
__ mov(R12, ShifterOperand(R0)); // Save code address returned into R12
__ DecreaseFrameSize(12);
__ PopList(save);
__ cmp(R12, ShifterOperand(0));
__ bx(R12, NE); // If R12 != 0 tail call method's code
__ bx(LR); // Return to caller to handle exception
#endif // ART_USE_LLVM_COMPILER
assembler->EmitSlowPaths();
size_t cs = assembler->CodeSize();
SirtRef<ByteArray> resolution_trampoline(ByteArray::Alloc(cs));
CHECK(resolution_trampoline.get() != NULL);
MemoryRegion code(resolution_trampoline->GetData(), resolution_trampoline->GetLength());
assembler->FinalizeInstructions(code);
return resolution_trampoline.get();
}
typedef void (*ThrowAme)(Method*, Thread*);
ByteArray* CreateAbstractMethodErrorStub() {
UniquePtr<ArmAssembler> assembler(static_cast<ArmAssembler*>(Assembler::Create(kArm)));
#if !defined(ART_USE_LLVM_COMPILER)
// Save callee saves and ready frame for exception delivery
RegList save = (1 << R4) | (1 << R5) | (1 << R6) | (1 << R7) | (1 << R8) | (1 << R9) |
(1 << R10) | (1 << R11) | (1 << LR);
// TODO: enable when GetCalleeSaveMethod is available at stub generation time
// DCHECK_EQ(save, Runtime::Current()->GetCalleeSaveMethod(Runtime::kSaveAll)->GetCoreSpillMask());
__ PushList(save); // push {r4-r11, lr} - 9 words of callee saves
// TODO: enable when GetCalleeSaveMethod is available at stub generation time
// DCHECK_EQ(Runtime::Current()->GetCalleeSaveMethod(Runtime::kSaveAll)->GetFpSpillMask(), 0xFFFFU);
__ Emit(0xed2d0a20); // vpush {s0-s31}
__ IncreaseFrameSize(12); // 3 words of space, bottom word will hold callee save Method*
// R0 is the Method* already
__ mov(R1, ShifterOperand(R9)); // Pass Thread::Current() in R1
__ mov(R2, ShifterOperand(SP)); // Pass SP in R2
// Call to throw AbstractMethodError
__ LoadFromOffset(kLoadWord, R12, TR, ENTRYPOINT_OFFSET(pThrowAbstractMethodErrorFromCode));
__ mov(PC, ShifterOperand(R12)); // Leaf call to routine that never returns
__ bkpt(0);
#else // ART_USE_LLVM_COMPILER
// R0 is the Method* already
__ mov(R1, ShifterOperand(R9)); // Pass Thread::Current() in R1
// Call to throw AbstractMethodError
__ LoadFromOffset(kLoadWord, R12, TR, ENTRYPOINT_OFFSET(pThrowAbstractMethodErrorFromCode));
__ mov(PC, ShifterOperand(R12)); // Leaf call to routine that never returns
__ bkpt(0);
#endif // ART_USE_LLVM_COMPILER
assembler->EmitSlowPaths();
size_t cs = assembler->CodeSize();
SirtRef<ByteArray> abstract_stub(ByteArray::Alloc(cs));
CHECK(abstract_stub.get() != NULL);
MemoryRegion code(abstract_stub->GetData(), abstract_stub->GetLength());
assembler->FinalizeInstructions(code);
return abstract_stub.get();
}
ByteArray* CreateJniDlsymLookupStub() {
UniquePtr<ArmAssembler> assembler(static_cast<ArmAssembler*>(Assembler::Create(kArm)));
// Build frame and save argument registers and LR.
RegList save = (1 << R0) | (1 << R1) | (1 << R2) | (1 << R3) | (1 << LR);
__ PushList(save);
__ AddConstant(SP, -12); // Ensure 16-byte alignment
__ mov(R0, ShifterOperand(R9)); // Pass Thread::Current() in R0
// Call FindNativeMethod
__ LoadFromOffset(kLoadWord, R12, TR, ENTRYPOINT_OFFSET(pFindNativeMethod));
__ blx(R12);
__ mov(R12, ShifterOperand(R0)); // Save result of FindNativeMethod in R12
__ AddConstant(SP, 12); // Restore registers (including outgoing arguments)
__ PopList(save);
__ cmp(R12, ShifterOperand(0));
__ bx(R12, NE); // If R12 != 0 tail call into native code
__ bx(LR); // Return to caller to handle exception
assembler->EmitSlowPaths();
size_t cs = assembler->CodeSize();
SirtRef<ByteArray> jni_stub(ByteArray::Alloc(cs));
CHECK(jni_stub.get() != NULL);
MemoryRegion code(jni_stub->GetData(), jni_stub->GetLength());
assembler->FinalizeInstructions(code);
return jni_stub.get();
}
} // namespace arm
} // namespace art
<|endoftext|>
|
<commit_before>/*
* helper.cpp
*
* Created on: Dec 2, 2017
* Author: lowji
*/
#include "helper.h"
#include "Hand.h"
#include "Deck.h"
#include "Card.h"
#include <sstream>
using namespace std;
helper::helper() {
// TODO Auto-generated constructor stub
for (int i=0;i<13;i++){
for (int j=0;j<13;j++){
strengthChart[i][i]=0;
}
}
}
//method to determine if a string is an integer
bool helper::isInt(string input){
//Reference: https://stackoverflow.com/questions/20287186/how-to-check-if-the-input-is-a-valid-integer-without-any-other-chars
int x; //temporary int variable for checking input validity
char c; //temporary char variable for checking input validity
istringstream s(input);
if (!(s >> x)) {
return false;
}
if (s >> c) {
return false;
}
return true;
}
int helper::getStrength(Card* card1, Card* card2){
int num1=card1->getNumber();
int num2=card2->getNumber();
if (card1->getSuit()==card2->getSuit()){
return strengthChart[14-max(num1,num2)][14-min(num1,num2)];
}
else{
return strengthChart[14-min(num1,num2)][14-max(num1,num2)];
}
}
void helper::setStrengthChart(){
//https://howtoplaypokerinfo.com/wp-content/uploads/2016/06/Poker-cheat-sheet-card-printout-400x210.png
//setting strength 4
for (int i=0;i<13;i++){
strengthChart[i][i]=4;
}
for (int i=0;i<4;i++){
for (int j=0;j<5;j++){
strengthChart[i][j]=4;
}
}
//setting strength 3
strengthChart[4][0]=3;
strengthChart[3][1]=3;
strengthChart[3][2]=3;
strengthChart[1][4]=3;
strengthChart[2][4]=3;
strengthChart[3][4]=3;
strengthChart[4][5]=3;
//setting strength 2
for (int i=5;i<13;i++){
strengthChart[0][i]=2;
}
for (int i=1;i<4;i++){
strengthChart[i][5]=2;
}
for (int i=1;i<4;i++){
strengthChart[4][i]=2;
}
strengthChart[5][0]=2;
strengthChart[6][0]=2;
strengthChart[5][6]=2;
strengthChart[6][7]=2;
//setting strength 1
for (int i=1;i<5;i++){
strengthChart[i][6]=1;
}
strengthChart[1][7]=1;
strengthChart[5][7]=1;
strengthChart[6][8]=1;
strengthChart[7][9]=1;
strengthChart[7][8]=1;
strengthChart[8][9]=1;
strengthChart[9][10]=1;
for (int i=7;i<13;i++){
strengthChart[i][0]=1;
}
for (int i=5;i<8;i++){
strengthChart[i][1]=1;
}
for (int i=2;i<5;i++){
strengthChart[5][i]=1;
}
//print to test
/*for (int i=0;i<13;i++){
for (int j=0;j<13;j++){
cout<<strengthChart[i][j]<<"\t";
}
cout<<endl;
}*/
}
//returns 2 when they tie, 1 when hand1 wins, and 0 when hand 2 wins
int helper::compareHands(Hand* hand1, Hand* hand2)
{
int i = 2;
if(hand1->getType() > hand2->getType())
{
i = 1;
}
else if(hand1->getType() < hand2->getType())
{
i = 0;
}
else
{
if(hand1->getType() == 1 || hand1->getType() == 2)
{
if(hand1 -> getDoub() > hand2 -> getDoub())
{
i = 1;
}
else if(hand1 -> getDoub() < hand2 -> getDoub())
{
i = 0;
}
}
else if(hand1 -> getType() == 6 || hand1 -> getType() == 3)
{
if((hand1 -> getTrip())%100 > (hand2 -> getTrip())%100)
{
i = 1;
}
else if((hand1 -> getTrip())%100 < (hand2 -> getTrip())%100)
{
i = 0;
}
}
else if (hand1 -> getType() == 7)
{
if(hand1 -> getQuad() > hand2 -> getQuad())
{
i = 1;
}
else if(hand1->getQuad() < hand2->getQuad())
{
i = 0;
}
}
if(i == 2)
{
if(hand1 -> getHigh() > hand2 -> getHigh())
{
i = 1;
}
else if(hand1->getHigh() < hand2->getHigh())
{
i = 0;
}
}
}
return i;
}
//returns the highest value hand from a pool of 7 cards
Hand* helper::bestHand(Card card0, Card card1, Card card2, Card card3, Card card4, Card card5, Card card6)
{
Hand* best = new Hand(card0,card1,card2,card3,card4);
Hand* comp;
int ori1;
int ori2;
for(int i = 0; i < 6; i++)
{
for(int j = i + 1; j < 7; j++)
{
vector<Card> temp;
ori1 = i;
ori2 = j;
if(ori1 != 0 && ori2 != 0)
{
temp.push_back(card0);
}
if(ori1 != 1 && ori2 != 1)
{
temp.push_back(card1);
}
if(ori1 != 2 && ori2 != 2)
{
temp.push_back(card2);
}
if(ori1 != 3 && ori2 != 3)
{
temp.push_back(card3);
}
if(ori1 != 4 && ori2 != 4)
{
temp.push_back(card4);
}
if(ori1 != 5 && ori2 != 5)
{
temp.push_back(card5);
}
if(ori1 != 6 && ori2 != 6)
{
temp.push_back(card6);
}
comp = new Hand(temp[0],temp[1],temp[2],temp[3],temp[4]);
if(this->compareHands(comp,best) == 1)
{
best = comp;
}
}
}
return best;
}
/* namespace std */
/*int main(){
helper* help=new helper();
help->setStrengthChart();
Card* one=new Card(12,1);
Card* two=new Card(11,2);
cout<<help->getStrength(one,two);
}*/
<commit_msg>Added comments<commit_after>//******************************************************************************
//
// File Name: helper.cpp
//
// File Overview: ????
#include "helper.h"
#include "Hand.h"
#include "Deck.h"
#include "Card.h"
#include <sstream>
using namespace std;
//******************************************************************************
// Function : constructor
// Process : Initialize data members
// Notes : None
//
//******************************************************************************
helper::helper() {
// TODO Auto-generated constructor stub
for (int i=0;i<13;i++){
for (int j=0;j<13;j++){
strengthChart[i][i]=0;
}
}
}
//******************************************************************************
// Function : isInt
// Process : Determines if a string input is an integer
// Notes : None
//******************************************************************************
bool helper::isInt(string input){
//Reference: https://stackoverflow.com/questions/20287186/how-to-check-if-the-input-is-a-valid-integer-without-any-other-chars
int x; //temporary int variable for checking input validity
char c; //temporary char variable for checking input validity
istringstream s(input);
if (!(s >> x)) {
return false;
}
if (s >> c) {
return false;
}
return true;
}
//******************************************************************************
// Function : getStrength
// Process : Returns an integer representing the "strength" of the stronger
// card
// Notes : This is done using a predetermined "strength chart"
//******************************************************************************
int helper::getStrength(Card* card1, Card* card2){
int num1=card1->getNumber();
int num2=card2->getNumber();
if (card1->getSuit()==card2->getSuit()){
return strengthChart[14-max(num1,num2)][14-min(num1,num2)];
}
else{
return strengthChart[14-min(num1,num2)][14-max(num1,num2)];
}
}
//******************************************************************************
// Function : setStrengthChart()
// Process : Creates a "strength chart" according to standard poker rules.
// Notes : None
//******************************************************************************
void helper::setStrengthChart(){
//https://howtoplaypokerinfo.com/wp-content/uploads/2016/06/Poker-cheat-sheet-card-printout-400x210.png
//setting strength 4
for (int i=0;i<13;i++){
strengthChart[i][i]=4;
}
for (int i=0;i<4;i++){
for (int j=0;j<5;j++){
strengthChart[i][j]=4;
}
}
//setting strength 3
strengthChart[4][0]=3;
strengthChart[3][1]=3;
strengthChart[3][2]=3;
strengthChart[1][4]=3;
strengthChart[2][4]=3;
strengthChart[3][4]=3;
strengthChart[4][5]=3;
//setting strength 2
for (int i=5;i<13;i++){
strengthChart[0][i]=2;
}
for (int i=1;i<4;i++){
strengthChart[i][5]=2;
}
for (int i=1;i<4;i++){
strengthChart[4][i]=2;
}
strengthChart[5][0]=2;
strengthChart[6][0]=2;
strengthChart[5][6]=2;
strengthChart[6][7]=2;
//setting strength 1
for (int i=1;i<5;i++){
strengthChart[i][6]=1;
}
strengthChart[1][7]=1;
strengthChart[5][7]=1;
strengthChart[6][8]=1;
strengthChart[7][9]=1;
strengthChart[7][8]=1;
strengthChart[8][9]=1;
strengthChart[9][10]=1;
for (int i=7;i<13;i++){
strengthChart[i][0]=1;
}
for (int i=5;i<8;i++){
strengthChart[i][1]=1;
}
for (int i=2;i<5;i++){
strengthChart[5][i]=1;
}
//print to test
/*for (int i=0;i<13;i++){
for (int j=0;j<13;j++){
cout<<strengthChart[i][j]<<"\t";
}
cout<<endl;
}*/
}
//******************************************************************************
// Function : compareHands
// Process : Compares 2 hands of cards and returns an integer according to who
// wins or draws.
// Notes : This is done according to standard poker rules.
//******************************************************************************
//returns 2 when they tie, 1 when hand1 wins, and 0 when hand 2 wins
int helper::compareHands(Hand* hand1, Hand* hand2)
{
int i = 2;
if(hand1->getType() > hand2->getType())
{
i = 1;
}
else if(hand1->getType() < hand2->getType())
{
i = 0;
}
else
{
if(hand1->getType() == 1 || hand1->getType() == 2)
{
if(hand1 -> getDoub() > hand2 -> getDoub())
{
i = 1;
}
else if(hand1 -> getDoub() < hand2 -> getDoub())
{
i = 0;
}
}
else if(hand1 -> getType() == 6 || hand1 -> getType() == 3)
{
if((hand1 -> getTrip())%100 > (hand2 -> getTrip())%100)
{
i = 1;
}
else if((hand1 -> getTrip())%100 < (hand2 -> getTrip())%100)
{
i = 0;
}
}
else if (hand1 -> getType() == 7)
{
if(hand1 -> getQuad() > hand2 -> getQuad())
{
i = 1;
}
else if(hand1->getQuad() < hand2->getQuad())
{
i = 0;
}
}
if(i == 2)
{
if(hand1 -> getHigh() > hand2 -> getHigh())
{
i = 1;
}
else if(hand1->getHigh() < hand2->getHigh())
{
i = 0;
}
}
}
return i;
}
//******************************************************************************
// Function : bestHand
// Process : Returns a pointer to the best possible hand given a set of 7 cards
// Notes : The function iterates through all 7C2 = 21 possibilities.
//******************************************************************************
//returns the highest value hand from a pool of 7 cards
Hand* helper::bestHand(Card card0, Card card1, Card card2, Card card3, Card card4, Card card5, Card card6)
{
Hand* best = new Hand(card0,card1,card2,card3,card4);
Hand* comp;
int ori1;
int ori2;
for(int i = 0; i < 6; i++)
{
for(int j = i + 1; j < 7; j++)
{
vector<Card> temp;
ori1 = i;
ori2 = j;
if(ori1 != 0 && ori2 != 0)
{
temp.push_back(card0);
}
if(ori1 != 1 && ori2 != 1)
{
temp.push_back(card1);
}
if(ori1 != 2 && ori2 != 2)
{
temp.push_back(card2);
}
if(ori1 != 3 && ori2 != 3)
{
temp.push_back(card3);
}
if(ori1 != 4 && ori2 != 4)
{
temp.push_back(card4);
}
if(ori1 != 5 && ori2 != 5)
{
temp.push_back(card5);
}
if(ori1 != 6 && ori2 != 6)
{
temp.push_back(card6);
}
comp = new Hand(temp[0],temp[1],temp[2],temp[3],temp[4]);
if(this->compareHands(comp,best) == 1)
{
best = comp;
}
}
}
return best;
}
/* namespace std */
/*int main(){
helper* help=new helper();
help->setStrengthChart();
Card* one=new Card(12,1);
Card* two=new Card(11,2);
cout<<help->getStrength(one,two);
}*/
<|endoftext|>
|
<commit_before>#include "GraphML.h"
#include "DirectedGraph.h"
#include "UndirectedGraph.h"
#include <tinyxml2.h>
#include <Table.h>
#include <cassert>
#include <map>
#include <iostream>
using namespace std;
using namespace tinyxml2;
GraphML::GraphML() : FileTypeHandler("GraphML", true) {
addExtension("graphml");
}
std::shared_ptr<Graph>
GraphML::openGraph(const char * filename) {
RenderMode mode = RENDERMODE_3D;
XMLDocument doc;
doc.LoadFile(filename);
XMLElement * graphml_element = doc.FirstChildElement("graphml");
assert(graphml_element);
XMLElement * graph_element = graphml_element->FirstChildElement("graph");
assert(graph_element);
return createGraphFromElement(*graphml_element, *graph_element);
}
std::shared_ptr<Graph>
GraphML::createGraphFromElement(XMLElement & graphml_element, XMLElement & graph_element) const {
map<string, int> nodes_by_id;
const char * edgedefault = graph_element.Attribute("edgedefault");
bool directed = true;
if (edgedefault && strcmp(edgedefault, "undirected") == 0) {
directed = false;
}
std::shared_ptr<Graph> graph;
if (directed) {
graph = std::make_shared<DirectedGraph>();
graph->setNodeArray(std::make_shared<NodeArray>());
graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_INDEGREE));
} else {
graph = std::make_shared<UndirectedGraph>();
graph->setNodeArray(std::make_shared<NodeArray>());
graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_DEGREE));
}
auto & node_table = graph->getNodeArray().getTable();
auto & edge_table = directed ? graph->getEdgeData() : graph->getFaceData();
auto & node_id_column = node_table.addTextColumn("id");
auto & edge_id_column = edge_table.addTextColumn("id");
XMLElement * key_element = graphml_element.FirstChildElement("key");
for ( ; key_element ; key_element = key_element->NextSiblingElement("key") ) {
const char * key_type = key_element->Attribute("attr.type");
const char * key_id = key_element->Attribute("id");
const char * for_type = key_element->Attribute("for");
const char * name = key_element->Attribute("attr.name");
assert(key_type && key_id && for_type);
std::shared_ptr<table::Column> column;
if (strcmp(key_type, "string") == 0) {
column = std::make_shared<table::ColumnText>(key_id ? key_id : "");
} else if (strcmp(key_type, "double") == 0 || strcmp(key_type, "float") == 0) {
column = std::make_shared<table::ColumnDouble>(key_id ? key_id : "");
} else if (strcmp(key_type, "int") == 0) {
column = std::make_shared<table::ColumnInt>(key_id ? key_id : "");
} else {
assert(0);
}
if (strcmp(for_type, "node") == 0) {
node_table.addColumn(column);
} else if (strcmp(for_type, "edge") == 0) {
edge_table.addColumn(column);
} else {
assert(0);
}
}
bool is_complex = false;
XMLElement * node_element = graph_element.FirstChildElement("node");
for ( ; node_element ; node_element = node_element->NextSiblingElement("node") ) {
const char * node_id_text = node_element->Attribute("id");
assert(node_id_text);
int node_id = graph->addNode();
graph->addEdge(node_id, node_id);
node_id_column.setValue(node_id, node_id_text);
nodes_by_id[node_id_text] = node_id + 1;
XMLElement * data_element = node_element->FirstChildElement("data");
for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) {
const char * key = data_element->Attribute("key");
assert(key);
const char * text = data_element->GetText();
if (text) {
node_table[key].setValue(node_id, text);
}
}
graph->getNodeArray().updateNodeAppearanceSlow(node_id);
XMLElement * nested_graph_element = node_element->FirstChildElement("graph");
if (nested_graph_element) {
auto nested_graph = createGraphFromElement(graphml_element, *nested_graph_element);
assert(nested_graph.get());
is_complex = true;
graph->getNodeArray().setNestedGraph(node_id, nested_graph);
}
}
graph->randomizeGeometry();
graph->setComplexGraph(is_complex);
graph->setHasSubGraphs(is_complex);
XMLElement * edge_element = graph_element.FirstChildElement("edge");
for ( ; edge_element ; edge_element = edge_element->NextSiblingElement("edge") ) {
const char * edge_id_text = edge_element->Attribute("id");
const char * source = edge_element->Attribute("source");
const char * target = edge_element->Attribute("target");
assert(source && target);
if (strcmp(source, target) == 0) {
cerr << "GraphML: skipping self link for " << source << endl;
continue;
}
int source_node = nodes_by_id[source];
int target_node = nodes_by_id[target];
if (source_node && target_node) {
int edge_id;
if (directed) {
edge_id = graph->addEdge(source_node - 1, target_node - 1);
if (edge_id_text && strlen(edge_id_text) != 0) {
edge_id_column.setValue(edge_id, edge_id_text);
}
} else {
edge_id = graph->addFace(-1);
graph->addEdge(source_node - 1, target_node - 1, edge_id);
graph->addEdge(target_node - 1, source_node - 1, edge_id);
}
XMLElement * data_element = edge_element->FirstChildElement("data");
for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) {
const char * key = data_element->Attribute("key");
assert(key);
const char * text = data_element->GetText();
if (text) {
edge_table[key].setValue(edge_id, text);
}
}
} else {
if (!source_node) {
// cerr << "cannot find node " << source << endl;
}
if (!target_node) {
// cerr << "cannot find node " << target << endl;
}
}
}
return graph;
}
bool
GraphML::saveGraph(const Graph & graph, const std::string & filename) {
XMLDocument doc;
doc.LinkEndChild(doc.NewDeclaration());
XMLElement * graphml_element = doc.NewElement("graphml");
graphml_element->SetAttribute("xmlns", "http://graphml.graphdrawing.org/xmlns");
bool directed = graph.isDirected();
auto & node_table = graph.getNodeArray().getTable();
auto & edge_table = directed ? graph.getEdgeData() : graph.getFaceData();
for (auto & col : node_table.getColumns()) {
XMLElement * key_element = doc.NewElement("key");
key_element->SetAttribute("attr.name", col.first.c_str());
key_element->SetAttribute("id", col.first.c_str());
key_element->SetAttribute("attr.type", col.second->getTypeText());
key_element->SetAttribute("for", "node");
graphml_element->LinkEndChild(key_element);
}
for (auto & col : edge_table.getColumns()) {
XMLElement * key_element = doc.NewElement("key");
key_element->SetAttribute("attr.name", col.first.c_str());
key_element->SetAttribute("id", col.first.c_str());
key_element->SetAttribute("attr.type", col.second->getTypeText());
key_element->SetAttribute("for", "edge");
graphml_element->LinkEndChild(key_element);
}
XMLElement * graph_element = doc.NewElement("graph");
graphml_element->LinkEndChild(graph_element);
if (!directed) {
graph_element->SetAttribute("edgedefault", "undirected");
}
for (unsigned int i = 0; i < graph.getNodeCount(); i++) {
XMLElement * node_element = doc.NewElement("node");
string node_id = "n" + to_string(i);
node_element->SetAttribute("id", node_id.c_str());
for (auto & col : node_table.getColumns()) {
XMLElement * data_element = doc.NewElement("data");
data_element->SetAttribute("key", col.first.c_str());
data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str()));
node_element->LinkEndChild(data_element);
}
graph_element->LinkEndChild(node_element);
}
#if 0
for (unsigned int i = 0; i < graph.getEdgeCount(); i++) {
XMLElement * edge_element = doc.NewElement("edge");
auto edge = graph.getEdgeAttributes(i);
string node_id1 = "n" + to_string(edge.tail);
string node_id2 = "n" + to_string(edge.head);
// timestamp, sentiment
edge_element->SetAttribute("source", node_id1.c_str());
edge_element->SetAttribute("target", node_id2.c_str());
for (auto & col : edge_table.getColumns()) {
XMLElement * data_element = doc.NewElement("data");
data_element->SetAttribute("key", col.first.c_str());
data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str()));
edge_element->LinkEndChild(data_element);
}
graph_element->LinkEndChild(edge_element);
}
#endif
doc.LinkEndChild(graphml_element);
doc.SaveFile(filename.c_str());
return true;
}
<commit_msg>replace Graph::getNodeCount() with NodeArray::size()<commit_after>#include "GraphML.h"
#include "DirectedGraph.h"
#include "UndirectedGraph.h"
#include <tinyxml2.h>
#include <Table.h>
#include <cassert>
#include <map>
#include <iostream>
using namespace std;
using namespace tinyxml2;
GraphML::GraphML() : FileTypeHandler("GraphML", true) {
addExtension("graphml");
}
std::shared_ptr<Graph>
GraphML::openGraph(const char * filename) {
RenderMode mode = RENDERMODE_3D;
XMLDocument doc;
doc.LoadFile(filename);
XMLElement * graphml_element = doc.FirstChildElement("graphml");
assert(graphml_element);
XMLElement * graph_element = graphml_element->FirstChildElement("graph");
assert(graph_element);
return createGraphFromElement(*graphml_element, *graph_element);
}
std::shared_ptr<Graph>
GraphML::createGraphFromElement(XMLElement & graphml_element, XMLElement & graph_element) const {
map<string, int> nodes_by_id;
const char * edgedefault = graph_element.Attribute("edgedefault");
bool directed = true;
if (edgedefault && strcmp(edgedefault, "undirected") == 0) {
directed = false;
}
std::shared_ptr<Graph> graph;
if (directed) {
graph = std::make_shared<DirectedGraph>();
graph->setNodeArray(std::make_shared<NodeArray>());
graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_INDEGREE));
} else {
graph = std::make_shared<UndirectedGraph>();
graph->setNodeArray(std::make_shared<NodeArray>());
graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_DEGREE));
}
auto & node_table = graph->getNodeArray().getTable();
auto & edge_table = directed ? graph->getEdgeData() : graph->getFaceData();
auto & node_id_column = node_table.addTextColumn("id");
auto & edge_id_column = edge_table.addTextColumn("id");
XMLElement * key_element = graphml_element.FirstChildElement("key");
for ( ; key_element ; key_element = key_element->NextSiblingElement("key") ) {
const char * key_type = key_element->Attribute("attr.type");
const char * key_id = key_element->Attribute("id");
const char * for_type = key_element->Attribute("for");
const char * name = key_element->Attribute("attr.name");
assert(key_type && key_id && for_type);
std::shared_ptr<table::Column> column;
if (strcmp(key_type, "string") == 0) {
column = std::make_shared<table::ColumnText>(key_id ? key_id : "");
} else if (strcmp(key_type, "double") == 0 || strcmp(key_type, "float") == 0) {
column = std::make_shared<table::ColumnDouble>(key_id ? key_id : "");
} else if (strcmp(key_type, "int") == 0) {
column = std::make_shared<table::ColumnInt>(key_id ? key_id : "");
} else {
assert(0);
}
if (strcmp(for_type, "node") == 0) {
node_table.addColumn(column);
} else if (strcmp(for_type, "edge") == 0) {
edge_table.addColumn(column);
} else {
assert(0);
}
}
bool is_complex = false;
XMLElement * node_element = graph_element.FirstChildElement("node");
for ( ; node_element ; node_element = node_element->NextSiblingElement("node") ) {
const char * node_id_text = node_element->Attribute("id");
assert(node_id_text);
int node_id = graph->addNode();
graph->addEdge(node_id, node_id);
node_id_column.setValue(node_id, node_id_text);
nodes_by_id[node_id_text] = node_id + 1;
XMLElement * data_element = node_element->FirstChildElement("data");
for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) {
const char * key = data_element->Attribute("key");
assert(key);
const char * text = data_element->GetText();
if (text) {
node_table[key].setValue(node_id, text);
}
}
graph->getNodeArray().updateNodeAppearanceSlow(node_id);
XMLElement * nested_graph_element = node_element->FirstChildElement("graph");
if (nested_graph_element) {
auto nested_graph = createGraphFromElement(graphml_element, *nested_graph_element);
assert(nested_graph.get());
is_complex = true;
graph->getNodeArray().setNestedGraph(node_id, nested_graph);
}
}
graph->randomizeGeometry();
graph->setComplexGraph(is_complex);
graph->setHasSubGraphs(is_complex);
XMLElement * edge_element = graph_element.FirstChildElement("edge");
for ( ; edge_element ; edge_element = edge_element->NextSiblingElement("edge") ) {
const char * edge_id_text = edge_element->Attribute("id");
const char * source = edge_element->Attribute("source");
const char * target = edge_element->Attribute("target");
assert(source && target);
if (strcmp(source, target) == 0) {
cerr << "GraphML: skipping self link for " << source << endl;
continue;
}
int source_node = nodes_by_id[source];
int target_node = nodes_by_id[target];
if (source_node && target_node) {
int edge_id;
if (directed) {
edge_id = graph->addEdge(source_node - 1, target_node - 1);
if (edge_id_text && strlen(edge_id_text) != 0) {
edge_id_column.setValue(edge_id, edge_id_text);
}
} else {
edge_id = graph->addFace(-1);
graph->addEdge(source_node - 1, target_node - 1, edge_id);
graph->addEdge(target_node - 1, source_node - 1, edge_id);
}
XMLElement * data_element = edge_element->FirstChildElement("data");
for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) {
const char * key = data_element->Attribute("key");
assert(key);
const char * text = data_element->GetText();
if (text) {
edge_table[key].setValue(edge_id, text);
}
}
} else {
if (!source_node) {
// cerr << "cannot find node " << source << endl;
}
if (!target_node) {
// cerr << "cannot find node " << target << endl;
}
}
}
return graph;
}
bool
GraphML::saveGraph(const Graph & graph, const std::string & filename) {
XMLDocument doc;
doc.LinkEndChild(doc.NewDeclaration());
XMLElement * graphml_element = doc.NewElement("graphml");
graphml_element->SetAttribute("xmlns", "http://graphml.graphdrawing.org/xmlns");
bool directed = graph.isDirected();
auto & node_table = graph.getNodeArray().getTable();
auto & edge_table = directed ? graph.getEdgeData() : graph.getFaceData();
for (auto & col : node_table.getColumns()) {
XMLElement * key_element = doc.NewElement("key");
key_element->SetAttribute("attr.name", col.first.c_str());
key_element->SetAttribute("id", col.first.c_str());
key_element->SetAttribute("attr.type", col.second->getTypeText());
key_element->SetAttribute("for", "node");
graphml_element->LinkEndChild(key_element);
}
for (auto & col : edge_table.getColumns()) {
XMLElement * key_element = doc.NewElement("key");
key_element->SetAttribute("attr.name", col.first.c_str());
key_element->SetAttribute("id", col.first.c_str());
key_element->SetAttribute("attr.type", col.second->getTypeText());
key_element->SetAttribute("for", "edge");
graphml_element->LinkEndChild(key_element);
}
XMLElement * graph_element = doc.NewElement("graph");
graphml_element->LinkEndChild(graph_element);
if (!directed) {
graph_element->SetAttribute("edgedefault", "undirected");
}
for (unsigned int i = 0; i < graph.getNodeArray().size(); i++) {
XMLElement * node_element = doc.NewElement("node");
string node_id = "n" + to_string(i);
node_element->SetAttribute("id", node_id.c_str());
for (auto & col : node_table.getColumns()) {
XMLElement * data_element = doc.NewElement("data");
data_element->SetAttribute("key", col.first.c_str());
data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str()));
node_element->LinkEndChild(data_element);
}
graph_element->LinkEndChild(node_element);
}
#if 0
for (unsigned int i = 0; i < graph.getEdgeCount(); i++) {
XMLElement * edge_element = doc.NewElement("edge");
auto edge = graph.getEdgeAttributes(i);
string node_id1 = "n" + to_string(edge.tail);
string node_id2 = "n" + to_string(edge.head);
// timestamp, sentiment
edge_element->SetAttribute("source", node_id1.c_str());
edge_element->SetAttribute("target", node_id2.c_str());
for (auto & col : edge_table.getColumns()) {
XMLElement * data_element = doc.NewElement("data");
data_element->SetAttribute("key", col.first.c_str());
data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str()));
edge_element->LinkEndChild(data_element);
}
graph_element->LinkEndChild(edge_element);
}
#endif
doc.LinkEndChild(graphml_element);
doc.SaveFile(filename.c_str());
return true;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: ChartPlotAreaOASISTContext.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-07-13 08:44:41 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "ChartPlotAreaOASISTContext.hxx"
#ifndef _XMLOFF_TRANSFORMER_BASE_HXX
#include "TransformerBase.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_DEEPTCONTEXT_HXX
#include "DeepTContext.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::rtl::OUString;
class XMLAxisOASISContext : public XMLTransformerContext
{
public:
TYPEINFO();
XMLAxisOASISContext( XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName,
::rtl::Reference< XMLPersAttrListTContext > & rOutCategoriesContext );
~XMLAxisOASISContext();
virtual XMLTransformerContext *CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rQName,
const Reference< xml::sax::XAttributeList >& xAttrList );
private:
::rtl::Reference< XMLPersAttrListTContext > & m_rCategoriesContext;
};
TYPEINIT1( XMLAxisOASISContext, XMLTransformerContext );
XMLAxisOASISContext::XMLAxisOASISContext(
XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName,
::rtl::Reference< XMLPersAttrListTContext > & rOutCategoriesContext ) :
XMLTransformerContext( rTransformer, rQName ),
m_rCategoriesContext( rOutCategoriesContext )
{}
XMLAxisOASISContext::~XMLAxisOASISContext()
{}
XMLTransformerContext * XMLAxisOASISContext::CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rQName,
const Reference< xml::sax::XAttributeList >& xAttrList )
{
XMLTransformerContext * pContext = 0;
if( XML_NAMESPACE_CHART == nPrefix &&
::xmloff::token::IsXMLToken( rLocalName, ::xmloff::token::XML_CATEGORIES ) )
{
// store categories element at parent
m_rCategoriesContext.set( new XMLPersAttrListTContext( GetTransformer(), rQName ));
pContext = m_rCategoriesContext.get();
}
else
{
pContext = XMLTransformerContext::CreateChildContext(
nPrefix, rLocalName, rQName, xAttrList );
}
return pContext;
}
TYPEINIT1( XMLChartPlotAreaOASISTContext, XMLProcAttrTransformerContext );
XMLChartPlotAreaOASISTContext::XMLChartPlotAreaOASISTContext(
XMLTransformerBase & rTransformer, const ::rtl::OUString & rQName ) :
XMLProcAttrTransformerContext( rTransformer, rQName, OASIS_SHAPE_ACTIONS )
{
}
XMLChartPlotAreaOASISTContext::~XMLChartPlotAreaOASISTContext()
{}
XMLTransformerContext * XMLChartPlotAreaOASISTContext::CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rQName,
const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
XMLTransformerContext *pContext = 0;
if( XML_NAMESPACE_CHART == nPrefix &&
::xmloff::token::IsXMLToken( rLocalName, ::xmloff::token::XML_AXIS ) )
{
pContext = new XMLAxisOASISContext( GetTransformer(), rQName, m_rCategoriesContext );
}
else
{
// export (and forget) categories if found in an axis-element
// otherwise export regularly
ExportCategories();
pContext = XMLProcAttrTransformerContext::CreateChildContext(
nPrefix, rLocalName, rQName, xAttrList );
}
return pContext;
}
void XMLChartPlotAreaOASISTContext::EndElement()
{
ExportCategories();
XMLProcAttrTransformerContext::EndElement();
}
void XMLChartPlotAreaOASISTContext::ExportCategories()
{
if( m_rCategoriesContext.is())
{
m_rCategoriesContext->Export();
m_rCategoriesContext.clear();
}
}
<commit_msg>INTEGRATION: CWS schoasis02 (1.2.94); FILE MERGED 2004/11/05 13:23:38 bm 1.2.94.2: #i36581# rename axis class -> dimension 2004/11/04 17:19:29 bm 1.2.94.1: #i36581# axis: class->dimension<commit_after>/*************************************************************************
*
* $RCSfile: ChartPlotAreaOASISTContext.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-11-15 12:36:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "ChartPlotAreaOASISTContext.hxx"
#ifndef _XMLOFF_TRANSFORMER_BASE_HXX
#include "TransformerBase.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_DEEPTCONTEXT_HXX
#include "DeepTContext.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using ::com::sun::star::uno::Reference;
using ::rtl::OUString;
class XMLAxisOASISContext : public XMLPersElemContentTContext
{
public:
TYPEINFO();
XMLAxisOASISContext( XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName,
::rtl::Reference< XMLPersAttrListTContext > & rOutCategoriesContext );
~XMLAxisOASISContext();
virtual XMLTransformerContext *CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rQName,
const Reference< xml::sax::XAttributeList >& xAttrList );
virtual void StartElement( const Reference< xml::sax::XAttributeList >& rAttrList );
virtual void EndElement();
bool IsCategoryAxis() const;
private:
::rtl::Reference< XMLPersAttrListTContext > & m_rCategoriesContext;
bool m_bHasCategories;
};
TYPEINIT1( XMLAxisOASISContext, XMLPersElemContentTContext );
XMLAxisOASISContext::XMLAxisOASISContext(
XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName,
::rtl::Reference< XMLPersAttrListTContext > & rOutCategoriesContext ) :
XMLPersElemContentTContext( rTransformer, rQName ),
m_rCategoriesContext( rOutCategoriesContext ),
m_bHasCategories( false )
{}
XMLAxisOASISContext::~XMLAxisOASISContext()
{}
XMLTransformerContext * XMLAxisOASISContext::CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rQName,
const Reference< xml::sax::XAttributeList >& xAttrList )
{
XMLTransformerContext * pContext = 0;
if( XML_NAMESPACE_CHART == nPrefix &&
IsXMLToken( rLocalName, XML_CATEGORIES ) )
{
// store categories element at parent
m_rCategoriesContext.set( new XMLPersAttrListTContext( GetTransformer(), rQName ));
m_bHasCategories = true;
pContext = m_rCategoriesContext.get();
}
else
{
pContext = XMLPersElemContentTContext::CreateChildContext(
nPrefix, rLocalName, rQName, xAttrList );
}
return pContext;
}
void XMLAxisOASISContext::StartElement(
const Reference< xml::sax::XAttributeList >& rAttrList )
{
OUString aLocation, aMacroName;
Reference< xml::sax::XAttributeList > xAttrList( rAttrList );
XMLMutableAttributeList *pMutableAttrList = 0;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
if( nPrefix == XML_NAMESPACE_CHART &&
IsXMLToken( aLocalName, XML_DIMENSION ) )
{
if( !pMutableAttrList )
{
pMutableAttrList = new XMLMutableAttributeList( xAttrList );
xAttrList = pMutableAttrList;
}
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
XMLTokenEnum eToken = XML_TOKEN_INVALID;
if( IsXMLToken( rAttrValue, XML_X ))
{
eToken = XML_DOMAIN;
// has to be XML_CATEGORY for axes with a categories
// sub-element. The attribute is changed later (when it is
// known that there is a categories sub-element) in this case.
}
else if( IsXMLToken( rAttrValue, XML_Y ))
{
eToken = XML_VALUE;
}
else if( IsXMLToken( rAttrValue, XML_Z ))
{
eToken = XML_SERIES;
}
else
{
OSL_ENSURE( false, "ChartAxis: Invalid attribute value" );
}
if( eToken != XML_TOKEN_INVALID )
{
OUString aNewAttrQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_CHART, GetXMLToken( XML_CLASS )));
pMutableAttrList->RenameAttributeByIndex( i, aNewAttrQName );
pMutableAttrList->SetValueByIndex( i, GetXMLToken( eToken ));
}
}
}
XMLPersElemContentTContext::StartElement( xAttrList );
}
void XMLAxisOASISContext::EndElement()
{
// if we have categories, change the "class" attribute
if( IsCategoryAxis() &&
m_rCategoriesContext.is() )
{
OSL_ENSURE( GetAttrList().is(), "Invalid attribute list" );
XMLMutableAttributeList * pMutableAttrList =
new XMLMutableAttributeList( GetAttrList());
OUString aAttrQName( GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_CHART, GetXMLToken( XML_CLASS )));
sal_Int16 nIndex = pMutableAttrList->GetIndexByName( aAttrQName );
if( nIndex != -1 )
{
OSL_ENSURE( IsXMLToken( pMutableAttrList->getValueByIndex( nIndex ),
XML_DOMAIN ), "Axis Dimension: invalid former value" );
pMutableAttrList->SetValueByIndex( nIndex, GetXMLToken( XML_CATEGORY ));
OSL_ENSURE( IsXMLToken( pMutableAttrList->getValueByIndex( nIndex ),
XML_CATEGORY ), "Axis Dimension: invalid new value" );
}
GetTransformer().GetDocHandler()->startElement(
GetExportQName(),
Reference< xml::sax::XAttributeList >( pMutableAttrList ));
ExportContent();
GetTransformer().GetDocHandler()->endElement( GetExportQName());
}
else
Export();
}
bool XMLAxisOASISContext::IsCategoryAxis() const
{
return m_bHasCategories;
}
TYPEINIT1( XMLChartPlotAreaOASISTContext, XMLProcAttrTransformerContext );
XMLChartPlotAreaOASISTContext::XMLChartPlotAreaOASISTContext(
XMLTransformerBase & rTransformer, const ::rtl::OUString & rQName ) :
XMLProcAttrTransformerContext( rTransformer, rQName, OASIS_SHAPE_ACTIONS )
{
}
XMLChartPlotAreaOASISTContext::~XMLChartPlotAreaOASISTContext()
{}
XMLTransformerContext * XMLChartPlotAreaOASISTContext::CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rQName,
const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
XMLTransformerContext *pContext = 0;
if( XML_NAMESPACE_CHART == nPrefix &&
IsXMLToken( rLocalName, XML_AXIS ) )
{
pContext = new XMLAxisOASISContext( GetTransformer(), rQName, m_rCategoriesContext );
}
else
{
// export (and forget) categories if found in an axis-element
// otherwise export regularly
ExportCategories();
pContext = XMLProcAttrTransformerContext::CreateChildContext(
nPrefix, rLocalName, rQName, xAttrList );
}
return pContext;
}
void XMLChartPlotAreaOASISTContext::EndElement()
{
ExportCategories();
XMLProcAttrTransformerContext::EndElement();
}
void XMLChartPlotAreaOASISTContext::ExportCategories()
{
if( m_rCategoriesContext.is())
{
m_rCategoriesContext->Export();
m_rCategoriesContext.clear();
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012, 2015 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andreas Sandberg
*/
#ifndef __SIM_DRAIN_HH__
#define __SIM_DRAIN_HH__
#include <atomic>
#include <mutex>
#include <unordered_set>
#include "base/flags.hh"
class Drainable;
#ifndef SWIG // SWIG doesn't support strongly typed enums
/**
* Object drain/handover states
*
* An object starts out in the Running state. When the simulator
* prepares to take a snapshot or prepares a CPU for handover, it
* calls the drain() method to transfer the object into the Draining
* or Drained state. If any object enters the Draining state
* (Drainable::drain() returning >0), simulation continues until it
* all objects have entered the Drained state.
*
* Before resuming simulation, the simulator calls resume() to
* transfer the object to the Running state.
*
* \note Even though the state of an object (visible to the rest of
* the world through Drainable::getState()) could be used to determine
* if all objects have entered the Drained state, the protocol is
* actually a bit more elaborate. See Drainable::drain() for details.
*/
enum class DrainState {
Running, /** Running normally */
Draining, /** Draining buffers pending serialization/handover */
Drained /** Buffers drained, ready for serialization/handover */
};
#endif
/**
* This class coordinates draining of a System.
*
* When draining the simulator, we need to make sure that all
* Drainable objects within the system have ended up in the drained
* state before declaring the operation to be successful. This class
* keeps track of how many objects are still in the process of
* draining. Once it determines that all objects have drained their
* state, it exits the simulation loop.
*
* @note A System might not be completely drained even though the
* DrainManager has caused the simulation loop to exit. Draining needs
* to be restarted until all Drainable objects declare that they don't
* need further simulation to be completely drained. See Drainable for
* more information.
*/
class DrainManager
{
private:
DrainManager();
#ifndef SWIG
DrainManager(DrainManager &) = delete;
#endif
~DrainManager();
public:
/** Get the singleton DrainManager instance */
static DrainManager &instance() { return _instance; }
/**
* Try to drain the system.
*
* Try to drain the system and return true if all objects are in a
* the Drained state at which point the whole simulator is in a
* consistent state and ready for checkpointing or CPU
* handover. The simulation script must continue simulating until
* the simulation loop returns "Finished drain", at which point
* this method should be called again. This cycle should continue
* until this method returns true.
*
* @return true if all objects were drained successfully, false if
* more simulation is needed.
*/
bool tryDrain();
/**
* Resume normal simulation in a Drained system.
*/
void resume();
/**
* Run state fixups before a checkpoint restore operation
*
* The drain state of an object isn't stored in a checkpoint since
* the whole system is always going to be in the Drained state
* when the checkpoint is created. When the checkpoint is restored
* at a later stage, recreated objects will be in the Running
* state since the state isn't stored in checkpoints. This method
* performs state fixups on all Drainable objects and the
* DrainManager itself.
*/
void preCheckpointRestore();
/** Check if the system is drained */
bool isDrained() { return _state == DrainState::Drained; }
/** Get the simulators global drain state */
DrainState state() { return _state; }
/**
* Notify the DrainManager that a Drainable object has finished
* draining.
*/
void signalDrainDone();
public:
void registerDrainable(Drainable *obj);
void unregisterDrainable(Drainable *obj);
private:
/**
* Thread-safe helper function to get the number of Drainable
* objects in a system.
*/
size_t drainableCount() const;
/** Lock protecting the set of drainable objects */
mutable std::mutex globalLock;
/** Set of all drainable objects */
std::unordered_set<Drainable *> _allDrainable;
/**
* Number of objects still draining. This is flagged atomic since
* it can be manipulated by SimObjects living in different
* threads.
*/
std::atomic_uint _count;
/** Global simulator drain state */
DrainState _state;
/** Singleton instance of the drain manager */
static DrainManager _instance;
};
/**
* Interface for objects that might require draining before
* checkpointing.
*
* An object's internal state needs to be drained when creating a
* checkpoint, switching between CPU models, or switching between
* timing models. Once the internal state has been drained from
* <i>all</i> objects in the simulator, the objects are serialized to
* disc or the configuration change takes place. The process works as
* follows (see simulate.py for details):
*
* <ol>
* <li>DrainManager::tryDrain() calls Drainable::drain() for every
* object in the system. Draining has completed if all of them
* return true. Otherwise, the drain manager keeps track of the
* objects that requested draining and waits for them to signal
* that they are done draining using the signalDrainDone() method.
*
* <li>Continue simulation. When an object has finished draining its
* internal state, it calls DrainManager::signalDrainDone() on the
* manager. The drain manager keeps track of the objects that
* haven't drained yet, simulation stops when the set of
* non-drained objects becomes empty.
*
* <li>Check if any object still needs draining
* (DrainManager::tryDrain()), if so repeat the process above.
*
* <li>Serialize objects, switch CPU model, or change timing model.
*
* <li>Call DrainManager::resume(), which intern calls
* Drainable::drainResume() for all objects, and continue the
* simulation.
* </ol>
*
*/
class Drainable
{
friend class DrainManager;
protected:
Drainable();
virtual ~Drainable();
/**
* Determine if an object needs draining and register a
* DrainManager.
*
* If the object does not need further simulation to drain
* internal buffers, it returns true and automatically switches to
* the Drained state, otherwise it switches to the Draining state.
*
* @note An object that has entered the Drained state can be
* disturbed by other objects in the system and consequently be
* being drained. These perturbations are not visible in the
* drain state. The simulator therefore repeats the draining
* process until all objects return DrainState::Drained on the
* first call to drain().
*
* @return DrainState::Drained if the object is ready for
* serialization now, DrainState::Draining if it needs further
* simulation.
*/
virtual DrainState drain() = 0;
/**
* Resume execution after a successful drain.
*/
virtual void drainResume() {};
/**
* Signal that an object is drained
*
* This method is designed to be called whenever an object enters
* into a state where it is ready to be drained. The method is
* safe to call multiple times and there is no need to check that
* draining has been requested before calling this method.
*/
void signalDrainDone() const {
switch (_drainState) {
case DrainState::Running:
case DrainState::Drained:
return;
case DrainState::Draining:
_drainState = DrainState::Drained;
_drainManager.signalDrainDone();
return;
}
}
public:
/** Return the current drain state of an object. */
DrainState drainState() const { return _drainState; }
private:
/** DrainManager interface to request a drain operation */
DrainState dmDrain();
/** DrainManager interface to request a resume operation */
void dmDrainResume();
/** Convenience reference to the drain manager */
DrainManager &_drainManager;
/**
* Current drain state of the object. Needs to be mutable since
* objects need to be able to signal that they have transitioned
* into a Drained state even if the calling method is const.
*/
mutable DrainState _drainState;
};
#endif
<commit_msg>sim: Fixup comments and constness in draining infrastructure<commit_after>/*
* Copyright (c) 2012, 2015 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andreas Sandberg
*/
#ifndef __SIM_DRAIN_HH__
#define __SIM_DRAIN_HH__
#include <atomic>
#include <mutex>
#include <unordered_set>
#include "base/flags.hh"
class Drainable;
#ifndef SWIG // SWIG doesn't support strongly typed enums
/**
* Object drain/handover states
*
* An object starts out in the Running state. When the simulator
* prepares to take a snapshot or prepares a CPU for handover, it
* calls the drain() method to transfer the object into the Draining
* or Drained state. If any object enters the Draining state
* (Drainable::drain() returning >0), simulation continues until it
* all objects have entered the Drained state.
*
* Before resuming simulation, the simulator calls resume() to
* transfer the object to the Running state.
*
* \note Even though the state of an object (visible to the rest of
* the world through Drainable::getState()) could be used to determine
* if all objects have entered the Drained state, the protocol is
* actually a bit more elaborate. See Drainable::drain() for details.
*/
enum class DrainState {
Running, /** Running normally */
Draining, /** Draining buffers pending serialization/handover */
Drained /** Buffers drained, ready for serialization/handover */
};
#endif
/**
* This class coordinates draining of a System.
*
* When draining the simulator, we need to make sure that all
* Drainable objects within the system have ended up in the drained
* state before declaring the operation to be successful. This class
* keeps track of how many objects are still in the process of
* draining. Once it determines that all objects have drained their
* state, it exits the simulation loop.
*
* @note A System might not be completely drained even though the
* DrainManager has caused the simulation loop to exit. Draining needs
* to be restarted until all Drainable objects declare that they don't
* need further simulation to be completely drained. See Drainable for
* more information.
*/
class DrainManager
{
private:
DrainManager();
#ifndef SWIG
DrainManager(DrainManager &) = delete;
#endif
~DrainManager();
public:
/** Get the singleton DrainManager instance */
static DrainManager &instance() { return _instance; }
/**
* Try to drain the system.
*
* Try to drain the system and return true if all objects are in a
* the Drained state at which point the whole simulator is in a
* consistent state and ready for checkpointing or CPU
* handover. The simulation script must continue simulating until
* the simulation loop returns "Finished drain", at which point
* this method should be called again. This cycle should continue
* until this method returns true.
*
* @return true if all objects were drained successfully, false if
* more simulation is needed.
*/
bool tryDrain();
/**
* Resume normal simulation in a Drained system.
*/
void resume();
/**
* Run state fixups before a checkpoint restore operation
*
* The drain state of an object isn't stored in a checkpoint since
* the whole system is always going to be in the Drained state
* when the checkpoint is created. When the checkpoint is restored
* at a later stage, recreated objects will be in the Running
* state since the state isn't stored in checkpoints. This method
* performs state fixups on all Drainable objects and the
* DrainManager itself.
*/
void preCheckpointRestore();
/** Check if the system is drained */
bool isDrained() const { return _state == DrainState::Drained; }
/** Get the simulators global drain state */
DrainState state() const { return _state; }
/**
* Notify the DrainManager that a Drainable object has finished
* draining.
*/
void signalDrainDone();
public:
void registerDrainable(Drainable *obj);
void unregisterDrainable(Drainable *obj);
private:
/**
* Thread-safe helper function to get the number of Drainable
* objects in a system.
*/
size_t drainableCount() const;
/** Lock protecting the set of drainable objects */
mutable std::mutex globalLock;
/** Set of all drainable objects */
std::unordered_set<Drainable *> _allDrainable;
/**
* Number of objects still draining. This is flagged atomic since
* it can be manipulated by SimObjects living in different
* threads.
*/
std::atomic_uint _count;
/** Global simulator drain state */
DrainState _state;
/** Singleton instance of the drain manager */
static DrainManager _instance;
};
/**
* Interface for objects that might require draining before
* checkpointing.
*
* An object's internal state needs to be drained when creating a
* checkpoint, switching between CPU models, or switching between
* timing models. Once the internal state has been drained from
* <i>all</i> objects in the simulator, the objects are serialized to
* disc or the configuration change takes place. The process works as
* follows (see simulate.py for details):
*
* <ol>
* <li>DrainManager::tryDrain() calls Drainable::drain() for every
* object in the system. Draining has completed if all of them
* return true. Otherwise, the drain manager keeps track of the
* objects that requested draining and waits for them to signal
* that they are done draining using the signalDrainDone() method.
*
* <li>Continue simulation. When an object has finished draining its
* internal state, it calls DrainManager::signalDrainDone() on the
* manager. The drain manager keeps track of the objects that
* haven't drained yet, simulation stops when the set of
* non-drained objects becomes empty.
*
* <li>Check if any object still needs draining
* (DrainManager::tryDrain()), if so repeat the process above.
*
* <li>Serialize objects, switch CPU model, or change timing model.
*
* <li>Call DrainManager::resume(), which in turn calls
* Drainable::drainResume() for all objects, and then continue the
* simulation.
* </ol>
*
*/
class Drainable
{
friend class DrainManager;
protected:
Drainable();
virtual ~Drainable();
/**
* Notify an object that it needs to drain its state.
*
* If the object does not need further simulation to drain
* internal buffers, it returns DrainState::Drained and
* automatically switches to the Drained state. If the object
* needs more simulation, it returns DrainState::Draining and
* automatically enters the Draining state. Other return values
* are invalid.
*
* @note An object that has entered the Drained state can be
* disturbed by other objects in the system and consequently stop
* being drained. These perturbations are not visible in the drain
* state. The simulator therefore repeats the draining process
* until all objects return DrainState::Drained on the first call
* to drain().
*
* @return DrainState::Drained if the object is drained at this
* point in time, DrainState::Draining if it needs further
* simulation.
*/
virtual DrainState drain() = 0;
/**
* Resume execution after a successful drain.
*/
virtual void drainResume() {};
/**
* Signal that an object is drained
*
* This method is designed to be called whenever an object enters
* into a state where it is ready to be drained. The method is
* safe to call multiple times and there is no need to check that
* draining has been requested before calling this method.
*/
void signalDrainDone() const {
switch (_drainState) {
case DrainState::Running:
case DrainState::Drained:
return;
case DrainState::Draining:
_drainState = DrainState::Drained;
_drainManager.signalDrainDone();
return;
}
}
public:
/** Return the current drain state of an object. */
DrainState drainState() const { return _drainState; }
private:
/** DrainManager interface to request a drain operation */
DrainState dmDrain();
/** DrainManager interface to request a resume operation */
void dmDrainResume();
/** Convenience reference to the drain manager */
DrainManager &_drainManager;
/**
* Current drain state of the object. Needs to be mutable since
* objects need to be able to signal that they have transitioned
* into a Drained state even if the calling method is const.
*/
mutable DrainState _drainState;
};
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
using namespace std ;
#include <iodata/iodata>
#include <iodata/validator>
void dump_cpp(ostringstream &cpp, const string &full_name, iodata::validator *v)
{
using iodata::/*validator::*/record_type ;
using iodata::/*validator::*/node ;
using iodata::/*validator::*/node_integer ;
using iodata::/*validator::*/node_bytes ;
using iodata::/*validator::*/node_bitmask ;
using iodata::/*validator::*/node_record ;
cpp << "iodata::validator * " << full_name << "()" << "{" << endl ;
cpp << "static bool init_done = false ;" << endl ;
cpp << "static iodata::validator A ;" << endl ;
map<record_type*, int> record_type_to_num ;
int rec_no = 0 ;
for (map<string,record_type*>::iterator it = v->types.begin(); it != v->types.end() and ++rec_no; ++it)
{
record_type *rt = it->second ;
record_type_to_num[rt] = rec_no ;
cpp << "static iodata::validator::record_type record_type" << rec_no << " = { " ;
cpp << '"' << it->first << '"' << ", " << rt->nodes.size() << " } ;" << endl ;
}
map<node*, int> node_to_num ;
int node_no = 0 ;
int bitmask_no = 0 ;
for (map<string,record_type*>::iterator it = v->types.begin(); it != v->types.end() and ++rec_no; ++it)
{
record_type *rt = it->second ;
for (vector<node*>::iterator nit = rt->nodes.begin(); nit !=rt->nodes.end(); ++nit)
{
node *no = *nit ;
node_to_num[no] = ++node_no ;
if (node_bitmask *nn = dynamic_cast<node_bitmask*> (no))
{
cpp << "static const char *bitmask_list" << ++bitmask_no << "[] = { " ;
for(set<string>::const_iterator it=nn->value.xs.begin(); it!=nn->value.xs.end(); ++it)
cpp << '"' << *it << '"' << ", " ;
cpp << "NULL } ;" << endl ;
}
cpp << "static iodata::validator::" << no->node_name() << " node" << node_no ;
cpp << "(" << '"' << no->name << '"' << ", " ;
cpp << no->is_array << ", " << no->is_mandatory << ", " ;
if (node_integer *nn = dynamic_cast<node_integer*> (no))
cpp << nn->value ;
else if (node_bytes *nn = dynamic_cast<node_bytes*> (no))
cpp << '"' << nn->value << '"' ;
else if (node_record *nn = dynamic_cast<node_record*> (no))
cpp << '"' << nn->type_name << '"' ;
else if (node_bitmask *nn = dynamic_cast<node_bitmask*> (no))
cpp << "iodata::bitmask(" << nn->value.xl << ", bitmask_list" << bitmask_no << ")" ;
cpp << ") ;" << endl ;
}
}
}
int main(int ac, char **av)
{
for (int i=1; i<=ac; ++i)
{
cout << "// " << av[i] << endl ;
iodata::validator *v = iodata::validator::from_file(av[i]) ;
ostringstream cpp ;
dump_cpp (cpp, (string)"blah", v) ;
cout << cpp.str() << endl << endl ;
}
return 0 ;
}
<commit_msg>minor<commit_after>#include <iostream>
using namespace std ;
#include <iodata/iodata>
#include <iodata/validator>
void dump_cpp(ostringstream &cpp, const string &full_name, iodata::validator *v)
{
using iodata::/*validator::*/record_type ;
using iodata::/*validator::*/node ;
using iodata::/*validator::*/node_integer ;
using iodata::/*validator::*/node_bytes ;
using iodata::/*validator::*/node_bitmask ;
using iodata::/*validator::*/node_record ;
cpp << "iodata::validator * " << full_name << "()" << "{" << endl ;
cpp << "static bool init_done = false ;" << endl ;
cpp << "static iodata::validator A ;" << endl ;
map<record_type*, int> record_type_to_num ;
int rec_no = 0 ;
for (map<string,record_type*>::iterator it = v->types.begin(); it != v->types.end() and ++rec_no; ++it)
{
record_type *rt = it->second ;
record_type_to_num[rt] = rec_no ;
cpp << "static iodata::validator::record_type record_type" << rec_no << " = { " ;
cpp << '"' << it->first << '"' << ", " << rt->nodes.size() << " } ;" << endl ;
}
map<node*, int> node_to_num ;
int node_no = 0 ;
int bitmask_no = 0 ;
for (map<string,record_type*>::iterator it = v->types.begin(); it != v->types.end() and ++rec_no; ++it)
{
record_type *rt = it->second ;
for (vector<node*>::iterator nit = rt->nodes.begin(); nit !=rt->nodes.end(); ++nit)
{
node *no = *nit ;
node_to_num[no] = ++node_no ;
if (node_bitmask *nn = dynamic_cast<node_bitmask*> (no))
{
cpp << "static const char *bitmask_list" << ++bitmask_no << "[] = { " ;
for(set<string>::const_iterator it=nn->value.xs.begin(); it!=nn->value.xs.end(); ++it)
cpp << '"' << *it << '"' << ", " ;
cpp << "NULL } ;" << endl ;
}
cpp << "static iodata::validator::" << no->node_name() << " node" << node_no ;
cpp << "(" << '"' << no->name << '"' << ", " ;
cpp << no->is_array << ", " << no->is_mandatory << ", " ;
if (node_integer *nn = dynamic_cast<node_integer*> (no))
cpp << nn->value ;
else if (node_bytes *nn = dynamic_cast<node_bytes*> (no))
cpp << '"' << nn->value << '"' ;
else if (node_record *nn = dynamic_cast<node_record*> (no))
cpp << '"' << nn->type_name << '"' ;
else if (node_bitmask *nn = dynamic_cast<node_bitmask*> (no))
cpp << "iodata::bitmask(" << nn->value.xl << ", bitmask_list" << bitmask_no << ")" ;
cpp << ") ;" << endl ;
}
}
}
int main(int ac, char **av)
{
for (int i=1; i<ac; ++i)
{
cout << "// " << av[i] << endl ;
iodata::validator *v = iodata::validator::from_file(av[i]) ;
ostringstream cpp ;
dump_cpp (cpp, (string)"blah", v) ;
cout << cpp.str() << endl << endl ;
}
return 0 ;
}
<|endoftext|>
|
<commit_before>/*
* 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 <QDesktopServices>
#include <QFileDialog>
#include <QScrollBar>
#include <QToolButton>
#include <QUrl>
#include "ty.h"
#include "about_dialog.hh"
#include "board_widget.hh"
#include "commands.hh"
#include "main_window.hh"
#include "tyqt.hh"
using namespace std;
MainWindow::MainWindow(Manager *manager, QWidget *parent)
: QMainWindow(parent), manager_(manager)
{
setupUi(this);
connect(actionQuit, &QAction::triggered, TyQt::instance(), &TyQt::quit);
QObject *obj = toolBar->widgetForAction(actionUpload);
if (obj) {
QToolButton* uploadButton = qobject_cast<QToolButton *>(obj);
if (uploadButton) {
QMenu *uploadMenu = new QMenu(this);
uploadMenu->addAction(actionUploadNew);
uploadMenu->addSeparator();
uploadMenu->addAction(actionUploadAll);
uploadButton->setMenu(uploadMenu);
uploadButton->setPopupMode(QToolButton::MenuButtonPopup);
}
}
disableBoardWidgets();
monitorText->setWordWrapMode(QTextOption::WrapAnywhere);
boardList->setModel(manager);
boardList->setItemDelegate(new BoardItemDelegate(manager));
connect(boardList->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::selectionChanged);
connect(manager, &Manager::boardAdded, this, &MainWindow::setBoardDefaults);
connect(monitorText, &QPlainTextEdit::textChanged, this, &MainWindow::monitorTextChanged);
connect(monitorText, &QPlainTextEdit::updateRequest, this, &MainWindow::monitorTextScrolled);
for (auto &board: *manager)
setBoardDefaults(board);
}
void MainWindow::disableBoardWidgets()
{
setWindowTitle("TyQt");
infoTab->setEnabled(false);
modelText->clear();
locationText->clear();
serialText->clear();
interfaceTree->clear();
monitorTab->setEnabled(false);
monitorEdit->setEnabled(false);
actionUpload->setEnabled(false);
actionUploadNew->setEnabled(false);
uploadTab->setEnabled(false);
firmwarePath->clear();
actionReset->setEnabled(false);
actionReboot->setEnabled(false);
}
QString MainWindow::browseForFirmware()
{
QString filename = QFileDialog::getOpenFileName(this, tr("Open Firmware"), QString(),
tr("Binary Files (*.elf *.hex);;All Files (*)"));
if (filename.isEmpty())
return QString();
firmwarePath->setText(filename);
emit firmwarePath->editingFinished();
return filename;
}
void MainWindow::setBoardDefaults(shared_ptr<Board> board)
{
board->setProperty("resetAfter", true);
if (!boardList->currentIndex().isValid() && manager_->boardCount())
boardList->setCurrentIndex(manager_->index(0, 0));
}
void MainWindow::selectionChanged(const QItemSelection &selected, const QItemSelection &previous)
{
TY_UNUSED(previous);
if (current_board_)
current_board_->disconnect(this);
if (selected.indexes().isEmpty()) {
monitorText->setDocument(nullptr);
current_board_ = nullptr;
disableBoardWidgets();
return;
}
current_board_ = manager_->board(selected.indexes().front().row());
firmwarePath->setText(current_board_->property("firmware").toString());
resetAfterUpload->setChecked(current_board_->property("resetAfter").toBool());
monitor_autoscroll_ = true;
clearOnReset->setChecked(current_board_->clearOnReset());
monitor_cursor_ = QTextCursor();
monitorText->setDocument(¤t_board_->serialDocument());
monitorText->moveCursor(QTextCursor::End);
monitorText->verticalScrollBar()->setValue(monitorText->verticalScrollBar()->maximum());
connect(current_board_.get(), &Board::boardChanged, this, &MainWindow::refreshBoardInfo);
connect(current_board_.get(), &Board::propertyChanged, this, &MainWindow::updatePropertyField);
refreshBoardInfo();
}
void MainWindow::refreshBoardInfo()
{
setWindowTitle(QString("TyQt - %1 - %2")
.arg(current_board_->modelName())
.arg(current_board_->tag()));
infoTab->setEnabled(true);
modelText->setText(current_board_->modelName());
locationText->setText(current_board_->location());
serialText->setText(QString::number(current_board_->serialNumber()));
interfaceTree->clear();
for (auto iface: current_board_->interfaces()) {
auto item = new QTreeWidgetItem(QStringList{iface.desc, iface.path});
item->setToolTip(1, iface.path);
new QTreeWidgetItem(item, QStringList{tr("capabilities"),
Board::makeCapabilityList(current_board_->capabilities()).join(", ")});
new QTreeWidgetItem(item, QStringList{tr("location"),
QString("%1:%2").arg(current_board_->location(), QString::number(iface.number))});
interfaceTree->addTopLevelItem(item);
}
monitorTab->setEnabled(true);
monitorEdit->setEnabled(current_board_->isSerialAvailable());
if (current_board_->isUploadAvailable()) {
actionUpload->setEnabled(true);
actionUploadNew->setEnabled(true);
uploadTab->setEnabled(true);
} else {
actionUpload->setEnabled(false);
actionUploadNew->setEnabled(false);
uploadTab->setEnabled(false);
}
actionReset->setEnabled(current_board_->isResetAvailable());
actionReboot->setEnabled(current_board_->isRebootAvailable());
}
void MainWindow::updatePropertyField(const QByteArray &name, const QVariant &value)
{
if (name == "firmware") {
firmwarePath->setText(value.toString());
} else if (name == "resetAfter") {
resetAfterUpload->setChecked(value.toBool());
} else if (name == "clearOnReset") {
clearOnReset->setChecked(value.toBool());
}
}
void MainWindow::monitorTextChanged()
{
if (monitor_autoscroll_) {
monitorText->verticalScrollBar()->setValue(monitorText->verticalScrollBar()->maximum());
} else {
QTextCursor old_cursor = monitorText->textCursor();
monitorText->setTextCursor(monitor_cursor_);
monitorText->ensureCursorVisible();
int position = monitorText->verticalScrollBar()->value();
monitorText->setTextCursor(old_cursor);
monitorText->verticalScrollBar()->setValue(position);
}
}
void MainWindow::monitorTextScrolled(const QRect &rect, int dy)
{
TY_UNUSED(rect);
if (!dy)
return;
QScrollBar *vbar = monitorText->verticalScrollBar();
monitor_autoscroll_ = vbar->value() >= vbar->maximum() - 1;
monitor_cursor_ = monitorText->cursorForPosition(QPoint(0, 0));
}
void MainWindow::clearMonitor()
{
monitor_cursor_ = QTextCursor();
monitorText->clear();
}
void MainWindow::showErrorMessage(const QString &msg)
{
statusBar()->showMessage(msg, 5000);
logText->appendPlainText(msg);
}
void MainWindow::on_firmwarePath_editingFinished()
{
if (!current_board_)
return;
if (!firmwarePath->text().isEmpty()) {
QString firmware = QFileInfo(firmwarePath->text()).canonicalFilePath();
if (firmware.isEmpty()) {
tyQt->reportError(tr("Path '%1' is not valid").arg(firmwarePath->text()));
return;
}
current_board_->setProperty("firmware", firmware);
} else {
current_board_->setProperty("firmware", QVariant());
}
}
void MainWindow::on_resetAfterUpload_toggled(bool checked)
{
if (!current_board_)
return;
current_board_->setProperty("resetAfter", checked);
}
void MainWindow::on_actionNewWindow_triggered()
{
tyQt->openMainWindow();
}
void MainWindow::on_actionUpload_triggered()
{
if (!current_board_)
return;
if (current_board_->property("firmware").toString().isEmpty()) {
QString filename = browseForFirmware();
if (filename.isEmpty())
return;
Commands::upload(*current_board_, filename).start();
} else {
Commands::upload(*current_board_, "").start();
}
}
void MainWindow::on_actionUploadNew_triggered()
{
if (!current_board_)
return;
QString filename = browseForFirmware();
if (filename.isEmpty())
return;
Commands::upload(*current_board_, filename).start();
}
void MainWindow::on_actionUploadAll_triggered()
{
Commands::uploadAll().start();
}
void MainWindow::on_actionReset_triggered()
{
if (!current_board_)
return;
current_board_->reset().start();
}
void MainWindow::on_actionReboot_triggered()
{
if (!current_board_)
return;
current_board_->reboot().start();
}
void MainWindow::on_monitorEdit_returnPressed()
{
if (!current_board_)
return;
QString s = monitorEdit->text();
monitorEdit->clear();
switch (newlineComboBox->currentIndex()) {
case 1:
s += '\n';
break;
case 2:
s += '\r';
break;
case 3:
s += "\r\n";
break;
default:
break;
}
if (echo->isChecked())
current_board_->appendToSerialDocument(s);
current_board_->sendSerial(s.toUtf8());
}
void MainWindow::on_clearOnReset_toggled(bool checked)
{
if (!current_board_)
return;
current_board_->setClearOnReset(checked);
}
void MainWindow::on_actionMinimalInterface_toggled(bool checked)
{
toolBar->setVisible(!checked);
boardList->setVisible(!checked);
statusbar->setVisible(!checked);
}
void MainWindow::on_actionClearMonitor_triggered()
{
clearMonitor();
}
void MainWindow::on_firmwareBrowseButton_clicked()
{
browseForFirmware();
}
void MainWindow::on_monitorText_customContextMenuRequested(const QPoint &pos)
{
QMenu *menu = monitorText->createStandardContextMenu();
menu->addAction(actionClearMonitor);
menu->exec(monitorText->viewport()->mapToGlobal(pos));
}
void MainWindow::on_logText_customContextMenuRequested(const QPoint &pos)
{
QMenu *menu = logText->createStandardContextMenu();
menu->addAction(tr("Clear"), logText, SLOT(clear()));
menu->exec(logText->viewport()->mapToGlobal(pos));
}
void MainWindow::on_actionWebsite_triggered()
{
QDesktopServices::openUrl(QUrl("https://github.com/Koromix/ty/"));
}
void MainWindow::on_actionReportBug_triggered()
{
QDesktopServices::openUrl(QUrl("https://github.com/Koromix/ty/issues"));
}
void MainWindow::on_actionAbout_triggered()
{
AboutDialog(this).exec();
}
<commit_msg>Limit the log size to 1000 lines<commit_after>/*
* 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 <QDesktopServices>
#include <QFileDialog>
#include <QScrollBar>
#include <QToolButton>
#include <QUrl>
#include "ty.h"
#include "about_dialog.hh"
#include "board_widget.hh"
#include "commands.hh"
#include "main_window.hh"
#include "tyqt.hh"
using namespace std;
MainWindow::MainWindow(Manager *manager, QWidget *parent)
: QMainWindow(parent), manager_(manager)
{
setupUi(this);
connect(actionQuit, &QAction::triggered, TyQt::instance(), &TyQt::quit);
QObject *obj = toolBar->widgetForAction(actionUpload);
if (obj) {
QToolButton* uploadButton = qobject_cast<QToolButton *>(obj);
if (uploadButton) {
QMenu *uploadMenu = new QMenu(this);
uploadMenu->addAction(actionUploadNew);
uploadMenu->addSeparator();
uploadMenu->addAction(actionUploadAll);
uploadButton->setMenu(uploadMenu);
uploadButton->setPopupMode(QToolButton::MenuButtonPopup);
}
}
disableBoardWidgets();
monitorText->setWordWrapMode(QTextOption::WrapAnywhere);
boardList->setModel(manager);
boardList->setItemDelegate(new BoardItemDelegate(manager));
connect(boardList->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::selectionChanged);
connect(manager, &Manager::boardAdded, this, &MainWindow::setBoardDefaults);
connect(monitorText, &QPlainTextEdit::textChanged, this, &MainWindow::monitorTextChanged);
connect(monitorText, &QPlainTextEdit::updateRequest, this, &MainWindow::monitorTextScrolled);
for (auto &board: *manager)
setBoardDefaults(board);
logText->setMaximumBlockCount(1000);
}
void MainWindow::disableBoardWidgets()
{
setWindowTitle("TyQt");
infoTab->setEnabled(false);
modelText->clear();
locationText->clear();
serialText->clear();
interfaceTree->clear();
monitorTab->setEnabled(false);
monitorEdit->setEnabled(false);
actionUpload->setEnabled(false);
actionUploadNew->setEnabled(false);
uploadTab->setEnabled(false);
firmwarePath->clear();
actionReset->setEnabled(false);
actionReboot->setEnabled(false);
}
QString MainWindow::browseForFirmware()
{
QString filename = QFileDialog::getOpenFileName(this, tr("Open Firmware"), QString(),
tr("Binary Files (*.elf *.hex);;All Files (*)"));
if (filename.isEmpty())
return QString();
firmwarePath->setText(filename);
emit firmwarePath->editingFinished();
return filename;
}
void MainWindow::setBoardDefaults(shared_ptr<Board> board)
{
board->setProperty("resetAfter", true);
if (!boardList->currentIndex().isValid() && manager_->boardCount())
boardList->setCurrentIndex(manager_->index(0, 0));
}
void MainWindow::selectionChanged(const QItemSelection &selected, const QItemSelection &previous)
{
TY_UNUSED(previous);
if (current_board_)
current_board_->disconnect(this);
if (selected.indexes().isEmpty()) {
monitorText->setDocument(nullptr);
current_board_ = nullptr;
disableBoardWidgets();
return;
}
current_board_ = manager_->board(selected.indexes().front().row());
firmwarePath->setText(current_board_->property("firmware").toString());
resetAfterUpload->setChecked(current_board_->property("resetAfter").toBool());
monitor_autoscroll_ = true;
clearOnReset->setChecked(current_board_->clearOnReset());
monitor_cursor_ = QTextCursor();
monitorText->setDocument(¤t_board_->serialDocument());
monitorText->moveCursor(QTextCursor::End);
monitorText->verticalScrollBar()->setValue(monitorText->verticalScrollBar()->maximum());
connect(current_board_.get(), &Board::boardChanged, this, &MainWindow::refreshBoardInfo);
connect(current_board_.get(), &Board::propertyChanged, this, &MainWindow::updatePropertyField);
refreshBoardInfo();
}
void MainWindow::refreshBoardInfo()
{
setWindowTitle(QString("TyQt - %1 - %2")
.arg(current_board_->modelName())
.arg(current_board_->tag()));
infoTab->setEnabled(true);
modelText->setText(current_board_->modelName());
locationText->setText(current_board_->location());
serialText->setText(QString::number(current_board_->serialNumber()));
interfaceTree->clear();
for (auto iface: current_board_->interfaces()) {
auto item = new QTreeWidgetItem(QStringList{iface.desc, iface.path});
item->setToolTip(1, iface.path);
new QTreeWidgetItem(item, QStringList{tr("capabilities"),
Board::makeCapabilityList(current_board_->capabilities()).join(", ")});
new QTreeWidgetItem(item, QStringList{tr("location"),
QString("%1:%2").arg(current_board_->location(), QString::number(iface.number))});
interfaceTree->addTopLevelItem(item);
}
monitorTab->setEnabled(true);
monitorEdit->setEnabled(current_board_->isSerialAvailable());
if (current_board_->isUploadAvailable()) {
actionUpload->setEnabled(true);
actionUploadNew->setEnabled(true);
uploadTab->setEnabled(true);
} else {
actionUpload->setEnabled(false);
actionUploadNew->setEnabled(false);
uploadTab->setEnabled(false);
}
actionReset->setEnabled(current_board_->isResetAvailable());
actionReboot->setEnabled(current_board_->isRebootAvailable());
}
void MainWindow::updatePropertyField(const QByteArray &name, const QVariant &value)
{
if (name == "firmware") {
firmwarePath->setText(value.toString());
} else if (name == "resetAfter") {
resetAfterUpload->setChecked(value.toBool());
} else if (name == "clearOnReset") {
clearOnReset->setChecked(value.toBool());
}
}
void MainWindow::monitorTextChanged()
{
if (monitor_autoscroll_) {
monitorText->verticalScrollBar()->setValue(monitorText->verticalScrollBar()->maximum());
} else {
QTextCursor old_cursor = monitorText->textCursor();
monitorText->setTextCursor(monitor_cursor_);
monitorText->ensureCursorVisible();
int position = monitorText->verticalScrollBar()->value();
monitorText->setTextCursor(old_cursor);
monitorText->verticalScrollBar()->setValue(position);
}
}
void MainWindow::monitorTextScrolled(const QRect &rect, int dy)
{
TY_UNUSED(rect);
if (!dy)
return;
QScrollBar *vbar = monitorText->verticalScrollBar();
monitor_autoscroll_ = vbar->value() >= vbar->maximum() - 1;
monitor_cursor_ = monitorText->cursorForPosition(QPoint(0, 0));
}
void MainWindow::clearMonitor()
{
monitor_cursor_ = QTextCursor();
monitorText->clear();
}
void MainWindow::showErrorMessage(const QString &msg)
{
statusBar()->showMessage(msg, 5000);
logText->appendPlainText(msg);
}
void MainWindow::on_firmwarePath_editingFinished()
{
if (!current_board_)
return;
if (!firmwarePath->text().isEmpty()) {
QString firmware = QFileInfo(firmwarePath->text()).canonicalFilePath();
if (firmware.isEmpty()) {
tyQt->reportError(tr("Path '%1' is not valid").arg(firmwarePath->text()));
return;
}
current_board_->setProperty("firmware", firmware);
} else {
current_board_->setProperty("firmware", QVariant());
}
}
void MainWindow::on_resetAfterUpload_toggled(bool checked)
{
if (!current_board_)
return;
current_board_->setProperty("resetAfter", checked);
}
void MainWindow::on_actionNewWindow_triggered()
{
tyQt->openMainWindow();
}
void MainWindow::on_actionUpload_triggered()
{
if (!current_board_)
return;
if (current_board_->property("firmware").toString().isEmpty()) {
QString filename = browseForFirmware();
if (filename.isEmpty())
return;
Commands::upload(*current_board_, filename).start();
} else {
Commands::upload(*current_board_, "").start();
}
}
void MainWindow::on_actionUploadNew_triggered()
{
if (!current_board_)
return;
QString filename = browseForFirmware();
if (filename.isEmpty())
return;
Commands::upload(*current_board_, filename).start();
}
void MainWindow::on_actionUploadAll_triggered()
{
Commands::uploadAll().start();
}
void MainWindow::on_actionReset_triggered()
{
if (!current_board_)
return;
current_board_->reset().start();
}
void MainWindow::on_actionReboot_triggered()
{
if (!current_board_)
return;
current_board_->reboot().start();
}
void MainWindow::on_monitorEdit_returnPressed()
{
if (!current_board_)
return;
QString s = monitorEdit->text();
monitorEdit->clear();
switch (newlineComboBox->currentIndex()) {
case 1:
s += '\n';
break;
case 2:
s += '\r';
break;
case 3:
s += "\r\n";
break;
default:
break;
}
if (echo->isChecked())
current_board_->appendToSerialDocument(s);
current_board_->sendSerial(s.toUtf8());
}
void MainWindow::on_clearOnReset_toggled(bool checked)
{
if (!current_board_)
return;
current_board_->setClearOnReset(checked);
}
void MainWindow::on_actionMinimalInterface_toggled(bool checked)
{
toolBar->setVisible(!checked);
boardList->setVisible(!checked);
statusbar->setVisible(!checked);
}
void MainWindow::on_actionClearMonitor_triggered()
{
clearMonitor();
}
void MainWindow::on_firmwareBrowseButton_clicked()
{
browseForFirmware();
}
void MainWindow::on_monitorText_customContextMenuRequested(const QPoint &pos)
{
QMenu *menu = monitorText->createStandardContextMenu();
menu->addAction(actionClearMonitor);
menu->exec(monitorText->viewport()->mapToGlobal(pos));
}
void MainWindow::on_logText_customContextMenuRequested(const QPoint &pos)
{
QMenu *menu = logText->createStandardContextMenu();
menu->addAction(tr("Clear"), logText, SLOT(clear()));
menu->exec(logText->viewport()->mapToGlobal(pos));
}
void MainWindow::on_actionWebsite_triggered()
{
QDesktopServices::openUrl(QUrl("https://github.com/Koromix/ty/"));
}
void MainWindow::on_actionReportBug_triggered()
{
QDesktopServices::openUrl(QUrl("https://github.com/Koromix/ty/issues"));
}
void MainWindow::on_actionAbout_triggered()
{
AboutDialog(this).exec();
}
<|endoftext|>
|
<commit_before>/*
INTERVAL.cc -- interface implementation of real intervals for the iRRAM library
Copyright (C) 2003 Norbert Mueller, Shao Qi
This file is part of the iRRAM Library.
The iRRAM 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.
The iRRAM 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 the iRRAM 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 "iRRAM/core.h"
namespace iRRAM {
INTERVAL::INTERVAL()
{
low=0;
upp=0;
}
INTERVAL::INTERVAL(const REAL& x)
{
low=x;
upp=x;
}
INTERVAL::INTERVAL(const REAL& x, const REAL& y)
{
low=minimum(x,y);
upp=maximum(x,y);
};
INTERVAL operator + (const INTERVAL & x, const INTERVAL & y){
return INTERVAL( x.low+y.low, x.upp+y.upp );
};
INTERVAL operator - (const INTERVAL & x, const INTERVAL & y){
return INTERVAL( x.low-y.upp, x.upp-y.low );
};
INTERVAL operator - (const INTERVAL & x){
return INTERVAL( -x.upp, -x.low);
};
INTERVAL operator * (const INTERVAL & x, const INTERVAL & y){
REAL aa= x.low*y.low;
REAL ab= x.upp*y.low;
REAL ba= x.low*y.upp;
REAL bb= x.upp*y.upp ;
REAL mina=minimum(aa,ab);
REAL minb=minimum(ba,bb);
REAL maxa=maximum(aa,ab);
REAL maxb=maximum(bb,ba);
return INTERVAL(minimum(mina,minb),maximum(maxa,maxb));
};
INTERVAL operator / (const INTERVAL & x, const INTERVAL & y){
if ( y.low< REAL(0) && REAL(0) < y.upp ) {
throw iRRAM_Numerical_Exception(iRRAM_interval_divide_by_zero);
}
return INTERVAL(1/y.low,1/y.upp)*x;
};
REAL wid(const INTERVAL& x){
return x.upp-x.low ;
}
REAL inf(const INTERVAL& x){
return x.low;
}
REAL sup(const INTERVAL& x){
return x.upp;
}
REAL mid(const INTERVAL& x){
return (x.upp+x.low)/2;
}
REAL mag(const INTERVAL& x){
return maximum(abs(x.upp),abs(x.low));
};
REAL mig(const INTERVAL& x){
return maximum(REAL(0),x.low)-minimum(REAL(0),x.upp);
};
INTERVAL fabs(const INTERVAL& x){
return INTERVAL(maximum(x.low,REAL(0))-minimum(x.upp,REAL(0)),
maximum(abs(x.low),abs(x.upp)));
}
INTERVAL exp(const INTERVAL& x){
// exp is monotonic increasing, so the following is sufficient:
return INTERVAL(exp(x.low),exp(x.upp));
}
INTERVAL log(const INTERVAL& x){
// log is monotonic increasing, so the following is sufficient:
return INTERVAL(log(x.low),log(x.upp));
}
INTERVAL sin(const INTERVAL& x){
// first, using lazy booleans, we do a multivalued test
// whether the interval width is definitely at least 2*pi.
int test=choose( x.upp-x.low >= 2*pi(),
x.upp-x.low < 3*pi());
// if the width is at least 2*pi, return the closed interval [-1,1]
if ( test == 1 ) return INTERVAL(REAL(-1), REAL(1));
// now we have a width of at most 3*pi,
// and we do a range reduction
REAL inf_reduced=modulo(x.low,2*pi());
REAL sup_reduced=x.upp- (x.low-inf_reduced);
// now we have -2*pi <= inf_reduced<= sup_reduced <= 5*pi
// with a difference between the values of at most 3*pi
// we could estimate which odd multiples of pi/2 lie between the
// borders of the reduced interval, but for simplicity here I try all
// 7 possibilities (it was easier using copy and paste...)
// the following values are either
// inf_reduced, or
// sup_reduced, or
// the multiple of pi/2, in case it lies between the two values
REAL p1= maximum(inf_reduced,minimum(sup_reduced,-3*pi()/2));
REAL p2= maximum(inf_reduced,minimum(sup_reduced, -pi()/2));
REAL p3= maximum(inf_reduced,minimum(sup_reduced, pi()/2));
REAL p4= maximum(inf_reduced,minimum(sup_reduced, 3*pi()/2));
REAL p5= maximum(inf_reduced,minimum(sup_reduced, 5*pi()/2));
REAL p6= maximum(inf_reduced,minimum(sup_reduced, 7*pi()/2));
REAL p7= maximum(inf_reduced,minimum(sup_reduced, 9*pi()/2));
REAL s1=sin(p1);
REAL s2=sin(p2);
REAL s3=sin(p3);
REAL s4=sin(p4);
REAL s5=sin(p5);
REAL s6=sin(p6);
REAL s7=sin(p7);
REAL inf_min=minimum(sin(inf_reduced),sin(sup_reduced));
inf_min=minimum(inf_min,s1);
inf_min=minimum(inf_min,s2);
inf_min=minimum(inf_min,s3);
inf_min=minimum(inf_min,s4);
inf_min=minimum(inf_min,s5);
inf_min=minimum(inf_min,s6);
inf_min=minimum(inf_min,s7);
REAL sup_min=maximum(sin(inf_reduced),sin(sup_reduced));
sup_min=maximum(sup_min,s1);
sup_min=maximum(sup_min,s2);
sup_min=maximum(sup_min,s3);
sup_min=maximum(sup_min,s4);
sup_min=maximum(sup_min,s5);
sup_min=maximum(sup_min,s6);
sup_min=maximum(sup_min,s7);
return INTERVAL(inf_min,sup_min);
}
INTERVAL cos(const INTERVAL& x){
// using lazy booleans, we do a multivalued test whether
// the interval width is definitely at least 2*pi.
int test=choose( x.upp-x.low >= 2*pi(),
x.upp-x.low < 3*pi());
// if the width is at least 2*pi, return the closed interval [-1,1]
if ( test == 1 ) return INTERVAL(REAL(-1), REAL(1));
// now we have a width of at most 3*pi
// we do a range reduction
REAL inf_reduced=modulo(x.low,2*pi());
REAL sup_reduced=x.upp- (x.low-inf_reduced);
// now we have -2*pi <= inf_reduced<= sup_reduced <= 5*pi
// with a difference between the values of at most 3*pi
// now we could estimate which multiples of pi lie between the
// borders of the reduced interval, but for simplicity here I try all
// 8 possibilities (it was easier using copy and paste...)
// the following values are either
// inf_reduced, or
// sup_reduced, or
// a multiple of pi, in case it lies between the two values
REAL p1= maximum(inf_reduced,minimum(sup_reduced,-2*pi()));
REAL p2= maximum(inf_reduced,minimum(sup_reduced, -pi()));
REAL p3= maximum(inf_reduced,minimum(sup_reduced,REAL(0.0)));
REAL p4= maximum(inf_reduced,minimum(sup_reduced, pi()));
REAL p5= maximum(inf_reduced,minimum(sup_reduced, 2*pi()));
REAL p6= maximum(inf_reduced,minimum(sup_reduced, 3*pi()));
REAL p7= maximum(inf_reduced,minimum(sup_reduced, 4*pi()));
REAL s1=cos(p1);
REAL s2=cos(p2);
REAL s3=cos(p3);
REAL s4=cos(p4);
REAL s5=cos(p5);
REAL s6=cos(p6);
REAL s7=cos(p7);
REAL inf_min=minimum(cos(inf_reduced),cos(sup_reduced));
inf_min=minimum(inf_min,s1);
inf_min=minimum(inf_min,s2);
inf_min=minimum(inf_min,s3);
inf_min=minimum(inf_min,s4);
inf_min=minimum(inf_min,s5);
inf_min=minimum(inf_min,s6);
inf_min=minimum(inf_min,s7);
REAL sup_min=maximum(cos(inf_reduced),cos(sup_reduced));
sup_min=maximum(sup_min,s1);
sup_min=maximum(sup_min,s2);
sup_min=maximum(sup_min,s3);
sup_min=maximum(sup_min,s4);
sup_min=maximum(sup_min,s5);
sup_min=maximum(sup_min,s6);
sup_min=maximum(sup_min,s7);
return INTERVAL(inf_min,sup_min);
}
INTERVAL tan(const INTERVAL& x){
// If there is no odd multiple of pi/2 between the borders of
// the interval x, then the monotonicity of tan() is sufficient
// for the following formula to give the correct result:
return INTERVAL(tan(x.low),tan(x.upp));
// If on the other hand, there is such a multiple, then
// tan(x) is no proper interval.
// We choose to stay with the upper formula in this case.
// Another possibility would be to throw an exception.
}
INTERVAL asin(const INTERVAL& x){
return INTERVAL (asin(maximum(x.low,REAL(-1))),
asin(minimum(x.upp,REAL(1))));
}
INTERVAL acos(const INTERVAL& x){
return INTERVAL (acos(minimum(x.upp,REAL(1))),
acos(maximum(x.low,REAL(-1))));
}
INTERVAL atan(const INTERVAL& x){
return INTERVAL (atan(x.low),atan(x.upp));
}
LAZY_BOOLEAN superset (const INTERVAL& x,
const INTERVAL& y){
return ( (x.low <= y.low)&&(x.upp >= y.upp) );
};
LAZY_BOOLEAN proper_superset (const INTERVAL& x, const INTERVAL& y){
return superset(x,y); };
LAZY_BOOLEAN subset (const INTERVAL& x, const INTERVAL& y){
return superset(y,x); };
LAZY_BOOLEAN proper_subset (const INTERVAL& x, const INTERVAL& y){
return superset(y,x); };
LAZY_BOOLEAN in_interior (const INTERVAL& x, const INTERVAL& y){
return superset(y,x); };
LAZY_BOOLEAN disjoint (const INTERVAL& x, const INTERVAL& y){
return ( (x.low > y.upp) || (y.low > x.upp));};
LAZY_BOOLEAN in (const REAL& x, const INTERVAL& y){
return ( (y.low <= x) && (x <= y.upp) );};
INTERVAL interval_hull (const INTERVAL& x, const INTERVAL& y){
return INTERVAL(minimum(x.low,y.low),maximum(x.upp,x.upp));};
INTERVAL intersect (const INTERVAL& x, const INTERVAL& y){
return INTERVAL(maximum(x.low,y.low),minimum(x.upp,x.upp));};
} // namespace iRRAM
<commit_msg>-Wpedantic: removed unneeded ";"<commit_after>/*
INTERVAL.cc -- interface implementation of real intervals for the iRRAM library
Copyright (C) 2003 Norbert Mueller, Shao Qi
This file is part of the iRRAM Library.
The iRRAM 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.
The iRRAM 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 the iRRAM 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 "iRRAM/core.h"
namespace iRRAM {
INTERVAL::INTERVAL()
{
low=0;
upp=0;
}
INTERVAL::INTERVAL(const REAL& x)
{
low=x;
upp=x;
}
INTERVAL::INTERVAL(const REAL& x, const REAL& y)
{
low=minimum(x,y);
upp=maximum(x,y);
}
INTERVAL operator + (const INTERVAL & x, const INTERVAL & y){
return INTERVAL( x.low+y.low, x.upp+y.upp );
}
INTERVAL operator - (const INTERVAL & x, const INTERVAL & y){
return INTERVAL( x.low-y.upp, x.upp-y.low );
}
INTERVAL operator - (const INTERVAL & x){
return INTERVAL( -x.upp, -x.low);
}
INTERVAL operator * (const INTERVAL & x, const INTERVAL & y){
REAL aa= x.low*y.low;
REAL ab= x.upp*y.low;
REAL ba= x.low*y.upp;
REAL bb= x.upp*y.upp ;
REAL mina=minimum(aa,ab);
REAL minb=minimum(ba,bb);
REAL maxa=maximum(aa,ab);
REAL maxb=maximum(bb,ba);
return INTERVAL(minimum(mina,minb),maximum(maxa,maxb));
}
INTERVAL operator / (const INTERVAL & x, const INTERVAL & y){
if ( y.low< REAL(0) && REAL(0) < y.upp ) {
throw iRRAM_Numerical_Exception(iRRAM_interval_divide_by_zero);
}
return INTERVAL(1/y.low,1/y.upp)*x;
}
REAL wid(const INTERVAL& x){
return x.upp-x.low ;
}
REAL inf(const INTERVAL& x){
return x.low;
}
REAL sup(const INTERVAL& x){
return x.upp;
}
REAL mid(const INTERVAL& x){
return (x.upp+x.low)/2;
}
REAL mag(const INTERVAL& x){
return maximum(abs(x.upp),abs(x.low));
}
REAL mig(const INTERVAL& x){
return maximum(REAL(0),x.low)-minimum(REAL(0),x.upp);
}
INTERVAL fabs(const INTERVAL& x){
return INTERVAL(maximum(x.low,REAL(0))-minimum(x.upp,REAL(0)),
maximum(abs(x.low),abs(x.upp)));
}
INTERVAL exp(const INTERVAL& x){
// exp is monotonic increasing, so the following is sufficient:
return INTERVAL(exp(x.low),exp(x.upp));
}
INTERVAL log(const INTERVAL& x){
// log is monotonic increasing, so the following is sufficient:
return INTERVAL(log(x.low),log(x.upp));
}
INTERVAL sin(const INTERVAL& x){
// first, using lazy booleans, we do a multivalued test
// whether the interval width is definitely at least 2*pi.
int test=choose( x.upp-x.low >= 2*pi(),
x.upp-x.low < 3*pi());
// if the width is at least 2*pi, return the closed interval [-1,1]
if ( test == 1 ) return INTERVAL(REAL(-1), REAL(1));
// now we have a width of at most 3*pi,
// and we do a range reduction
REAL inf_reduced=modulo(x.low,2*pi());
REAL sup_reduced=x.upp- (x.low-inf_reduced);
// now we have -2*pi <= inf_reduced<= sup_reduced <= 5*pi
// with a difference between the values of at most 3*pi
// we could estimate which odd multiples of pi/2 lie between the
// borders of the reduced interval, but for simplicity here I try all
// 7 possibilities (it was easier using copy and paste...)
// the following values are either
// inf_reduced, or
// sup_reduced, or
// the multiple of pi/2, in case it lies between the two values
REAL p1= maximum(inf_reduced,minimum(sup_reduced,-3*pi()/2));
REAL p2= maximum(inf_reduced,minimum(sup_reduced, -pi()/2));
REAL p3= maximum(inf_reduced,minimum(sup_reduced, pi()/2));
REAL p4= maximum(inf_reduced,minimum(sup_reduced, 3*pi()/2));
REAL p5= maximum(inf_reduced,minimum(sup_reduced, 5*pi()/2));
REAL p6= maximum(inf_reduced,minimum(sup_reduced, 7*pi()/2));
REAL p7= maximum(inf_reduced,minimum(sup_reduced, 9*pi()/2));
REAL s1=sin(p1);
REAL s2=sin(p2);
REAL s3=sin(p3);
REAL s4=sin(p4);
REAL s5=sin(p5);
REAL s6=sin(p6);
REAL s7=sin(p7);
REAL inf_min=minimum(sin(inf_reduced),sin(sup_reduced));
inf_min=minimum(inf_min,s1);
inf_min=minimum(inf_min,s2);
inf_min=minimum(inf_min,s3);
inf_min=minimum(inf_min,s4);
inf_min=minimum(inf_min,s5);
inf_min=minimum(inf_min,s6);
inf_min=minimum(inf_min,s7);
REAL sup_min=maximum(sin(inf_reduced),sin(sup_reduced));
sup_min=maximum(sup_min,s1);
sup_min=maximum(sup_min,s2);
sup_min=maximum(sup_min,s3);
sup_min=maximum(sup_min,s4);
sup_min=maximum(sup_min,s5);
sup_min=maximum(sup_min,s6);
sup_min=maximum(sup_min,s7);
return INTERVAL(inf_min,sup_min);
}
INTERVAL cos(const INTERVAL& x){
// using lazy booleans, we do a multivalued test whether
// the interval width is definitely at least 2*pi.
int test=choose( x.upp-x.low >= 2*pi(),
x.upp-x.low < 3*pi());
// if the width is at least 2*pi, return the closed interval [-1,1]
if ( test == 1 ) return INTERVAL(REAL(-1), REAL(1));
// now we have a width of at most 3*pi
// we do a range reduction
REAL inf_reduced=modulo(x.low,2*pi());
REAL sup_reduced=x.upp- (x.low-inf_reduced);
// now we have -2*pi <= inf_reduced<= sup_reduced <= 5*pi
// with a difference between the values of at most 3*pi
// now we could estimate which multiples of pi lie between the
// borders of the reduced interval, but for simplicity here I try all
// 8 possibilities (it was easier using copy and paste...)
// the following values are either
// inf_reduced, or
// sup_reduced, or
// a multiple of pi, in case it lies between the two values
REAL p1= maximum(inf_reduced,minimum(sup_reduced,-2*pi()));
REAL p2= maximum(inf_reduced,minimum(sup_reduced, -pi()));
REAL p3= maximum(inf_reduced,minimum(sup_reduced,REAL(0.0)));
REAL p4= maximum(inf_reduced,minimum(sup_reduced, pi()));
REAL p5= maximum(inf_reduced,minimum(sup_reduced, 2*pi()));
REAL p6= maximum(inf_reduced,minimum(sup_reduced, 3*pi()));
REAL p7= maximum(inf_reduced,minimum(sup_reduced, 4*pi()));
REAL s1=cos(p1);
REAL s2=cos(p2);
REAL s3=cos(p3);
REAL s4=cos(p4);
REAL s5=cos(p5);
REAL s6=cos(p6);
REAL s7=cos(p7);
REAL inf_min=minimum(cos(inf_reduced),cos(sup_reduced));
inf_min=minimum(inf_min,s1);
inf_min=minimum(inf_min,s2);
inf_min=minimum(inf_min,s3);
inf_min=minimum(inf_min,s4);
inf_min=minimum(inf_min,s5);
inf_min=minimum(inf_min,s6);
inf_min=minimum(inf_min,s7);
REAL sup_min=maximum(cos(inf_reduced),cos(sup_reduced));
sup_min=maximum(sup_min,s1);
sup_min=maximum(sup_min,s2);
sup_min=maximum(sup_min,s3);
sup_min=maximum(sup_min,s4);
sup_min=maximum(sup_min,s5);
sup_min=maximum(sup_min,s6);
sup_min=maximum(sup_min,s7);
return INTERVAL(inf_min,sup_min);
}
INTERVAL tan(const INTERVAL& x){
// If there is no odd multiple of pi/2 between the borders of
// the interval x, then the monotonicity of tan() is sufficient
// for the following formula to give the correct result:
return INTERVAL(tan(x.low),tan(x.upp));
// If on the other hand, there is such a multiple, then
// tan(x) is no proper interval.
// We choose to stay with the upper formula in this case.
// Another possibility would be to throw an exception.
}
INTERVAL asin(const INTERVAL& x){
return INTERVAL (asin(maximum(x.low,REAL(-1))),
asin(minimum(x.upp,REAL(1))));
}
INTERVAL acos(const INTERVAL& x){
return INTERVAL (acos(minimum(x.upp,REAL(1))),
acos(maximum(x.low,REAL(-1))));
}
INTERVAL atan(const INTERVAL& x){
return INTERVAL (atan(x.low),atan(x.upp));
}
LAZY_BOOLEAN superset (const INTERVAL& x,
const INTERVAL& y){
return ( (x.low <= y.low)&&(x.upp >= y.upp) );
}
LAZY_BOOLEAN proper_superset (const INTERVAL& x, const INTERVAL& y){
return superset(x,y); }
LAZY_BOOLEAN subset (const INTERVAL& x, const INTERVAL& y){
return superset(y,x); }
LAZY_BOOLEAN proper_subset (const INTERVAL& x, const INTERVAL& y){
return superset(y,x); }
LAZY_BOOLEAN in_interior (const INTERVAL& x, const INTERVAL& y){
return superset(y,x); }
LAZY_BOOLEAN disjoint (const INTERVAL& x, const INTERVAL& y){
return ( (x.low > y.upp) || (y.low > x.upp));}
LAZY_BOOLEAN in (const REAL& x, const INTERVAL& y){
return ( (y.low <= x) && (x <= y.upp) );}
INTERVAL interval_hull (const INTERVAL& x, const INTERVAL& y){
return INTERVAL(minimum(x.low,y.low),maximum(x.upp,x.upp));}
INTERVAL intersect (const INTERVAL& x, const INTERVAL& y){
return INTERVAL(maximum(x.low,y.low),minimum(x.upp,x.upp));}
} // namespace iRRAM
<|endoftext|>
|
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/* -------------------------------------------------------------------------
ATS
License: see $ATS_DIR/COPYRIGHT
Author: Ethan Coon
Interface for EWC, a helper class that does projections and preconditioners in
energy/water-content space instead of temperature/pressure space.
------------------------------------------------------------------------- */
#include "FieldEvaluator.hh"
#include "ewc_model.hh"
#include "mpc_delegate_ewc.hh"
namespace Amanzi {
#define DEBUG_FLAG 1
// -----------------------------------------------------------------------------
// Constructor
// -----------------------------------------------------------------------------
MPCDelegateEWC::MPCDelegateEWC(Teuchos::ParameterList& plist) :
plist_(Teuchos::rcpFromRef(plist)) {
// set up the VerboseObject
std::string name = plist_->get<std::string>("PK name")+std::string(" EWC");
vo_ = Teuchos::rcp(new VerboseObject(name, *plist_));
}
// -----------------------------------------------------------------------------
// Allocate any data or models required.
// -----------------------------------------------------------------------------
void MPCDelegateEWC::setup(const Teuchos::Ptr<State>& S) {
// Verbosity
std::string name = plist_->get<std::string>("PK name")+std::string(" EWC");
// Get the mesh
Key domain = plist_->get<std::string>("domain key", "");
if (domain.size() != 0) {
mesh_ = S->GetMesh(domain);
} else {
mesh_ = S->GetMesh("domain");
}
// set up a debugger
db_ = Teuchos::rcp(new Debugger(mesh_, name, *plist_));
// Process the parameter list for data Keys
if (domain.size() > 0) domain.append(1, '_');
pres_key_ = plist_->get<std::string>("pressure key", domain+std::string("pressure"));
temp_key_ = plist_->get<std::string>("temperature key",
domain+std::string("temperature"));
e_key_ = plist_->get<std::string>("energy key", domain+std::string("energy"));
wc_key_ = plist_->get<std::string>("water content key",
domain+std::string("water_content"));
cv_key_ = plist_->get<std::string>("cell volume key",
domain+std::string("cell_volume"));
// Process the parameter list for methods
std::string precon_string = plist_->get<std::string>("preconditioner type", "none");
if (precon_string == "none") {
precon_type_ = PRECON_NONE;
} else if (precon_string == "ewc") {
precon_type_ = PRECON_EWC;
ASSERT(0);
} else if (precon_string == "smart ewc") {
precon_type_ = PRECON_SMART_EWC;
}
// select the method used for nonlinear prediction
std::string predictor_string = plist_->get<std::string>("predictor type", "none");
if (predictor_string == "none") {
predictor_type_ = PREDICTOR_NONE;
} else if (predictor_string == "ewc") {
predictor_type_ = PREDICTOR_EWC;
ASSERT(0);
} else if (predictor_string == "smart ewc") {
predictor_type_ = PREDICTOR_SMART_EWC;
}
// Smart EWC uses a heuristic to guess when we need the EWC instead of using
// it blindly.
if (predictor_type_ == PREDICTOR_SMART_EWC || precon_type_ == PRECON_SMART_EWC) {
if (plist_->isParameter("cusp distance in T")) {
cusp_size_T_freezing_ = plist_->get<double>("cusp distance in T");
cusp_size_T_thawing_ = cusp_size_T_freezing_;
} else {
cusp_size_T_freezing_ = plist_->get<double>("cusp distance in T, freezing", 0.005);
cusp_size_T_thawing_ = plist_->get<double>("cusp distance in T, thawing", 0.005);
}
}
}
// -----------------------------------------------------------------------------
// Initialize any data required in setup.
// -----------------------------------------------------------------------------
void MPCDelegateEWC::initialize(const Teuchos::Ptr<State>& S) {
// Create and initialize old stored data for previous steps.
if (predictor_type_ == PREDICTOR_EWC || predictor_type_ == PREDICTOR_SMART_EWC) {
const Epetra_MultiVector& wc = *S->GetFieldData(wc_key_)
->ViewComponent("cell",false);
const Epetra_MultiVector& e = *S->GetFieldData(e_key_)
->ViewComponent("cell",false);
wc_prev2_ = Teuchos::rcp(new Epetra_MultiVector(wc));
e_prev2_ = Teuchos::rcp(new Epetra_MultiVector(e));
wc_prev2_->PutScalar(0.);
e_prev2_->PutScalar(0.);
time_prev2_ = S->time();
}
// initialize the Jacobian
if (precon_type_ == PRECON_EWC || precon_type_ == PRECON_SMART_EWC) {
int ncells = mesh_->num_entities(AmanziMesh::CELL, AmanziMesh::OWNED);
jac_.resize(ncells, WhetStone::Tensor(2,2));
}
// initialize the model, which grabs all needed models from state
model_->InitializeModel(S);
}
// -----------------------------------------------------------------------------
// Set state pointers.
// -----------------------------------------------------------------------------
void MPCDelegateEWC::set_states(const Teuchos::RCP<const State>& S,
const Teuchos::RCP<State>& S_inter,
const Teuchos::RCP<State>& S_next) {
S_= S;
S_inter_ = S_inter;
S_next_ = S_next;
}
// -----------------------------------------------------------------------------
// Save info from previous iterations if needed.
// -----------------------------------------------------------------------------
void MPCDelegateEWC::commit_state(double dt, const Teuchos::RCP<State>& S) {
if ((predictor_type_ == PREDICTOR_EWC || predictor_type_ == PREDICTOR_SMART_EWC)
&& S_inter_ != Teuchos::null) {
// stash water content and energy in S_work.
*wc_prev2_ = *S_inter_->GetFieldData(wc_key_)->ViewComponent("cell",false);
*e_prev2_ = *S_inter_->GetFieldData(e_key_)->ViewComponent("cell",false);
time_prev2_ = S_inter_->time();
}
}
// -----------------------------------------------------------------------------
// Modify the prediction from linearization of the time integration.
// -----------------------------------------------------------------------------
bool MPCDelegateEWC::ModifyPredictor(double h, Teuchos::RCP<TreeVector> up) {
bool modified = false;
double dt_prev = S_inter_->time() - time_prev2_;
if (predictor_type_ == PREDICTOR_EWC) {
if (dt_prev > 0.) {
ASSERT(0);
// modified = modify_predictor_ewc_(h,up);
}
} else if (predictor_type_ == PREDICTOR_SMART_EWC) {
if (dt_prev > 0.) {
modified = modify_predictor_smart_ewc_(h,up);
}
}
return modified;
}
// -----------------------------------------------------------------------------
// Update of the preconditioner
// -----------------------------------------------------------------------------
void MPCDelegateEWC::UpdatePreconditioner(double t, Teuchos::RCP<const TreeVector> up, double h) {
if (precon_type_ == PRECON_EWC || precon_type_ == PRECON_SMART_EWC) {
update_precon_ewc_(t,up,h);
}
}
// -----------------------------------------------------------------------------
// Application of the preconditioner.
// -----------------------------------------------------------------------------
void MPCDelegateEWC::ApplyPreconditioner(Teuchos::RCP<const TreeVector> u, Teuchos::RCP<TreeVector> Pu) {
if ((precon_type_ == PRECON_EWC) || (precon_type_ == PRECON_SMART_EWC)) {
precon_ewc_(u,Pu);
}
}
void MPCDelegateEWC::update_precon_ewc_(double t, Teuchos::RCP<const TreeVector> up, double h) {
Key dedT_key = std::string("d")+e_key_+std::string("_d")+temp_key_;
S_next_->GetFieldEvaluator(e_key_)
->HasFieldDerivativeChanged(S_next_.ptr(), "ewc", temp_key_);
const Epetra_MultiVector& dedT = *S_next_->GetFieldData(dedT_key)
->ViewComponent("cell",false);
Key dedp_key = std::string("d")+e_key_+std::string("_d")+pres_key_;
S_next_->GetFieldEvaluator(e_key_)
->HasFieldDerivativeChanged(S_next_.ptr(), "ewc", pres_key_);
const Epetra_MultiVector& dedp = *S_next_->GetFieldData(dedp_key)
->ViewComponent("cell",false);
Key dwcdT_key = std::string("d")+wc_key_+std::string("_d")+temp_key_;
S_next_->GetFieldEvaluator(wc_key_)
->HasFieldDerivativeChanged(S_next_.ptr(), "ewc", temp_key_);
const Epetra_MultiVector& dwcdT = *S_next_->GetFieldData(dwcdT_key)
->ViewComponent("cell",false);
Key dwcdp_key = std::string("d")+wc_key_+std::string("_d")+pres_key_;
S_next_->GetFieldEvaluator(wc_key_)
->HasFieldDerivativeChanged(S_next_.ptr(), "ewc", pres_key_);
const Epetra_MultiVector& dwcdp = *S_next_->GetFieldData(dwcdp_key)
->ViewComponent("cell",false);
int ncells = mesh_->num_entities(AmanziMesh::CELL, AmanziMesh::OWNED);
for (int c=0; c!=ncells; ++c) {
jac_[c](0,0) = dwcdp[0][c];
jac_[c](0,1) = dwcdT[0][c];
jac_[c](1,0) = dedp[0][c];
jac_[c](1,1) = dedT[0][c];
}
}
} // namespace
<commit_msg>potential bug in input spec parsing for predictor with incorrect name<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/* -------------------------------------------------------------------------
ATS
License: see $ATS_DIR/COPYRIGHT
Author: Ethan Coon
Interface for EWC, a helper class that does projections and preconditioners in
energy/water-content space instead of temperature/pressure space.
------------------------------------------------------------------------- */
#include "FieldEvaluator.hh"
#include "ewc_model.hh"
#include "mpc_delegate_ewc.hh"
namespace Amanzi {
#define DEBUG_FLAG 1
// -----------------------------------------------------------------------------
// Constructor
// -----------------------------------------------------------------------------
MPCDelegateEWC::MPCDelegateEWC(Teuchos::ParameterList& plist) :
plist_(Teuchos::rcpFromRef(plist)) {
// set up the VerboseObject
std::string name = plist_->get<std::string>("PK name")+std::string(" EWC");
vo_ = Teuchos::rcp(new VerboseObject(name, *plist_));
}
// -----------------------------------------------------------------------------
// Allocate any data or models required.
// -----------------------------------------------------------------------------
void MPCDelegateEWC::setup(const Teuchos::Ptr<State>& S) {
// Verbosity
std::string name = plist_->get<std::string>("PK name")+std::string(" EWC");
// Get the mesh
Key domain = plist_->get<std::string>("domain key", "");
if (domain.size() != 0) {
mesh_ = S->GetMesh(domain);
} else {
mesh_ = S->GetMesh("domain");
}
// set up a debugger
db_ = Teuchos::rcp(new Debugger(mesh_, name, *plist_));
// Process the parameter list for data Keys
if (domain.size() > 0) domain.append(1, '_');
pres_key_ = plist_->get<std::string>("pressure key", domain+std::string("pressure"));
temp_key_ = plist_->get<std::string>("temperature key",
domain+std::string("temperature"));
e_key_ = plist_->get<std::string>("energy key", domain+std::string("energy"));
wc_key_ = plist_->get<std::string>("water content key",
domain+std::string("water_content"));
cv_key_ = plist_->get<std::string>("cell volume key",
domain+std::string("cell_volume"));
// Process the parameter list for methods
std::string precon_string = plist_->get<std::string>("preconditioner type", "none");
if (precon_string == "none") {
precon_type_ = PRECON_NONE;
} else if (precon_string == "ewc") {
precon_type_ = PRECON_EWC;
ASSERT(0);
} else if (precon_string == "smart ewc") {
precon_type_ = PRECON_SMART_EWC;
}
// select the method used for nonlinear prediction
std::string predictor_string = plist_->get<std::string>("predictor type", "none");
if (predictor_string == "none") {
predictor_type_ = PREDICTOR_NONE;
} else if (predictor_string == "ewc") {
predictor_type_ = PREDICTOR_EWC;
ASSERT(0);
} else if (predictor_string == "smart ewc") {
predictor_type_ = PREDICTOR_SMART_EWC;
} else {
Errors::Message message;
message << "EWC Delegate: invalid predictor string: \"" << predictor_string
<< "\", valid are \"none\", \"ewc\", \"smart ewc\"";
Exceptions::amanzi_throw(message);
}
// Smart EWC uses a heuristic to guess when we need the EWC instead of using
// it blindly.
if (predictor_type_ == PREDICTOR_SMART_EWC || precon_type_ == PRECON_SMART_EWC) {
if (plist_->isParameter("cusp distance in T")) {
cusp_size_T_freezing_ = plist_->get<double>("cusp distance in T");
cusp_size_T_thawing_ = cusp_size_T_freezing_;
} else {
cusp_size_T_freezing_ = plist_->get<double>("cusp distance in T, freezing", 0.005);
cusp_size_T_thawing_ = plist_->get<double>("cusp distance in T, thawing", 0.005);
}
}
}
// -----------------------------------------------------------------------------
// Initialize any data required in setup.
// -----------------------------------------------------------------------------
void MPCDelegateEWC::initialize(const Teuchos::Ptr<State>& S) {
// Create and initialize old stored data for previous steps.
if (predictor_type_ == PREDICTOR_EWC || predictor_type_ == PREDICTOR_SMART_EWC) {
const Epetra_MultiVector& wc = *S->GetFieldData(wc_key_)
->ViewComponent("cell",false);
const Epetra_MultiVector& e = *S->GetFieldData(e_key_)
->ViewComponent("cell",false);
wc_prev2_ = Teuchos::rcp(new Epetra_MultiVector(wc));
e_prev2_ = Teuchos::rcp(new Epetra_MultiVector(e));
wc_prev2_->PutScalar(0.);
e_prev2_->PutScalar(0.);
time_prev2_ = S->time();
}
// initialize the Jacobian
if (precon_type_ == PRECON_EWC || precon_type_ == PRECON_SMART_EWC) {
int ncells = mesh_->num_entities(AmanziMesh::CELL, AmanziMesh::OWNED);
jac_.resize(ncells, WhetStone::Tensor(2,2));
}
// initialize the model, which grabs all needed models from state
model_->InitializeModel(S);
}
// -----------------------------------------------------------------------------
// Set state pointers.
// -----------------------------------------------------------------------------
void MPCDelegateEWC::set_states(const Teuchos::RCP<const State>& S,
const Teuchos::RCP<State>& S_inter,
const Teuchos::RCP<State>& S_next) {
S_= S;
S_inter_ = S_inter;
S_next_ = S_next;
}
// -----------------------------------------------------------------------------
// Save info from previous iterations if needed.
// -----------------------------------------------------------------------------
void MPCDelegateEWC::commit_state(double dt, const Teuchos::RCP<State>& S) {
if ((predictor_type_ == PREDICTOR_EWC || predictor_type_ == PREDICTOR_SMART_EWC)
&& S_inter_ != Teuchos::null) {
// stash water content and energy in S_work.
*wc_prev2_ = *S_inter_->GetFieldData(wc_key_)->ViewComponent("cell",false);
*e_prev2_ = *S_inter_->GetFieldData(e_key_)->ViewComponent("cell",false);
time_prev2_ = S_inter_->time();
}
}
// -----------------------------------------------------------------------------
// Modify the prediction from linearization of the time integration.
// -----------------------------------------------------------------------------
bool MPCDelegateEWC::ModifyPredictor(double h, Teuchos::RCP<TreeVector> up) {
bool modified = false;
double dt_prev = S_inter_->time() - time_prev2_;
if (predictor_type_ == PREDICTOR_EWC) {
if (dt_prev > 0.) {
ASSERT(0);
// modified = modify_predictor_ewc_(h,up);
}
} else if (predictor_type_ == PREDICTOR_SMART_EWC) {
if (dt_prev > 0.) {
modified = modify_predictor_smart_ewc_(h,up);
}
}
return modified;
}
// -----------------------------------------------------------------------------
// Update of the preconditioner
// -----------------------------------------------------------------------------
void MPCDelegateEWC::UpdatePreconditioner(double t, Teuchos::RCP<const TreeVector> up, double h) {
if (precon_type_ == PRECON_EWC || precon_type_ == PRECON_SMART_EWC) {
update_precon_ewc_(t,up,h);
}
}
// -----------------------------------------------------------------------------
// Application of the preconditioner.
// -----------------------------------------------------------------------------
void MPCDelegateEWC::ApplyPreconditioner(Teuchos::RCP<const TreeVector> u, Teuchos::RCP<TreeVector> Pu) {
if ((precon_type_ == PRECON_EWC) || (precon_type_ == PRECON_SMART_EWC)) {
precon_ewc_(u,Pu);
}
}
void MPCDelegateEWC::update_precon_ewc_(double t, Teuchos::RCP<const TreeVector> up, double h) {
Key dedT_key = std::string("d")+e_key_+std::string("_d")+temp_key_;
S_next_->GetFieldEvaluator(e_key_)
->HasFieldDerivativeChanged(S_next_.ptr(), "ewc", temp_key_);
const Epetra_MultiVector& dedT = *S_next_->GetFieldData(dedT_key)
->ViewComponent("cell",false);
Key dedp_key = std::string("d")+e_key_+std::string("_d")+pres_key_;
S_next_->GetFieldEvaluator(e_key_)
->HasFieldDerivativeChanged(S_next_.ptr(), "ewc", pres_key_);
const Epetra_MultiVector& dedp = *S_next_->GetFieldData(dedp_key)
->ViewComponent("cell",false);
Key dwcdT_key = std::string("d")+wc_key_+std::string("_d")+temp_key_;
S_next_->GetFieldEvaluator(wc_key_)
->HasFieldDerivativeChanged(S_next_.ptr(), "ewc", temp_key_);
const Epetra_MultiVector& dwcdT = *S_next_->GetFieldData(dwcdT_key)
->ViewComponent("cell",false);
Key dwcdp_key = std::string("d")+wc_key_+std::string("_d")+pres_key_;
S_next_->GetFieldEvaluator(wc_key_)
->HasFieldDerivativeChanged(S_next_.ptr(), "ewc", pres_key_);
const Epetra_MultiVector& dwcdp = *S_next_->GetFieldData(dwcdp_key)
->ViewComponent("cell",false);
int ncells = mesh_->num_entities(AmanziMesh::CELL, AmanziMesh::OWNED);
for (int c=0; c!=ncells; ++c) {
jac_[c](0,0) = dwcdp[0][c];
jac_[c](0,1) = dwcdT[0][c];
jac_[c](1,0) = dedp[0][c];
jac_[c](1,1) = dedT[0][c];
}
}
} // namespace
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.